Sql Injection Cheat Sheet Github



This page intends to provide quick basic .NET security tips for developers.

The .NET Framework

The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.

Updating the Framework

PWK course & the OSCP Exam Cheatsheet 6 minute read Forked from sinfulz “JustTryHarder” is his “cheat sheet which will aid you through the PWK course & the OSCP Exam.” So here: “ JustTryHarder. JustTryHarder, a cheat sheet which will aid you through the PWK course & the OSCP Exam. February 28th, 2021 sql injection cheat sheet github.

The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at Windows Update or from the Windows Update program on a Windows computer.

Individual frameworks can be kept up to date using NuGet. As Visual Studio prompts for updates, build it into your lifecycle.

Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.

  • SQL injection is a type of vulnerability that software developers aim to avoid. In this guide, you’ll learn: what SQL injection is examples of SQL injection how to prevent SQL injection Let&#.
  • SQL-Injection-cheat-sheet First try to figure out the vulnerable parameter NOTE: If it's a GET request don't forget to url encode the characters. Param=' - try to get error param=' - try to get error param=' or 1=1 - try if it works param=' or 1=0 - check if it returns nothing param=' and 1=1 - check.
  • GitHub Gist: instantly share code, notes, and snippets. GitHub Gist: instantly share code, notes, and snippets. 0x01 basic sqlinjection cheat sheet 0x01 basic: Check the current database version: VERSION @@ VERSION. Use sql injection can import export.

The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.

Data Access

  • Use Parameterized SQL commands for all data access, without exception.
  • Do not use SqlCommand with a string parameter made up of a concatenated SQL String.
  • Whitelist allowable values coming from the user. Use enums, TryParse or lookup values to assure that the data coming from the user is as expected.
    • Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. Enum.IsDefined can validate whether the input value is valid within the list of defined constants.
  • Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.
  • Use of the Entity Framework is a very effective SQL injection prevention mechanism. Remember that building your own ad hoc queries in Entity Framework is just as susceptible to SQLi as a plain SQL query.
  • When using SQL Server, prefer integrated authentication over SQL authentication.
  • Use Always Encrypted where possible for sensitive data (SQL Server 2016 and SQL Azure),

Encryption

  • Never, ever write your own encryption.
  • Use the Windows Data Protection API (DPAPI) for secure local storage of sensitive data.
  • Use a strong hash algorithm.
    • In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is System.Security.Cryptography.SHA512.
    • In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as System.Security.Cryptography.Rfc2898DeriveBytes.aspx).
    • In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2 which has several significant advantages over Rfc2898DeriveBytes.
    • When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.
  • Make sure your application or protocol can easily support a future change of cryptographic algorithms.
  • Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.

General

  • Lock down the config file.
    • Remove all aspects of configuration that are not in use.
    • Encrypt sensitive parts of the web.config using aspnet_regiis -pe (command line help)).
  • For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.

ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.

  • Always use HTTPS.
  • Enable requireSSL on cookies and form elements and HttpOnly on cookies in the web.config.
  • Implement customErrors).
  • Make sure tracing is turned off.
  • While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the ViewStateUserKey:

If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.

  • Consider HSTS in IIS. See here for the procedure.
  • This is a recommended web.config setup that handles HSTS among other things.
  • Remove the version header.
  • Also remove the Server header.

HTTP validation and encoding

  • Do not disable validateRequest in the web.config or the page setup. This value enables limited XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting. Complete request validation is recommended in addition to the built in protections.
  • The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.
  • Whitelist allowable values anytime user input is accepted.
  • Validate the URI format using Uri.IsWellFormedUriString.

Forms authentication

  • Use cookies for persistence when possible. Cookieless auth will default to UseDeviceProfile.
  • Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.
  • Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.
  • If HTTPS is not used, slidingExpiration should be disabled. Consider disabling slidingExpiration even with HTTPS.
  • Always implement proper access controls.
    • Compare user provided username with User.Identity.Name.
    • Check roles against User.Identity.IsInRole.
  • Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses ASP.NET Identity instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP Password Storage Cheat Sheet for more information.
  • Explicitly authorize resource requests.
  • Leverage role based authorization using User.Identity.IsInRole.
Free

ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model.

The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years.

This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.

A1 SQL Injection

DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.

DO: Use parameterized queries where a direct sql query must be used.

e.g. In entity frameworks:

DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql).

NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.

e.g

DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account

A2 Weak Account management

Ensure cookies are sent via httpOnly:

Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:

See here for full startup code snippet

Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:

Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.

DO NOT: Roll your own authentication or session management, use the one provided by .Net

DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration.

Sql Injection Cheat Sheet Github

The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested.

A3 Cross Site Scripting

DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists

You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:

Install-Package AntiXSS

Then set in config:

DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.

DO: Enable a Content Security Policy, this will prevent your pages from accessing assets it should not be able to access (e.g. a malicious script):

A4 Insecure Direct object references

When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there

A5 Security Misconfiguration

Ensure debug and trace are off in production. This can be enforced using web.config transforms:

