Saturday, February 7, 2015

OS Command Injection, Path Traversal & Local File Inclusion Vulnerability - Notes

When data is passed from one component to another

Data considered "Safe" by one component may NOT be Safe for an Onward component
  • Attacker may pass crafted input which may be interpreted as commands in an Onward component
Onward component may have much more functionality, than what the application component uses.
  • Attacker can exploit this additional functionality
==============================================================================

OS Command Injection

==============================================================================
  • Vulnerability exists when >>> User supplied input is passed to system shell.
  • Attacker supplies crafted input, which is passed as parameter to shell functions like system() or exec() 
  • Commands are executed with the Privilege of the vulnerable "Application"
  • Commonly found in ADMIN interface of an - Application Server, firewall, router, printer

Crafted Input usually contains Shell Meta-characters

  • Pipe Character "|" redirects output from one process to input of another.
  • Pipe Character "|" can be used for chaining multiple commands
  • Semicolon ";" is a command separator.
  • Ampersand "&" is used as command separator to batch multiple commands
  • Command1 & Command 2 , second commands runs regardless of success of first
  • Commands1 && Command2 , second command runs only when first is successful
  • Command1 || Command 2, second commands runs only when second fails
  • Placing a command between BackTicks  Eg. `command` causes the Shell to execute it and replace the `command`  with the results of this command. 
  • Command1 (`command2`) will evaluate to  Command1 (resultofcommand2)

Checking for OS Command Injection Vulnerability
Most reliable way is to execute a function which causes a time delay.
  • ||   ping - i   30  127.0.0.1  ||
  • ||   ping - n   30  127.0.0.1  ||
  • Try all the MetaCharacters     |   `  &   ;    %0A    ||    &&
If time delay occurs then application may be vulnerable to command Injection

If you are not able to retrieve the results of your command, you have two options
  • Output the results into  \wwwroot\output.txt file and use browser to view it
  • Use TFTP to copy tools up to the server, then use telnet to create a reverse shell and Use mail command to send output to yourself via SMTP
Prevention of OS Command Injection Vulnerability

1. Avoid calling OS commands directly
  • For a web application, Built-in APIs are a very good alternative to OS Commands
  • Built-in API cannot be manipulated to perform tasks other than those it is intended to do.
2. If use of OS commands is unavoidable,
  • WhiteList approach should be used. Allow only alphabets and numbers.
  • Meta-characters and white-spaces should be rejected. 
  • Additionally, use Command API like "Runtime.exec" in Java & "Process.Start" in ASP.NET which launch a specific process via (name, command line parameters) instead of directly passing the input to a shell interpreter. 
Note: Command APIs like - Runtime.exec tokenizes the input into an array of words, then executes the first word in the array as command with the rest of the words as parameters. The risk in using "Runtime.exec" depends on the command being used in source code. If "cmd" is used as command, then there this poses risk of OS Command Injection. Another risk associated with Runtime.exec is that of the user entering an unintended parameter.
3. Applications should use minimum privilege accounts or use multiple low privilege accounts.

Following functions are exploited to carryout OS command Injection

PHP    - exec,  eval,   passthru,    proc_open,   shell_exec,   system,    backtick operator (`)
C/C++ - system,    execlp,   execvp,    ShellExecute,    _wsystem
JAVA  - Runtime.exec
==============================================================================

Path Traversal Vulnerability

==============================================================================
Vulnerability exists when user-controllable data is used to access files & directories in an unsafe manner.
Attacker supplies crafted input which may allow him unintended read or write access to files.

Consequences/Risk : May allow an attacker to read or overwrite sensitive files
  • Password files for OS and Application
  • Server and Application Configuration files
  • Include files containing database credentials
  • MySQL database files or XML files
  • Source code files
  • Log files containing usernames or session tokens
If you get write access then, it can ultimately be used for arbitrary command execution.
  • Create scripts in startup folder
  • Write script in web directory & execute by calling in browser
Preventing Path Traversal Vulnerability

Most effective Technique 
  • Avoid passing user submitted data to filesystem API.
  • Files which do not need to be access controlled can be placed in webroot & accessed via URL.
If it is unavoidable to take filename as a parameter then
  • Maintain a mapping of fileName to fileID
  • Allow files to be accessed using FileID only. There is no attack surface in technique.
