Hand Book on effective communication

Zooomin, try it.. its cool.

zoomin!!! its cool

User Defined Functions

This article covers all the basics of User Defined Functions. It discusses how (and why) to create them and when to use them. It talks about scalar, inline table-valued and multi-statement table-valued functions. (This article has been updated through SQL Server 2005.)

<!–


–>

With SQL Server 2000, Microsoft has introduced the concept of User-Defined Functions that allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.

What Kind of User-Defined Functions can I Create?

There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.

How do I create and use a Scalar User-Defined Function?

A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. Below is an example that is based in the data found in the NorthWind Customers Table.

CREATE FUNCTION whichContinent
(@Country nvarchar(15))
RETURNS varchar(30)
AS
BEGIN
declare @Return varchar(30)
select @return = case @Country
when 'Argentina' then 'South America'
when 'Belgium' then 'Europe'
when 'Brazil' then 'South America'
when 'Canada' then 'North America'
when 'Denmark' then 'Europe'
when 'Finland' then 'Europe'
when 'France' then 'Europe'
else 'Unknown'
end

return @return
end

Because this function returns a scalar value of a varchar(30) this function could be used anywhere a varchar(30) expression is allowed such as a computed column in a table, view, a T-SQL select list item. Below are some of the examples that I was able to use after creating the above function definition. Note that I had to reference the dbo in the function name.

print dbo.WhichContinent('USA')

select dbo.WhichContinent(Customers.Country), customers.*
from customers

create table test
(Country varchar(15),
Continent as (dbo.WhichContinent(Country)))

insert into test (country)
values ('USA')

select * from test

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

Country          Continent
---------------  ------------------------------
USA              North America

Stored procedures have long given us the ability to pass parameters and get a value back, but the ability to use it in such a variety of different places where you cannot use a stored procedure make this a very powerful database object. Also notice the logic of my function is not exactly brain surgery. But it does encapsulate the business rules for the different continents in one location in my application. If you were to build this logic into T-SQL statements scattered throughout your application and you suddenly noticed that you forgot a country (like I missed Austria!) you would have to make the change in every T-SQL statement where you had used that logic. Now, with the SQL Server User-Defined Function, you can quickly maintain this logic in just one place.

How do I create and use an Inline Table-Value User-Defined Function?

An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

CREATE FUNCTION CustomersByContinent
(@Continent varchar(30))
RETURNS TABLE
AS
RETURN
  SELECT dbo.WhichContinent(Customers.Country) as continent,
         customers.*
  FROM customers
  WHERE dbo.WhichContinent(Customers.Country) = @Continent
GO

SELECT * from CustomersbyContinent('North America')
SELECT * from CustomersByContinent('South America')
SELECT * from customersbyContinent('Unknown')

Note that the example uses another function (WhichContinent) to select out the customers specified by the parameter of this function. After creating the user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets. Also note that I do not have to reference the dbo in my reference to this function. However, when using SQL Server built-in functions that return a table, you must now add the prefix :: to the name of the function.

Example from Books Online: Select * from ::fn_helpcollations()

How do I create and use a Multi-statement Table-Value User-Defined Function?

A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

CREATE FUNCTION dbo.customersbycountry ( @Country varchar(15) )
RETURNS
	@CustomersbyCountryTab table (
		[CustomerID] [nchar] (5), [CompanyName] [nvarchar] (40),
		[ContactName] [nvarchar] (30), [ContactTitle] [nvarchar] (30),
		[Address] [nvarchar] (60), [City] [nvarchar] (15),
		[PostalCode] [nvarchar] (10), [Country] [nvarchar] (15),
		[Phone] [nvarchar] (24), [Fax] [nvarchar] (24)
	)
AS
BEGIN
	INSERT INTO @CustomersByCountryTab
	SELECT 	[CustomerID],
			[CompanyName],
			[ContactName],
			[ContactTitle],
			[Address],
			[City],
			[PostalCode],
			[Country],
			[Phone],
			[Fax]
	FROM [Northwind].[dbo].[Customers]
	WHERE country = @Country

	DECLARE @cnt INT
	SELECT @cnt = COUNT(*) FROM @customersbyCountryTab

	IF @cnt = 0
		INSERT INTO @CustomersByCountryTab (
			[CustomerID],
			[CompanyName],
			[ContactName],
			[ContactTitle],
			[Address],
			[City],
			[PostalCode],
			[Country],
			[Phone],
			[Fax]  )
		VALUES ('','No Companies Found','','','','','','','','')

	RETURN
END
GO
SELECT * FROM dbo.customersbycountry('USA')
SELECT * FROM dbo.customersbycountry('CANADA')
SELECT * FROM dbo.customersbycountry('ADF')

What are the benefits of User-Defined Functions?

The benefits to SQL Server User-Defined functions are numerous. First, we can use these functions in so many different places when compared to the SQL Server stored procedure. The ability for a function to act like a table (for Inline table and Multi-statement table functions) gives developers the ability to break out complex logic into shorter and shorter code blocks. This will generally give the additional benefit of making the code less complex and easier to write and maintain. In the case of a Scalar User-Defined Function, the ability to use this function anywhere you can use a scalar of the same data type is also a very powerful thing. Combining these advantages with the ability to pass parameters into these database objects makes the SQL Server User-Defined function a very powerful tool.

Summary

So, if you have ever wanted to use the results of a stored procedure as part of a T-SQL command, use parameterized non-updateable views, or encapsulate complex logic into a single database object, the SQL Server 2000 User-Defined function is a new database object that you should examine to see if its right for your particular environment.