DO NOT: Use default passwords

DO: (When using TLS) Redirect a request made over Http to https: In Global.asax.cs:

A6 Sensitive data exposure

DO NOT: Store encrypted passwords.

DO: Use a strong hash to store password credentials. Use Argon2, PBKDF2, BCrypt or SCrypt with at least 8000 iterations and a strong key.

DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy.

DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.

DO: Use TLS 1.2 for your entire site. Get a free certificate LetsEncrypt.org.

DO NOT: Allow SSL, this is now obsolete.

DO: Have a strong TLS policy (see SSL Best Practises), use TLS 1.2 wherever possible. Then check the configuration using SSL Test or TestSSL.

DO: Ensure headers are not disclosing information about your application. See HttpHeaders.cs , Dionach StripHeaders or disable via web.config:

A7 Missing function level access control

DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:

or better yet, at controller level:

You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)

DO: Send the anti-forgery token with every Post/Put request:

Then validate it at the method or preferably the controller level:

Make sure the tokens are removed completely for invalidation on logout.

NB: You will need to attach the anti-forgery token to Ajax requests.

After .NET Core 2.0 it is possible to automatically generate and verify the antiforgery token. Forms must have the requisite helper as seen here:

And then add the [AutoValidateAntiforgeryToken] attribute to the action result.

A9 Using components with known vulnerabilities

DO: Keep the .Net framework updated with the latest patches

DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities.

DO: Run the OWASP Dependency Checker against your application as part of your build process and act on any high level vulnerabilities.

A10 Unvalidated redirects and forwards

A protection against this was introduced in Mvc 3 template. Here is the code:

Other advice:

  • Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security (HSTS) headers. Full details here
  • Protect against a man in the middle attack for a user who has never been to your site before. Register for HSTS preload
  • Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.

More information:

For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to Security Essentials Baseline project

  • Work within the constraints of Internet Zone security for your application.
  • Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.
  • Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.
  • Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.

WCF Guidance

  • Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.
  • Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.
  • Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.
  • Test your WCF implementation with a fuzzer like the ZAP.

Bill Sempf - bill.sempf@owasp.org

Troy Hunt - troyhunt@hotmail.com

Jeremy Long - jeremy.long@owasp.org

Shane Murnion

John Staveley

Steve Bamelis

Xander Sherry Download zcx driver.

Sam Ferree

Studying from various sources for Offensive-Security OSCP. I would like to make my own cheatsheet for the exam.

Enumeration

Enumeration is most important part. All finding should be noted for future reference. Without enumeration, we will have hard time to exploit the target.

DNS Enumeration

Forward Lookup brute force to find ip addres of host:

Reverse Lookup to find hostname:

Zone transfer and enumeration using Kali tools

Enumerate using Nmap

Port Scanning and Service Enumeration

Filter all open ports for nmap script scanning:


Automated Enumeration Script

Download: https://github.com/21y4d/nmapAutomator

Other Enumeration Command

Pentesting Specific Service

Port 21(FTP) Open

Scan FTP with Nmap

Login and Upload backdoor

Port 22(SSH) Open

Sql Injection Cheat Sheet Github

Banner Grab

Quick Brute Forces

Port 25(SMTP) Open

Enumerate Using netcat. Used for username Enumeration. Useful for brute forcing

Port 53(DNS) Open

Enumerating with nslookup,dig and gobuster:

Other tools to try:

Port 79(Finger) Open

If finger service is running, it is possible to enumerate username, and useful for brute force purpose.

Port 80/443(HTTP/HTTPS) Open

What to check?

  1. Manually Browse Common Files.
  2. Identify Technology. Search Vulnerability with identified info.
  3. Gather information from SSL.
  4. Check if it has any proxy related vulnerability.
  5. Directory, Sensitive files brute force and spider any discovered directory.
  6. May need to find out the hidden parameters.
  7. Find all inputs point.
  8. Find subdomains using dnsrecon or dnsenum.

View sources, and also Browse Manually

Identify Technology with whatWeb

Scan with Nikto

If any CMS identified

Brute Force Directory and Files

  1. First use small common wordlist
  2. Then Big Word list
  3. Try with CMS related wordlist

Word list File to brute forces:

Brute force with Gobuster

Password brute Forcing(wordpress example)

LFI and RFI

If the URL parameter has file name, we can try to vulnerability for LFI/RFI. We should request invalid file and see if any error is displayed!

LFI Can execute code!

Send our malicious code using CURL or Burpsuite or even netcat:

Now execute command:

Github Sql Server

Command Execution

If found any parameters or input fields, we can try for command execution. Test Every parameters and input fields with these payload(Better to use burp suite intruder):

Reference and more payload: https://github.com/payloadbox/command-injection-payload-list

SQLi for Login Bypass

If any login page found, should be tried to bypass password check. These payload copied from: https://github.com/payloadbox/sql-injection-payload-list

CheatSheet:
MSSQL INJECTION: https://perspectiverisk.com/mssql-practical-injection-cheat-sheet/
MYSQL INJECTION: https://perspectiverisk.com/mysql-sql-injection-practical-cheat-sheet/

