Jump to content

PHP:SQL Injection


MrHotFire

Recommended Posts

Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>

 

Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

 

Note:

 

It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

 

 

A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

 

Example #2 Listing out articles ... and some passwords (any database server)

<?php

$query  = "SELECT id, name, inserted, size FROM products
           WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>

The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

 

SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.

 

Example #3 From resetting a password ... to gaining more privileges (any database server)

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>

But a malicious user sumbits the value ' or uid like'%admin% to $uid to change the admin's password, or simply sets $pwd to hehehe', trusted=100, admin='yes to gain more privileges. Then, the query will be twisted:

<?php

// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";

?>

A frightening example how operating system level commands can be accessed on some database hosts.

 

Example #4 Attacking the database hosts operating system (MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

<?php

$query  = "SELECT * FROM products
           WHERE id LIKE '%a%'
           exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);

?>

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

 

 

 

 

 

Avoidance Techniques

 

While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.

 

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

 

    Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.

    Use prepared statements with bound variables. They are provided by PDO, by MySQLi and by other libraries.

    Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.

 

    If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().

 

 

Example #5 A more secure way to compose a query for paging

<?php

settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                 $offset);

?>

 

    If the database layer doesn't support binding variables then quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). Generic functions like addslashes() are useful only in a very specific environment (e.g. MySQL in a single-byte character set with disabled NO_BACKSLASH_ESCAPES) so it is better to avoid them.

    Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

    You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

 

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.

 

...

 

 

 

<?php
$login = mysql_query("select f_uname, f_passwd from t_user where MD5(f_uname) = '".md5($uname)."' and MD5(f_passwd)='".md5($passwd)."'");
?>

 

The injected requests will be crushed and it will become much more difficult to obtain data in the database. Use both sides of the hash result in a comparison of hash, not the execution of the injected queries.

 

Unfortunately, it probably does not work with other types of queries.

 

 

Pangolin:Pangolin is an automatic SQL injection penetration testing tool developed by NOSEC.

Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications. Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user"s specific DBMS tables/columns, run his own SQL statement, read specific files on the file system and more.

 

 

 

Exists many ways to prevent SQL Injections..etc...but I am tired to write.

 

 

 

Credits:Olympus,kirby4 & Me.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Posts

    • Instead of using encedc on it, try renaming it to "Icon.u" instead of "Icon.utx", and put it in your System folder. If it still crashes, the problem might be with your unrealed.
    • How's the project doing? Is there any news? It really interesting 🤔
    • thx for answer, i tried and woks encrypting, but i still having crashes 😞 i changed the icon in skillgrp.dat from "icon.skill0003" to "Myicons.misil" as i saved the file before endec and nothing. this is the report i got
    • New Season coming May 2024! First post updated      Website: L2Kain.net  Discord: https://discord.gg/l2kain  Wiki: https://info.kain.ws/   Important Dates   Server Start: TBD  Open Beta Test: 10th of May 2024!   Basic Information     Briefly about the concept of the server! We decided to move away from the standard Mid-Rate server concept and keep the mechanics of our beloved Lineage 2 that everyone loves! Massive battles for epic bosses, battles for profitable farming locations, resource spoilage and equipment crafting, daily instances, a balanced economy and much more. This server is build as a Craft-PvP concept. The goal is to gather players with a variety of preferences in the game and make a high-quality and interesting server with alternative character development options. We are well aware that "grinding" is an integral part of the game, but we diluted the boring and the same type of farming with interesting solutions and non-standard mechanics!   We have prepared a new High Five x25 on Modern Client for you. This server will be another step in the development of the platform and the project as a whole! Your appeals to those. support was not ignored, which means the new server will be even better than the previous one!      ⭐ Promotions and Bonuses for new players!     ⭐ Events and Giveaways daily!   ⭐ Rewards for Voting!   ℹ️ Server Rates Learn more about server rates! Server rates are configured in such a way that farming is best rewarded. Adena, drops, quests, various rewards and prices in the game store are well balanced among themselves!   Basic Server Rates:  ⭐ Experience & Skill Points - x25  ⭐ Adena Drop - x15 & Fixed Chance 66%  ⭐ Drop Rates - x10  ⭐ Spoil Rates - x10   Crafting keys, recipes drop & spoil with fixed amount from 2 to 3 and increased chances on all locations and quests  related to farm them.  ⭐ Quest Rates - x5  ⭐ Fortresses & Sieges - x5  ⭐ Raid Bosses & Epic Bosses - x1  ⭐ Weight Limit - x10      Connect with Us:  Discord: https://discord.gg/l2kain  Facebook: https://www.facebook.com/KainLineage2  TikTok: https://www.tiktok.com/@l2kain.net  YouTube: https://www.youtube.com/@Lineage2Kain
  • Topics

×
×
  • Create New...