source: http://www.sqlteam.com/

Cross Page posting in ASP.NET 2.0

Cross Page posting in ASP.NET 2.0

We always tend to post data from one page to another in a typical web application. For example, user name entered on login page getting displayed in welcome message on homepage.

How do you generally post values/data from one page to another page in ASP.NET 1.x? There are different ways in which you can exchange the data in ASP.NET 1.x like Query strings, Server.Transfer method, Response.Redirect method and session variables. All these techniques have their own merits and demerits like browser imposed character limit when passing parameters using Query Strings and indiscriminate usage of session variables can prove costly in terms of load on server and eventually impacts the performance of server.

Keeping in view above limitations in ASP.NET 1.x, Microsoft has reinstated Cross Page posting feature in ASP.NET 2.0. Many of us might not be aware of Cross Page posting feature in classic ASP. Cross Page posting feature allows a page to cross post to another page which in turn allows you to access all data in posted source page.

In ASP.NET 1.x , when you use look at page life level, you observe that a page can only submit to itself. Cross Page posting feature allows us post the form along with all its control values into another page.

Any server control which implements System.Web.UI.WebControls.IButtonControl interface can be used for Cross page posting. Examples of such controls include link button, Image button and submit button

By simply setting PostbackUrl property, we specify the destination page to which present page should post when post back occurs on present page.

Different methods to post data

There are several methods to post data from one page to another page depending on your needs. If you need to exchange simple insensitive data, you can give a try with existing techniques. So, let us revisit those different techniques which allow exchanging data from one page to another.

Response.Redirect method

We can use this method to allow client browser to do redirection from one page to another page. This technique is usually referred to as Client side redirection. When client browser redirects to DestinationPage.aspx, it involves Server sending a HTTP header informing that the user should redirect and the Client requests the DestinationPage.aspx. Server sends DestinationPage.aspx. Now the Client’s address bar shows DestinationPage.aspx. This entire series of steps incurs extra round trip to server which hits the performance. We usually associate Query Strings with Response.Redirect. There is always a client browser imposed limitation on the length of a query string; so you end up sending small amounts of data over the wire.

Session Variables

We can use session variable to store page information and use it across different pages for entire user session. However, this involves of consumption of costly server resources. This approach may prove disastrous when large numbers of users connect to server and things go pretty poor.

Server.Transfer Method

On flip side to Client side redirection, we have server doing the page transfer. In Server.Transfer, Http Context is preserved when moving from one page to another which means we can access the source page’s items collection in target page. The drawback of using this method is that the browser does not know that a different page was returned to it. It still displays the previous source page’s URL in the address bar. This can confuse the user. Transfer is not recommended since the operations typically flow through several different pages.

Technically speaking, Server.Transfer is faster since there is one less roundtrip, but you lose the URL of the page. Server.Transfer also allows for more flexibilty since you can use HTTPContext.Items to pass variables between pages.

Use Server.Transfer when you need to pass context items. Otherwise use Response.Redirect so the user will always see the correct URL in the address bar.

New Properties helping in Cross Page posting

The new PreviousPage property provides reference to the source page. When a cross page request occurs, the PreviousPage property of the current Page class holds a reference to the page that caused the post back. If the page is not the target of a cross-page posting or if the pages are in different applications, the PreviousPage property is not initialized. After cross-posts back from source page to the target page, the target page accesses information on the source page using this property.

Different ways of implementing Cross Page Posting

There are couples of ways of getting control values of the source page into the target page. First way being using FindControl method as discussed below

Using FindControl Method

In the below listing, we set the PostBackUrl property for Submit button. This property points to the location of the file to which this page should post. In this case, it is DestinationPage.aspx. This means that the DestinationPage.aspx receives the postback and all the values contained in CrossPostingPage.aspx page controls as shown below

<form id=”form1″ runat=”server”>
<div>
<h2> This page will cross post to another page by setting PostbackUrl property of submit button.</h2>
&nbsp;
<asp:Label ID=”lblName” runat=”server” Text=”LoginName” style=”left: 76px; position: relative; top: 20px”></asp:Label><br />
&nbsp;<asp:TextBox ID=”txtPassword” runat=”server” style=”z-index: 100; left: 160px; position: relative; top: 34px”></asp:TextBox>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox><br />
<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit”
PostBackUrl=”DestinationPage.aspx” style=”left: 208px; position: relative; top: 54px” />
<br />
<asp:Label ID=”lblPassword” runat=”server” Text=”Password” style=”left: 90px; position: relative; top: -12px” Height=”4px” Width=”43px”></asp:Label></div>
</form>


SourcePage which does Cross page post back to Destination page

You can see in below code how we are able to retrieve values from previous page using FindControl method and display them on Destination Page. Below given output should help you understand the funda.

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
Label1.Text = “Name:” + CType(PreviousPage.FindControl(“txtName”), TextBox).Text
Label2.Text = “Password:” + CType(PreviousPage.FindControl(“txtPassword”), TextBox).Text
End Sub


Output listing

Using Control Property

Another way of exposing the control values from the Source Page to Destination Page is to create a public property of controls as shown below

Public Property UserName() As String
Get
Return UserName
End Get
Set(ByVal value As String)

End Set
End Property
Public Property Password() As String
Get
Return Password
End Get
Set(ByVal value As String)

End Set
End Property

In order to work with the properties described in FindControl page as shown above, PreviousPageType directive should be included in the destination page that is in DestinationPage.aspx. See below listing

<%@ PreviousPageType VirtualPath=”FindControl.aspx”%>