In case where file upload & download functionality is required & user needs to specify the filename. Take all the following steps
  1. Perform decoding & canonicalization of user input.
  2. Check if the filename contains backslash (\), forwardslash(/) , null bytes, if yes, then stop processing
  3. Hard code the list of permissible filetypes and reject any request for a different file type.
  4. Now, use file system API (Eg. getCanonicalPath) to verify that, the file PATH specified is actually the same as the PATH allowed by the application, and only then allow access to the file. 
  5. Java - Java.io.File.getCanonicalPath ,                                                                         
  6. ASP.NET - System.io.Path.GetFullPath
Use a chrooted environment to mitigate the impact of path traversal vulnerabilites
  • Chrooted directory - is treated as filesystem root
  • Any attempt to access a directory above it using /../  sequence is ignored.
  • On Windows - mount a directory as new logical drive & access it using the associated drive letter. It will not allow access to higher directories using /../ sequence.
Identifying Path Traversal attack targets in an application

1. Initial mapping of the application helps in identifying Path traversal attack targets
2. Thoroughly test the functionality where User can 
  • upload or download files
  • share documents
  • upload images
  • download ebooks, documents, manuals
3. Test any GET or POST request PARAMETER which contains a filename or directory name
4. Test application functions which may retrieve data from a server filesystem ( instead of DB)
  • displaying documents
  • displaying images
5. If you have local access to the application server (Whitebox test)
  1. Use a tool like FileMon (Win), ltrace/strace (Unix) to moniter file system activity
  2. Using Burp Intruder, inject a UNIQUE STRING into every user injectable parameter in the application.
  3. Detect the UNIQUE string injected above using a filesystem moniter tool & Identify the parameter and test it for Path Traversal Vulnerability
Detecting the existence of Path Traversal vulnerability

1. Test whether user supplied crafted input is being blocked by the application
Try the following two as filenames
  1. foo.txt
  2. /bar/../foo.txt 