Exploit WebDav

If one method fail, another should be tested. If nothing work, Find different exploit!

Method 1:

Method 2:

Method 3:

Reference

File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion
SQL Injection: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection
Command Injection: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection

Port 110(POP3) Open

Found an user login information?

Port 111 (RPCINFO) Open

Connect with Null session.

Port 137,138,139 Open

Port 445(SMB) Open

Sql Injection Cheat Sheet Github

There is a big chance getting sensitive information with SMB. Need to check everything carefully!

Enumerating SMB

Connecting to share without password(Anonymous login)

Login with Password

Port 389(LDAP) Open

Port 1433(MSSQL) Open

Reference: https://book.hacktricks.xyz/pentesting/pentesting-mssql-microsoft-sql-server

Quick brute for pass “SA” password

Connect to MSSQL Server:

Enable xp_cmdshell:

Execute System Command:

Port 2049(NFS) Open

Enumerate shares

Mount shares in Local Machine

After mounting the filesystem if don’t have read/write permission, we need to edit /etc/passwd and change UUID:

Now we can write files to the target fold of the network filesystem. For example:

Port 3306(MYSQL) Open

Port 3389(RDP) Open

Connect to RDP

Brute force if a valid username found:

Add user to RDP Group

Port 5900/5800(VNC) Open

Scan with nmap

Connect from Kali

Password Attack

Sometime we need to do password guessing(We should!). For better success rate we need a good password dictionary. Also we should search for default credential online!

I have collected some Username and password for quick brute force, usually used for CTF. These list could be used to exploit weak password. Uploaded in GitHub:

Default Username: https://raw.githubusercontent.com/bytefellow/pentest/master/common-username
Default Password: https://raw.githubusercontent.com/bytefellow/pentest/master/common-password

Common password
Generate Password with cewl
Brute Forcing with Burp

If it is an web form we can brute force in intruder and match grep. Some screenshot from burp suit:

To brute force web form with the hydra, we need to grab the post data from the burp suite carefully. Otherwise, we will get false positive and waste lots of time! I tried to brute force otrs and it worked.

Brute Force With Hydra

Vulnerability and Exploitation

I believe finding vulnerability for the OSCP exam machine would be simple and easy. All enumeration previously should be noted! Version detection using and Web CMS version is most important to find exploit.

Find Vulnerability with Nmap

Using Searchsploit

Find Exploits using Google

Three kind of search should be enough to find an working exploit

Working with Public Exploits

A public exploit might be coded in python, ruby, c/c++ or any other language. Before executing the exploit:

  • Read the instruction Carefully.
  • Edit Target address, Reverse connection ip and Ports.

Working with Shell

We may get shell, after exploiting some vulnerability. Now what?

Sql

Backdoor Files in Kali

Kali already has some web shell.

Quick Shell in Different language

Here it is: http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet

Generate with metasploit

Upgrading Shell

Listening for Connection

Upgrading Shell when received connection!

Running Python http Server

Uploading Shell/File

After getting shell, we may need to upload additional files or stable backdoor.

Transfering file in Linux

Transfering file in Windows

Transfer file with impacket samba script

Piviot/Tunnel/Port Forwarding

  1. -L = Kali’s Port
  2. -R = Kali Port
  3. $ip:3306 is the port from target

Local Port Forwarding

Have SSH access with low privileges? and There are some ports open internally? Try Local Port Forwarding:

Remote Port Forwarding

No SSH Access but limited shell? Also some weird port is open? Upload plink and Try Remote port forward with plink

Connect to the the tunneled port:

Dynamic Port Forwarding(Socks4)

Dynamic Port Forwarding from victim machine(Socks Proxy):

With Dynamic Port Forwarding We can access/browse any ip range of the victim machine. We just need to configure proxychains.conf as follows:

Now we can use any application through proxychains… such as:

Port Forwarding with Plink.exe

Remote Port Forwarding using Plink. Needed When we don’t have access to specific port on on target box!

Common Issue

Correct permission for SSH Key?

Load key “id_rsa”: invalid format ?

Try Removing additional space. Also keep the public key in the same directory of private key. We may get the warning, but it should work!

Unable to negotiate with x.x.x.x … no matching key exchange method found

SSH Error:

Solutions:

Practical Exploitation

Exploiting NFS and FTP

I have done enumeration with nmapautomator. Found NFS and ProFtpd 1.3.5 is running. But no HTTP. The exploitation step was:

The network File system mounted but does not have any contents. FTP version is vulnerable. So i had to exploit it manually(https://www.exploit-db.com/exploits/36803):

Oracle Sql Injection Cheat Sheet

This way, I was able to successfully exploit the system without directly using any tools!

Exploiting Jenkins Server

Was able to login as user admin and password admin. Then I have navigated to Manage Jenkins>>Script Console and pasted this code for reverse connection:

Clicked run and got shell!

More Example: https://www.bytefellow.com/quick-initial-foothold-in-10-htb-machine/