The above directive points to FindControl.aspx by specifying the VirtualPath attribute and when that is in place, one can see the properties exposed by FindControl page in DestinationPage using the PreviousPage property. It is always better to expose only the information we need as public properties to reduce the amount of information available to potentially malicious users.

IsCrossPagePostBack Property

IsCrossPostBack property, which is new in ASP.NET 2.0, enables us to check whether the page is participating in a cross page request. Using IsCrossPostBack property, we can check whether the request is coming from a particular page or not and act accordingly. As per above example, DestinationPage can include this property to specially process the FindControl.aspx cross page post back. Similarly, we can use the IsValid property of our previous page to make sure the page passed all client validations before it is cross posted to DestinationPage.

If Page.IsCrossPagePostBack Then
Label1.Text = “Name:” + CType(PreviousPage.FindControl(“txtName”), TextBox).Text
Label2.Text = “Password:” + CType(PreviousPage.FindControl(“txtPassword”), TextBox).Text
Else
Label1.Text = “No Name:Normal Postback”
Label2.Text = “No password: normal postback”
End If

Hence, Cross Page posting is very handy feature to implement very specific scenarios like displaying logged in user details on different pages and ensuring the request is coming from correct page. You can implement this feature in either two ways using FindControl method or exposing values as public properties. PreviousPage object will expose very useful properties like IsValid property and FindControl property to make Cross Page Posting more useful.

source: http://www.beansoftware.com

Microsoft Office Ultimate 2007 (DIRECT LINK)

Microsoft Office Ultimate 2007 Direct Download
Office Ultimate 2007 provides people at home or work with a comprehensive set of tools that helps them gather and consolidate virtually any type of information, find what they are looking for quickly, and easily share information with others across geographical or organizational boundaries, so they can deliver better results faster.

Download Office 2007 Ultimate directly from :

Code:

http://msft-dnl.digitalrivercontent…./X12-30307.exe

CRACK:

Code:

http://rapidshare.com/files/96123233…gutom.rar.html

50 common questions asked in interviews

Review these typical interview questions and think about how you would
answer them. Read the questions listed; you will also find some
strategy suggestions with it.

1. Tell me about yourself:
The most often asked question in interviews. You need to have a short
statement prepared in your mind. Be careful that it does not sound
rehearsed. Limit it to work-related items unless instructed otherwise.
Talk about things you have done and jobs you have held that relate to
the position you are interviewing for. Start with the item farthest
back and work up to the present.

2. Why did you leave your last job?
Stay positive regardless of the circumstances. Never refer to a major
problem with management and never speak ill of supervisors, co-workers
or the organization. If you do, you will be the one looking bad. Keep
smiling and talk about leaving for a positive reason such as an
opportunity, a chance to do something special or other forward-looking
reasons.

3. What experience do you have in this field?
Speak about specifics that relate to the position you are applying for.
If you do not have specific experience, get as close as you can.

4. Do you consider yourself successful?
You should always answer yes and briefly explain why. A good
explanation is that you have set goals, and you have met some and are
on track to achieve the others.

5. What do co-workers say about you?
Be prepared with a quote or two from co-workers. Either a specific
statement or a paraphrase will work. Jill Clark, a co-worker at Smith
Company, always said I was the hardest workers she had ever known. It
is as powerful as Jill having said it at the interview herself.

6. What do you know about this organization?
This question is one reason to do some research on the organization
before the interview. Find out where they have been and where they are
going. What are the current issues and who are the major players?

7. What have you done to improve your knowledge in the last year?
Try to include improvement activities that relate to the job. A wide
variety of activities can be mentioned as positive self-improvement.
Have some good ones handy to mention.

8. Are you applying for other jobs?
Be honest but do not spend a lot of time in this area. Keep the focus
on this job and what you can do for this organization. Anything else is
a distraction.

9. Why do you want to work for this organization?
This may take some thought and certainly, should be based on the
research you have done on the organization. Sincerity is extremely
important here and will easily be sensed. Relate it to your long-term
career goals.

10. Do you know anyone who works for us?
Be aware of the policy on relatives working for the organization. This
can affect your answer even though they asked about friends not
relatives. Be careful to mention a friend only if they are well thought
of.

11. What kind of salary do you need?
A loaded question. A nasty little game that you will probably lose if
you answer first. So, do not answer it. Instead, say something like,
That’s a tough question. Can you tell me the range for this position?
In most cases, the interviewer, taken off guard, will tell you. If not,
say that it can depend on the details of the job. Then give a wide
range.

12. Are you a team player?
You are, of course, a team player. Be sure to have examples ready.
Specifics that show you often perform for the good of the team rather
than for yourself are good evidence of your team attitude. Do not brag,
just say it in a matter-of-fact tone. This is a key point.

13. How long would you expect to work for us if hired?
Specifics here are not good. Something like this should work: I’d like
it to be a long time. Or As long as we both feel I’m doing a good job.

14. Have you ever had to fire anyone? How did you feel about that?
This is serious. Do not make light of it or in any way seem like you
like to fire people. At the same time, you will do it when it is the
right thing to do. When it comes to the organization versus the
individual who has created a harmful situation, you will protect the
organization. Remember firing is not the same as layoff or reduction in
force.

15. What is your philosophy towards work?
The interviewer is not looking for a long or flowery dissertation here.
Do you have strong feelings that the job gets done? Yes. That’s the
type of answer that works best here. Short and positive, showing a
benefit to the organization.

16. If you had enough money to retire right now, would you?
Answer yes if you would. But since you need to work, this is the type
of work you prefer. Do not say yes if you do not mean it.