If Application behave in the same way for both inputs, then, it MAY BE VULNERABLE
Point to be Noted: Most file systems attempt canonicalization of a filepath before they try to retrieve it, In the above case    /bar/../  cancels out ( folder /bar/ doesn't need to exist

2. To TEST If the application is vulnerable & allows READ ACCESS try the following
  • ../../../../../../../../../../../etc/passwd
  • ../../../../../../../../../../../windows/win.ini
3. To TEST CONCLUSIVELY, that the application is vulnerable & allows WRITE ACCESS 
Write into a file that any user can write into & then write into a file in which even root cannot write The difference in application response can be USED TO CONCLUDE THAT writing is successful
Try the following in WINDOWS
  • ../../../../../../../../../../../test.txt
  • ../../../../../../../../../../../windows/system32/config/test ( will fail)
Try the following in UNIX
  • ../../../../../../../../../../../tmp/test.txt
  • ../../../../../../../../../../../tmp  (will fail)
 Point to be Noted: Overwriting a directory with a file will always fail in UNIX
 Point to be Noted: All file systems ignore redundant /../ sequences, so try submitting a large number of traversal sequences,
Point to be Noted: Windows tolerates both forward and backward slashes as directory separators.
Point to be Noted: Unix only accepts forward slashes as directory separators.
Point to be Noted: Don't rely on the knowledge of OS of the app server, a backend service may be using a different OS, so try both back and forward slashes.

4. Alternative method, to TEST if WRITE ACCESS is working is to try and write a new file in webroot & open it with browser.

Circumventing Flawed Defense mechanisms 
If the mechanism used to prevent Path Traversal is flawed ==> it can be bypassed

1. If the filter attempts to sanitize the input to remove the sequences, it can be defeated with Encoding
2. Try both back & forward slashes, some filters only remove forward slash while file system may         support both. Try the following encodings for   /../
  • URL encoding
  • 16 bit Unicode encoding
  • Double URL Encoding
  • Overlong UTF-8 Unicode Encoding
  • Use Burp Intruder to generate "Illegal Unicode" within Burp, these may be accepted by the Unicode decoders, particularly on windows.
3. If application removes ../ but doesn't remove it RECURSIVELY from ( ....//), then the following          will work because ../ will get removed and ../ will be left behind.
  • ....//
  • ....\/
  • ....\\
  • ..../\
4. If filetype (suffix) is being verified by the application, Sometimes, it can be subverted by placing a      null byte as follows
  • ../../../../boot.ini.jpg
Point to be Noted: This works because, this check is done in a Managed Environment (Java) which allows Strings to have a NULL character, but the API actually retrieves the file in an UNMANGED environment, in which Strings are NULL Terminated.

 5. If application appends the filetype suffix on its own, then also NULL byte attack can work
 6. If an application tries to verify that that the filename starts with a particular directory name              (downloads), then it can be subverted as follows
  • downloads/../../../../../../../etc/passwd

==============================================================================

File Inclusion Vulnerability ( Local & Remote)

==============================================================================

File Inclusion: Some scripting languages ( like PHP) support the use of Include functions ( include() in PHP). The content of included file is interpreted as if the code was actually copied and pasted.

Remote File Inclusion Vulnerability

PHP's include function accepts REMOTE file path, and thus is a basis of numerous vulnerabilities.
Vulnerability exists when >> User controllable input is used to specify the INCLUDE file name.
Attacker can specify an external URL pointing to a malicious script as the location of the include file.
  • www.example.com/index.php?Country=US
The corresponding backend PHP code is
$country =$_GET['Country']include ( $country. '.php' );
The contents of  US.php are effectively copied in index.php and then are executed.

Local File Inclusion Vulnerability

When the include function of any language allows local (or only local -Eg. Server.Execute() in ASP) files to be included, and the application accepts User controllable data as input to the Include function then the attacker may be able to specify a local file ( Eg. /Admin.aspx) and have it included in the page.

Attacking File Inclusion Vulnerabilities
  • Commonly found in request parameters which specify Language or Location
  • Found in parameters which specify a server file name.
To Detect a remote file inclusion vulnerability
  • Find the Parameter to be tested & Specify the URL to a server you control and see if your server gets any requests from the vulnerable application
To Detect a local file inclusion vulnerability
  • Wider range of scripting environments allow Local File inclusion compared to remote file inclusion
  • Submit the name of a known executable or static resource and check if it is included in the response
Mitigation: A safe solution is to use a Switch/Case statement to determine which file to include.
==============================================================================

12 comments:

  1. Good information provided on the types of injection in an easy to understand language and in very concise yet important. I am exploring on OS command injection and will wait for more updation on that. thank you

    ReplyDelete
  2. I like and suggest you to try LongPathTool program. It is very helpful for copying/deleting or renaming long path files.

    ReplyDelete
  3. I think Power BI is one of the most business intelligent tool to create dashboards for end users.Also I feel there is a need to look for utilising more.

    Powerbi Read Soap

    ReplyDelete
  4. ACTIVE & FRESH CC FULLZ WITH BALANCE
    Price $5 per each CC

    US FRESH, TESTED & VERIFIED SSN LEADS
    $1 PER EACH
    $5 FOR PREMIUM

    *Time wasters or cheap questioners please stay away
    *You can buy for your specific states too
    *Payment in advance

    CC DETAILS
    =>CARD TYPE
    =>FIRST NAME & LAST NAME
    =>CC NUMBER
    =>EXPIRY DATE
    =>CVV
    =>FULL ADDRESS (ZIP CODE, CITY/TOWN, STATE)
    =>PHONE NUMBER,DOB,SSN
    =>MOTHER'S MAIDEN NAME
    =>VERIFIED BY VISA
    =>CVV2

    SSN LEADS INFO
    First Name | Last Name | SSN | Dob | Address | State | City | Zip | Phone Number | Account Number | Bank NAME | DL Number | Home Owner | IP Address |MMN | Income

    Contact Us

    -->Whatsapp > +923172721122
    -->Email > leads.sellers1212@gmail.com
    -->Telegram > @leadsupplier
    -->ICQ > 752822040

    *Hope for the long term deal
    *If you buy leads in bulk, I'll definitely negotiate
    *You can ask me for sample of Lead for demo

    US DUMP TRACK 1 & 2 WITH PIN CODES ALSO AVAILABLE

    ReplyDelete

  5. This professional hacker is absolutely reliable and I strongly recommend him for any type of hack you require. I know this because I have hired him severally for various hacks and he has never disappointed me nor any of my friends who have hired him too, he can help you with any of the following hacks:

    -Phone hacks (remotely)
    -Credit repair
    -Bitcoin recovery (any cryptocurrency)
    -Make money from home (USA only)
    -Social media hacks
    -Website hacks
    -Erase criminal records (USA & Canada only)
    -Grade change

    Email: cybergoldenhacker at gmail dot com

    ReplyDelete
  6. Very important information from the blog and the writer of post and also Your Blog is too good and give unique information. I am so happy that you share this with us.

    Regards,
    Ultrasound guided Injection in Basildon

    ReplyDelete
  7. ****Contact****
    *ICQ :748957107
    *Gmail :fullzvendor111@gmail.com
    *Telegram :@James307
    *Skype : Jamesvince$
    <><><><><><><>
    USA SSN FULLZ WITH ALL PERSONAL DATA+DL NUMBER
    -FULLZ FOR PUA & SBA
    -FULLZ FOR TAX REFUND
    $2 for each fullz/lead with DL num
    $1 for each SSN+DOB
    $5 for each with Premium info
    ID's Photos For any state (back & front)
    (Price can be negotiable if order in bulk)
    <><><><><><><><><><><>
    +High quality and connectivity
    +If you have any trust issue before any deal you may get few to test
    +Every leads are well checked and available 24 hours
    +Fully cooperate with clients
    +Any invalid info found will be replaced
    +Payment Method(BTC,USDT,ETH,LTC & PAYPAL)
    +Fullz available according to demand too i.e (format,specific state,specific zip code & specifc name etc..)
    <><><><><><><><><><>
    +US cc Fullz
    +(Dead Fullz)
    +(Email leads with Password)
    +(Dumps track 1 & 2 with pin and without pin)
    +Hacking & Carding Tutorials
    +Smtp Linux
    +Safe Sock
    +Server I.P's
    +HQ Emails with passwords
    <><><><><><><><>
    *Let's do a long term business with good profit
    *Contact for more details & deal

    ReplyDelete
  8. ****Contact****
    *ICQ :748957107
    *Gmail :fullzvendor111@gmail.com
    *Telegram :@James307
    *Skype : Jamesvince$
    <><><><><><><>
    USA SSN FULLZ WITH ALL PERSONAL DATA+DL NUMBER
    -FULLZ FOR PUA & SBA
    -FULLZ FOR TAX REFUND
    $2 for each fullz/lead with DL num
    $1 for each SSN+DOB
    $5 for each with Premium info
    ID's Photos For any state (back & front)
    (Price can be negotiable if order in bulk)
    <><><><><><><><><><><>
    +High quality and connectivity
    +If you have any trust issue before any deal you may get few to test
    +Every leads are well checked and available 24 hours
    +Fully cooperate with clients
    +Any invalid info found will be replaced
    +Payment Method(BTC,USDT,ETH,LTC & PAYPAL)
    +Fullz available according to demand too i.e (format,specific state,specific zip code & specifc name etc..)
    <><><><><><><><><><>
    +US cc Fullz
    +(Dead Fullz)
    +(Email leads with Password)
    +(Dumps track 1 & 2 with pin and without pin)
    +Hacking & Carding Tutorials
    +Smtp Linux
    +Safe Sock
    +Server I.P's
    +HQ Emails with passwords
    <><><><><><><><>
    *Let's do a long term business with good profit
    *Contact for more details & deal

    ReplyDelete
  9. Hi frnds,

    Great Job done your content is very help full.I have got more information through your blog Ultrasound guided injection is good. blog like these are very helpful for us. It is always good to read and upgrade ourselves.

    Regards,
    Ultrasound guided Injection in Bexleyheath

    ReplyDelete
  10. Hello Everyone,

    Welcome to the future! Financing made easy with Prof. Mrs. DOROTHY LOAN INVESTMENTS

    Have you been looking for financing options for your new business plans, Are you seeking for a loan to expand your existing business, Do you find yourself in a bit of trouble with unpaid bills and you don’t know which way to go or where to turn to? Have you been turned down by your banks? MRS. DOROTHY LOAN INVESTMENTS says YES when your banks say NO. Contact us as we offer financial services at a low and affordable interest rate of 2% for long and short term loans. Interested applicants should contact us for further loan acquisition procedures via profdorothyinvestments@gmail.com

    Services rendered include:

    * Refinancing Loans
    * Car Loan
    * Truck Loans
    * COVID-19 Financing Loan
    * Home Loan
    * Mortgage Loan
    * Debt Consolidation Loan
    * Farm Loan
    * Business Loan [secure and unsecured]
    * Personal Loan [secure and unsecured]
    * Students Loan and so many others.

    For more info; Contact us via Email: profdorothyinvestments@gmail.com

    With Prof. Mrs. DOROTHY LOAN INVESTMENTS. you can say goodbye to all your financial crisis and difficulties as we are certified, trustworthy, reliable, efficient, fast and dynamic

    ReplyDelete
  11. Telegram= @leadsupplier @killhacks @jacobfullz
    ICQ= 752822040 / @killhacks
    Email= hacksp007 @ dnmx.org

    FRESH FULLZ/PROS AVAILABLE

    CC with CVV
    SSN DOB DL
    High Credit Scores Pros
    Business EIN Fullz
    Dumps with PIN Codes Track 101 & 202
    DL Scan Front & Back
    Fullz for KYC, PUA, UI, Tax Refund

    USA, UK, CANADA Fullz Available
    Fresh & Legit stuff
    No refund only replacement

    ReplyDelete