17. Have you ever been asked to leave a position?
If you have not, say no. If you have, be honest, brief and avoid saying
negative things about the people or organization involved.

18. Explain how you would be an asset to this organization
You should be anxious for this question. It gives you a chance to
highlight your best points as they relate to the position being
discussed. Give a little advance thought to this relationship.

19. Why should we hire you?
Point out how your assets meet what the organization needs. Do not
mention any other candidates to make a comparison.

20. Tell me about a suggestion you have made
Have a good one ready. Be sure and use a suggestion that was accepted
and was then considered successful. One related to the type of work
applied for is a real plus.

21. What irritates you about co-workers?
This is a trap question. Think real hard but fail to come up with
anything that irritates you. A short statement that you seem to get
along with folks is great.

22. What is your greatest strength?
Numerous answers are good, just stay positive. A few good examples:
Your ability to prioritize, Your problem-solving skills, Your ability
to work under pressure, Your ability to focus on projects, Your
professional expertise, Your leadership skills, Your positive attitude

23. Tell me about your dream job.
Stay away from a specific job. You cannot win. If you say the job you
are contending for is it, you strain credibility. If you say another
job is it, you plant the suspicion that you will be dissatisfied with
this position if hired. The best is to stay genetic and say something
like: A job where I love the work, like the people, can contribute and
can’t wait to get to work.

24. Why do you think you would do well at this job?
Give several reasons and include skills, experience and interest.

25. What are you looking for in a job?
See answer # 23

26. What kind of person would you refuse to work with?
Do not be trivial. It would take disloyalty to the organization,
violence or lawbreaking to get you to object. Minor objections will
label you as a whiner.

27. What is more important to you: the money or the work?
Money is always important, but the work is the most important. There is
no better answer.

28. What would your previous supervisor say your strongest point is?
There are numerous good possibilities:
Loyalty, Energy, Positive attitude, Leadership, Team player, Expertise,
Initiative, Patience, Hard work, Creativity, Problem solver

29. Tell me about a problem you had with a supervisor
Biggest trap of all. This is a test to see if you will speak ill of
your boss. If you fall for it and tell about a problem with a former
boss, you may well below the interview right there. Stay positive and
develop a poor memory about any trouble with a supervisor.

30. What has disappointed you about a job?
Don’t get trivial or negative. Safe areas are few but can include:
Not enough of a challenge. You were laid off in a reduction Company did
not win a contract, which would have given you more responsibility.

31. Tell me about your ability to work under pressure.
You may say that you thrive under certain types of pressure. Give an
example that relates to the type of position applied for.

32. Do your skills match this job or another job more closely?
Probably this one. Do not give fuel to the suspicion that you may want
another job more than this one.

33. What motivates you to do your best on the job?
This is a personal trait that only you can say, but good examples are:
Challenge, Achievement, Recognition

34. Are you willing to work overtime? Nights? Weekends?
This is up to you. Be totally honest.

35. How would you know you were successful on this job?
Several ways are good measures:
You set high standards for yourself and meet them. Your outcomes are a
success.Your boss tell you that you are successful

36. Would you be willing to relocate if required?
You should be clear on this with your family prior to the interview if
you think there is a chance it may come up. Do not say yes just to get
the job if the real answer is no. This can create a lot of problems
later on in your career. Be honest at this point and save yourself
future grief.

37. Are you willing to put the interests of the organization ahead ofyour own?
This is a straight loyalty and dedication question. Do not worry about
the deep ethical and philosophical implications. Just say yes.

38. Describe your management style.
Try to avoid labels. Some of the more common labels, like progressive,
salesman or consensus, can have several meanings or descriptions
depending on which management expert you listen to. The situational
style is safe, because it says you will manage according to the
situation, instead of one size fits all.

39. What have you learned from mistakes on the job?
Here you have to come up with something or you strain credibility. Make
it small, well intentioned mistake with a positive lesson learned. An
example would be working too far ahead of colleagues on a project and
thus throwing coordination off.

40. Do you have any blind spots?
Trick question. If you know about blind spots, they are no longer blind
spots. Do not reveal any personal areas of concern here. Let them do
their own discovery on your bad points. Do not hand it to them.

41. If you were hiring a person for this job, what would you look for?
Be careful to mention traits that are needed and that you have.

42. Do you think you are overqualified for this position?
Regardless of your qualifications, state that you are very well
qualified for the position.

43. How do you propose to compensate for your lack of experience?
First, if you have experience that the interviewer does not know about,
bring that up: Then, point out (if true) that you are a hard working
quick learner.

44. What qualities do you look for in a boss?
Be generic and positive. Safe qualities are knowledgeable, a sense of
humor, fair, loyal to subordinates and holder of high standards. All
bosses think they have these traits.

45. Tell me about a time when you helped resolve a dispute betweenothers.
Pick a specific incident. Concentrate on your problem solving technique
and not the dispute you settled.

46. What position do you prefer on a team working on a project?
Be honest. If you are comfortable in different roles, point that out.

47. Describe your work ethic.
Emphasize benefits to the organization. Things like, determination to
get the job done and work hard but enjoy your work are good.

48. What has been your biggest professional disappointment?
Be sure that you refer to something that was beyond your control. Show
acceptance and no negative feelings.

49. Tell me about the most fun you have had on the job.
Talk about having fun by accomplishing something for the organization.

50. Do you have any questions for me?
Always have some questions prepared. Questions prepared where you will be an asset to the organization are good. How soon will I be able to be productive? and What type of projects will I be able to assist on? are
examples.

source:  http://www.citehr.com/110299-50-common-questions-asked-interviews.html

file your IT-Returns on-line

Please find the following steps to file your IT-Returns on-line

You can submit yr IT return online by following process.

1.        GO TO

http://incometaxindiaefiling.gov.in/portal/index.jsp
http://incometaxindiaefiling.gov.in/portal/index.jsp>

2.        REGISTER AND CREATE USER (USERNAME AS YOUR PAN NO)
3.        GO TO
http://incometaxindiaefiling.gov.in/portal/html/downloads.jsp
http://incometaxindiaefiling.gov.in/portal/html/downloads.jsp>
4.        DOWNLOAD ITR-1
5.        FILL THE FORM
6.        CHECK THE FORM
7.        GENERATE BARCODE
8.        GENERATE XML AND SAVE ON YOUR SYSTEM
9.        GO TO https://incometaxindiaefiling.gov.in/portal/login.jsp
AND LOGIN
10.      CLICK ON SUBMIT RETURN.
11.      UPLOAD XML FILE.
12.      CLICK ON UPLOAD.

Congratulation YOU HAVE SUBMITED YOUR RETURN.

YOU CAN ALSO CHECK YOUR refund STATUS IF ANY.

SQL Injection Attacks by Example

sqlinjection

“SQL Injection” is subset of the an unverified/unsanitized user input vulnerability (“buffer overflows” are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it’s straightforward to create some real surprises.

We’ll note that this was a somewhat winding road with more than one wrong turn, and others with more experience will certainly have different — and better — approaches. But the fact that we were successful does suggest that we were not entirely misguided.

There have been other papers on SQL injection, including some that are much more detailed, but this one shows the rationale of discovery as much as the process of exploitation

The Target Intranet

This appeared to be an entirely custom application, and we had no prior knowledge of the application nor access to the source code: this was a “blind” attack. A bit of poking showed that this server ran Microsoft’s IIS 6 along with ASP.NET, and this suggested that the database was Microsoft’s SQL server: we believe that these techniques can apply to nearly any web application backed by any SQL server.

The login page had a traditional username-and-password form, but also an email-me-my-password link; the latter proved to be the downfall of the whole system.

When entering an email address, the system presumably looked in the user database for that email address, and mailed something to that address. Since my email address is not found, it wasn’t going to send me anything.

So the first test in any SQL-ish form is to enter a single quote as part of the data: the intention is to see if they construct an SQL string literally without sanitizing. When submitting the form with a quote in the email address, we get a 500 error (server failure), and this suggests that the “broken” input is actually being parsed literally. Bingo.

We speculate that the underlying SQL code looks something like this:

SELECT fieldlist
  FROM table
 WHERE field = '$EMAIL';

Here, $EMAIL is the address submitted on the form by the user, and the larger query provides the quotation marks that set it off as a literal string. We don’t know the specific names of the fields or table involved, but we do know their nature, and we’ll make some good guesses later.

When we enter steve@unixwiz.net’ – note the closing quote mark – this yields constructed SQL:

SELECT fieldlist
  FROM table
 WHERE field = 'steve@unixwiz.net'';

when this is executed, the SQL parser find the extra quote mark and aborts with a syntax error. How this manifests itself to the user depends on the application’s internal error-recovery procedures, but it’s usually different from “email address is unknown”. This error response is a dead giveaway that user input is not being sanitized properly and that the application is ripe for exploitation.

Since the data we’re filling in appears to be in the WHERE clause, let’s change the nature of that clause in an SQL legal way and see what happens. By entering anything’ OR ‘x’='x, the resulting SQL is:

SELECT fieldlist
  FROM table
 WHERE field = 'anything' OR 'x'='x';

Because the application is not really thinking about the query – merely constructing a string – our use of quotes has turned a single-component WHERE clause into a two-component one, and the ‘x’='x’ clause is guaranteed to be true no matter what the first clause is (there is a better approach for this “always true” part that we’ll touch on later).

But unlike the “real” query, which should return only a single item each time, this version will essentially return every item in the members database. The only way to find out what the application will do in this circumstance is to try it. Doing so, we were greeted with:

Your login information has been mailed to random.person@example.com.


Our best guess is that it’s the first record returned by the query, effectively an entry taken at random. This person really did get this forgotten-password link via email, which will probably come as surprise to him and may raise warning flags somewhere.

We now know that we’re able to manipulate the query to our own ends, though we still don’t know much about the parts of it we cannot see. But we have observed three different responses to our various inputs:

  • “Your login information has been mailed to email
  • “We don’t recognize your email address”
  • Server error

The first two are responses to well-formed SQL, while the latter is for bad SQL: this distinction will be very useful when trying to guess the structure of the query.

Schema field mapping

The first steps are to guess some field names: we’re reasonably sure that the query includes “email address” and “password”, and there may be things like “US Mail address” or “userid” or “phone number”. We’d dearly love to perform a SHOW TABLE, but in addition to not knowing the name of the table, there is no obvious vehicle to get the output of this command routed to us.

So we’ll do it in steps. In each case, we’ll show the whole query as we know it, with our own snippets shown specially. We know that the tail end of the query is a comparison with the email address, so let’s guess email as the name of the field:

SELECT fieldlist
  FROM table
 WHERE field = 'x' AND email IS NULL; --';

The intent is to use a proposed field name (email) in the constructed query and find out if the SQL is valid or not. We don’t care about matching the email address (which is why we use a dummy ‘x’), and the marks the start of an SQL comment. This is an effective way to “consume” the final quote provided by application and not worry about matching them.

If we get a server error, it means our SQL is malformed and a 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. This is the case whether we get the “email unknown” or “password was sent” response.

Note, however, that we use the AND conjunction instead of OR: this is intentional. In the SQL schema mapping phase, we’re not really concerned with guessing any particular email addresses, and we do not want random users inundated with “here is your password” emails from the application – this will surely raise suspicions to no good purpose. By using the AND conjunction with an email address that couldn’t ever be valid, we’re sure that the query will always return zero rows and never generate a password-reminder email.

Submitting the above snippet indeed gave us the “email address unknown” response, so now we know that the email address is stored in a field email. If this hadn’t worked, we’d have tried email_address or mail or the like. This process will involve quite a lot of guessing.

Next we’ll guess some other obvious names: password, user ID, name, and the like. These are all done one at a time, and anything other than “server failure” means we guessed the name correctly.

SELECT fieldlist
  FROM table
 WHERE email = 'x' AND userid IS NULL; --';

As a result of this process, we found several valid field names:

  • email
  • passwd
  • login_id
  • full_name

There are certainly more (and a good source of clues is the names of the fields on forms), but a bit of digging did not discover any. But we still don’t know the name of the table that these fields are found in – how to find out?

Finding the table name

The application’s built-in query already has the table name built into it, but we don’t know what that name is: there are several approaches for finding that (and other) table names. The one we took was to rely on a subselect.

A standalone query of

SELECT COUNT(*) FROM tabname

Returns the number of records in that table, and of course fails if the table name is unknown. We can build this into our string to probe for the table name:

SELECT email, passwd, login_id, full_name
  FROM table
 WHERE email = 'x' AND 1=(SELECT COUNT(*) FROM tabname); --';

We don’t care how many records are there, of course, only whether the table name is valid or not. By iterating over several guesses, we eventually determined that members was a valid table in the database. But is it the table used in this query? For that we need yet another test using table.field notation: it only works for tables that are actually part of this query, not merely that the table exists.

SELECT email, passwd, login_id, full_name
  FROM members
 WHERE email = 'x' AND members.email IS NULL; --';

When this returned “Email unknown”, it confirmed that our SQL was well formed and that we had properly guessed the table name. This will be important later, but we instead took a different approach in the interim.

Finding some users

At this point we have a partial idea of the structure of the members table, but we only know of one username: the random member who got our initial “Here is your password” email. Recall that we never received the message itself, only the address it was sent to. We’d like to get some more names to work with, preferably those likely to have access to more data.

The first place to start, of course, is the company’s website to find who is who: the “About us” or “Contact” pages often list who’s running the place. Many of these contain email addresses, but even those that don’t list them can give us some clues which allow us to find them with our tool.

The idea is to submit a query that uses the LIKE clause, allowing us to do partial matches of names or email addresses in the database, each time triggering the “We sent your password” message and email. Warning: though this reveals an email address each time we run it, it also actually sends that email, which may raise suspicions. This suggests that we take it easy.

We can do the query on email name or full name (or presumably other information), each time putting in the % wildcards that LIKE supports:

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

Keep in mind that even though there may be more than one “Bob”, we only get to see one of them: this suggests refining our LIKE clause narrowly.

Ultimately, we may only need one valid email address to leverage our way in.

Brute-force password guessing

One can certainly attempt brute-force guessing of passwords at the main login page, but many systems make an effort to detect or even prevent this. There could be logfiles, account lockouts, or other devices that would substantially impede our efforts, but because of the non-sanitized inputs, we have another avenue that is much less likely to be so protected.

We’ll instead do actual password testing in our snippet by including the email name and password directly. In our example, we’ll use our victim, bob@example.com and try multiple passwords.

SELECT email, passwd, login_id, full_name
  FROM members
 WHERE email = 'bob@example.com' AND passwd = 'hello123';

This is clearly well-formed SQL, so we don’t expect to see any server errors, and we’ll know we found the password when we receive the “your password has been mailed to you” message. Our mark has now been tipped off, but we do have his password.

This procedure can be automated with scripting in perl, and though we were in the process of creating this script, we ended up going down another road before actually trying it.

The database isn’t readonly

So far, we have done nothing but query the database, and even though a SELECT is readonly, that doesn’t mean that SQL is. SQL uses the semicolon for statement termination, and if the input is not sanitized properly, there may be nothing that prevents us from stringing our own unrelated command at the end of the query.

The most drastic example is:

SELECT email, passwd, login_id, full_name
  FROM members
 WHERE email = 'x'; DROP TABLE members; --';  -- Boom!

The first part provides a dummy email address — ‘x’ — and we don’t care what this query returns: we’re just getting it out of the way so we can introduce an unrelated SQL command. This one attempts to drop (delete) the entire members table, which really doesn’t seem too sporting.

This shows that not only can we run separate SQL commands, but we can also modify the database. This is promising.

Adding a new member

Given that we know the partial structure of the members table, it seems like a plausible approach to attempt adding a new record to that table: if this works, we’ll simply be able to login directly with our newly-inserted credentials.

This, not surprisingly, takes a bit more SQL, and we’ve wrapped it over several lines for ease of presentation, but our part is still one contiguous string:

SELECT email, passwd, login_id, full_name
  FROM members
 WHERE email = 'x';
        INSERT INTO members ('email','passwd','login_id','full_name') 
        VALUES ('steve@unixwiz.net','hello','steve','Steve Friedl');--';

Even if we have actually gotten our field and table names right, several things could get in our way of a successful attack:

  1. We might not have enough room in the web form to enter this much text directly (though this can be worked around via scripting, it’s much less convenient).
  2. The web application user might not have INSERT permission on the members table.
  3. There are undoubtedly other fields in the members table, and some may require initial values, causing the INSERT to fail.
  4. Even if we manage to insert a new record, the application itself might not behave well due to the auto-inserted NULL fields that we didn’t provide values for.
  5. A valid “member” might require not only a record in the members table, but associated information in other tables (say, “accessrights”), so adding to one table alone might not be sufficient.

In the case at hand, we hit a roadblock on either #4 or #5 – we can’t really be sure — because when going to the main login page and entering in the above username + password, a server error was returned. This suggests that fields we did not populate were vital, but nevertheless not handled properly.

A possible approach here is attempting to guess the other fields, but this promises to be a long and laborious process: though we may be able to guess other “obvious” fields, it’s very hard to imagine the bigger-picture organization of this application.

We ended up going down a different road.

Mail me a password

We then realized that though we are not able to add a new record to the members database, we can modify an existing one, and this proved to be the approach that gained us entry.

From a previous step, we knew that bob@example.com had an account on the system, and we used our SQL injection to update his database record with our email address:

SELECT email, passwd, login_id, full_name
  FROM members
 WHERE email = 'x';
      UPDATE members
      SET email = 'steve@unixwiz.net'
      WHERE email = 'bob@example.com';

After running this, we of course received the “we didn’t know your email address”, but this was expected due to the dummy email address provided. The UPDATE wouldn’t have registered with the application, so it executed quietly.

We then used the regular “I lost my password” link – with the updated email address – and a minute later received this email:

From: system@example.com
To: steve@unixwiz.net
Subject: Intranet login

This email is in response to your request for your Intranet log in information.
Your User ID is: bob
Your password is: hello

Now it was now just a matter of following the standard login process to access the system as a high-ranked MIS staffer, and this was far superior to a perhaps-limited user that we might have created with our INSERT approach.

We found the intranet site to be quite comprehensive, and it included – among other things – a list of all the users. It’s a fair bet that many Intranet sites also have accounts on the corporate Windows network, and perhaps some of them have used the same password in both places. Since it’s clear that we have an easy way to retrieve any Intranet password, and since we had located an open PPTP VPN port on the corporate firewall, it should be straightforward to attempt this kind of access.

We had done a spot check on a few accounts without success, and we can’t really know whether it’s “bad password” or “the Intranet account name differs from the Windows account name”. But we think that automated tools could make some of this easier.

Other Approaches

In this particular engagement, we obtained enough access that we did not feel the need to do much more, but other steps could have been taken. We’ll touch on the ones that we can think of now, though we are quite certain that this is not comprehensive.

We are also aware that not all approaches work with all databases, and we can touch on some of them here.

Use xp_cmdshell
Microsoft’s SQL Server supports a stored procedure xp_cmdshell that permits what amounts to arbitrary command execution, and if this is permitted to the web user, complete compromise of the webserver is inevitable.
What we had done so far was limited to the web application and the underlying database, but if we can run commands, the webserver itself cannot help but be compromised. Access to xp_cmdshell is usually limited to administrative accounts, but it’s possible to grant it to lesser users.
Map out more database structure
Though this particular application provided such a rich post-login environment that it didn’t really seem necessary to dig further, in other more limited environments this may not have been sufficient.
Being able to systematically map out the available schema, including tables and their field structure, can’t help but provide more avenues for compromise of the application.
One could probably gather more hints about the structure from other aspects of the website (e.g., is there a “leave a comment” page? Are there “support forums”?). Clearly, this is highly dependent on the application and it relies very much on making good guesses.

Mitigations

We believe that web application developers often simply do not think about “surprise inputs”, but security people do (including the bad guys), so there are three broad approaches that can be applied here.

Sanitize the input
It’s absolutely vital to sanitize user inputs to insure that they do not contain dangerous codes, whether to the SQL server or to HTML itself. One’s first idea is to strip out “bad stuff”, such as quotes or semicolons or escapes, but this is a misguided attempt. Though it’s easy to point out some dangerous characters, it’s harder to point to all of them.
The language of the web is full of special characters and strange markup (including alternate ways of representing the same characters), and efforts to authoritatively identify all “bad stuff” are unlikely to be successful.
Instead, rather than “remove known bad data”, it’s better to “remove everything but known good data”: this distinction is crucial. Since – in our example – an email address can contain only these characters:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
@.-_+
There is really no benefit in allowing characters that could not be valid, and rejecting them early – presumably with an error message – not only helps forestall SQL Injection, but also catches mere typos early rather than stores them into the database.

Sidebar on email addresses


It’s important to note here that email addresses in particular are troublesome to validate programmatically, because everybody seems to have his own idea about what makes one “valid”, and it’s a shame to exclude a good email address because it contains a character you didn’t think about.

The only real authority is RFC 2822 (which encompasses the more familiar RFC822), and it includes a fairly expansive definition of what’s allowed. The truly pedantic may well wish to accept email addresses with ampersands and asterisks (among other things) as valid, but others – including this author – are satisfied with a reasonable subset that includes “most” email addresses.

Those taking a more restrictive approach ought to be fully aware of the consequences of excluding these addresses, especially considering that better techniques (prepare/execute, stored procedures) obviate the security concerns which those “odd” characters present.


Be aware that “sanitizing the input” doesn’t mean merely “remove the quotes”, because even “regular” characters can be troublesome. In an example where an integer ID value is being compared against the user input (say, a numeric PIN):
SELECT fieldlist
  FROM table
 WHERE id = 23 OR 1=1;  -- Boom! Always matches!
In practice, however, this approach is highly limited because there are so few fields for which it’s possible to outright exclude many of the dangerous characters. For “dates” or “email addresses” or “integers” it may have merit, but for any kind of real application, one simply cannot avoid the other mitigations.
Escape/Quotesafe the input
Even if one might be able to sanitize a phone number or email address, one cannot take this approach with a “name” field lest one wishes to exclude the likes of Bill O’Reilly from one’s application: a quote is simply a valid character for this field.
One includes an actual single quote in an SQL string by putting two of them together, so this suggests the obvious – but wrong! – technique of preprocessing every string to replicate the single quotes:
SELECT fieldlist
  FROM customers
 WHERE name = 'Bill O''Reilly';  -- works OK
However, this naïve approach can be beaten because most databases support other string escape mechanisms. MySQL, for instance, also permits \’ to escape a quote, so after input of \’; DROP TABLE users; – is “protected” by doubling the quotes, we get:
SELECT fieldlist
  FROM customers
 WHERE name = '\''; DROP TABLE users; --';  -- Boom!
The expression ‘\” is a complete string (containing just one single quote), and the usual SQL shenanigans follow. It doesn’t stop with backslashes either: there is Unicode, other encodings, and parsing oddities all hiding in the weeds to trip up the application designer.
Getting quotes right is notoriously difficult, which is why many database interface languages provide a function that does it for you. When the same internal code is used for “string quoting” and “string parsing”, it’s much more likely that the process will be done properly and safely.
Some examples are the MySQL function mysql_real_escape_string() and perl DBD method $dbh->quote($value).
These methods must be used.
Use bound parameters (the PREPARE statement)
Though quotesafing is a good mechanism, we’re still in the area of “considering user input as SQL”, and a much better approach exists: bound parameters, which are supported by essentially all database programming interfaces. In this technique, an SQL statement string is created with placeholders – a question mark for each parameter – and it’s compiled (“prepared”, in SQL parlance) into an internal form.
Later, this prepared query is “executed” with a list of parameters:
Example in perl
$sth = $dbh->prepare("SELECT email, userid FROM members WHERE email = ?;");

$sth->execute($email);
Thanks to Stefan Wagner, this demonstrates bound parameters in Java:
Insecure version
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT email FROM member WHERE name = "
                             + formField); // *boom*
Secure version
PreparedStatement ps = connection.prepareStatement(
    "SELECT email FROM member WHERE name = ?");
ps.setString(1, formField);
ResultSet rs = ps.executeQuery();
Here, $email is the data obtained from the user’s form, and it is passed as positional parameter #1 (the first question mark), and at no point do the contents of this variable have anything to do with SQL statement parsing. Quotes, semicolons, backslashes, SQL comment notation – none of this has any impact, because it’s “just data”. There simply is nothing to subvert, so the application is be largely immune to SQL injection attacks.
There also may be some performance benefits if this prepared query is reused multiple times (it only has to be parsed once), but this is minor compared to the enormous security benefits. This is probably the single most important step one can take to secure a web application.
Limit database permissions and segregate users
In the case at hand, we observed just two interactions that are made not in the context of a logged-in user: “log in” and “send me password”. The web application ought to use a database connection with the most limited rights possible: query-only access to the members table, and no access to any other table.
The effect here is that even a “successful” SQL injection attack is going to have much more limited success. Here, we’d not have been able to do the UPDATE request that ultimately granted us access, so we’d have had to resort to other avenues.
Once the web application determined that a set of valid credentials had been passed via the login form, it would then switch that session to a database connection with more rights.
It should go almost without saying that sa rights should never be used for any web-based application.
Use stored procedures for database access
When the database server supports them, use stored procedures for performing access on the application’s behalf, which can eliminate SQL entirely (assuming the stored procedures themselves are written properly).
By encapsulating the rules for a certain action – query, update, delete, etc. – into a single procedure, it can be tested and documented on a standalone basis and business rules enforced (for instance, the “add new order” procedure might reject that order if the customer were over his credit limit).
For simple queries this might be only a minor benefit, but as the operations become more complicated (or are used in more than one place), having a single definition for the operation means it’s going to be more robust and easier to maintain.
Note: it’s always possible to write a stored procedure that itself constructs a query dynamically: this provides no protection against SQL Injection – it’s only proper binding with prepare/execute or direct SQL statements with bound variables that provide this protection.
Isolate the webserver
Even having taken all these mitigation steps, it’s nevertheless still possible to miss something and leave the server open to compromise. One ought to design the network infrastructure to assume that the bad guy will have full administrator access to the machine, and then attempt to limit how that can be leveraged to compromise other things.
For instance, putting the machine in a DMZ with extremely limited pinholes “inside” the network means that even getting complete control of the webserver doesn’t automatically grant full access to everything else. This won’t stop everything, of course, but it makes it a lot harder.
Configure error reporting
The default error reporting for some frameworks includes developer debugging information, and this cannot be shown to outside users. Imagine how much easier a time it makes for an attacker if the full query is shown, pointing to the syntax error involved.
This information is useful to developers, but it should be restricted – if possible – to just internal users.

Note that not all databases are configured the same way, and not all even support the same dialect of SQL (the “S” stands for “Structured”, not “Standard”). For instance, most versions of MySQL do not support subselects, nor do they usually allow multiple statements: these are substantially complicating factors when attempting to penetrate a network.

source: http://www.unixwiz.net/techtips/sql-injection.html

Windows 7 Transformation Pack

Windows 7 Transformation Pack

Download Size: 15272 KB

Filebox.ro Download : Click Here

Rapidshare.com Download : Click Here

Next Page »