Security Purity

Defend Your Site against Common Hack Attacks

Steve C Orr

October 30, 2009

17 Min Read
ITPro Today logo in a gray background | ITPro Today

ControlFreak

LANGUAGES:ALL

ASP.NETVERSIONS: 1.x | 2.x

 

Security Purity

Defend Your Site against Common Hack Attacks

 

By Steve C. Orr

 

Movies often portray hackers as evil super-geniuses orprodigy whiz kids. While there might be a few in the real world that almostlive up to that mythical status, the vast majority of modern day hackers areactually script kiddies who know little to nothing about the inner workings ofcomputer systems. Instead, they tend to find some pre-written malicious code orscript on the Internet and tinker with it, sometimes getting results thatharmonize with their dubious goals.

 

Indeed, there is very little originality left in thehacking world these days; it is much more evolutionary than revolutionary. Virtuallyevery variety of hacker exploit falls into one of several distinct, knowncategories (see Figure 1). By familiarizing yourself with these common attackvectors, you can craft resilient software that will not easily fall victim tosuch exploits. Read on and you ll also be introduced to some free Microsoftsoftware tools you can download to help secure your software s borders.

 

Hacker Attack

Description

Common Defenses

Social Engineering

Coaxing passwords and other valuable information from unsuspecting users through seemingly innocent conversation.

User education, two-factor authentication.

Dictionary

Cracking passwords by trying every word in a dictionary.

Require strong passwords, limit the number of failure retry attempts, two-factor authentication.

Brute Force

Cracking passwords by trying every possible combination of characters.

Require strong passwords, limit the number of failure retry attempts, two-factor authentication.

Replay

Network traffic is recorded and replayed later by a hacker after being adjusted to meet their dubious goals.

SSL, secure session management, authenticate every application layer, analyze your own network traffic, use the RegisterRequiresViewStateEncryption page method, threat modeling.

Man-in-the-Middle

Phishing, intermediate software that pretends to be a third-party Web site in order to collect passwords, credit card numbers, etc.

SSL, secure session management, authenticate every application layer, analyze your own network traffic, use the RegisterRequiresViewStateEncryption page method, threat modeling, user education.

Bots

Software that pretends to be a human Web site user and consumes resources without permission.

Turing-test technologies, such as CAPTCHA.

Denial of Service

Web servers are overwhelmed with dummy requests designed to consume CPU cycles.

Web farms with failover capability, code that fails early and intelligently.

Code Injection

SQL Injection, Cross Site Scripting (XSS), XPath Injection, etc. Causes a hacker s code to execute on others computers.

Use parameterized ADO.NET SQL queries, encode output, validate and filter input with white lists, set the Page s ViewStateUserKey property, use the Microsoft Anti-Cross Site Scripting Library.

Figure 1: Protectyour site against these common attack vectors by implementing appropriatedefensive measures.

 

Password Extraction

Most computer systems require only a username and passwordfor entry. Lists of usernames are easily obtained, as they are typically notconsidered secret. Passwords, on the other hand, tend to be a bit more of achallenge to acquire.

 

Social engineering is the art of convincing users towillingly divulge their passwords. Hackers may be stereotyped as nerds with fewsocial skills, but some of them (or their associates) do indeed have the giftof gab. You may be surprised how easy it can be to extract passwords and othersensitive information from unsuspecting employees with nothing more thanfriendly conversation. If schmoozing fails, the manipulator might try switchingto a more intimidating technique, such as demanding information on behalf ofthe CEO, FBI, or other authority figures. Technology alone cannot overcome suchunusually extraverted data extraction techniques; employee training is a keyfactor to help ensure workers don t naively divulge sensitive information.

 

Dictionary attacks are repetitive automated attempts touncover a user s password by sequentially supplying every word in a customizeddictionary as their password until a login attempt is finally successful.

 

Brute force attacks are the hacking technique most oftenillustrated in movies. Entry into a system is obtained by software thatsequentially tries every possible combination of characters until a password isfinally accepted.

 

Smart companies use two-factor authentication as a retortto the above exploits. Dictionary and brute force attacks are also mitigated byenforcing strong password requirements for users. (Strong passwords containlong combinations of uppercase and lowercase letters, along with numbers andsymbols.) Additionally, password entry failures should be logged and actionshould be taken after x number ofsequential bad password entries. For example, if a user has entered theirpassword incorrectly 10 times in a row, this is a highly suspicious situationindicative of a possible dictionary or brute force attack. In such situations,many modern and secure software systems cause a user s account to become lockedout for a certain period of time or until the user checks in through someother process. During the lockout period, all attempts to log in to that user saccount are met with rejection.

 

Packet Peeping

Modern applications pass tons of data across many kinds ofnetworks. Internal company networks, wireless networks, and the Internet areall leveraged for the services they provide. With all of these data packetsflying around, there are many opportunities for hackers to intercept them andpick them apart.

 

Replay attacks consist of previously recorded networktraffic that is later rebroadcast by a hacker instead of the original user. Ifthe replayed network traffic includes a user s login attempt, then a luckyhacker may essentially end up logged in as that user. If the user s passwordwas sent as plain text in that network request, the hacker can easily extractit and use it at will. In many cases, the hacker can alter the original networktraffic before replaying it to accomplish whatever sinister goals they mayhave.

 

An alternate form of replay attack involves using an HTTPanalyzer tool, such as Fiddler, to see what is being submitted from theirbrowser to the server (see Fiddler to learn more about Fiddler). These page requestscan be recorded, altered, and resubmitted to the server. This can result in theWeb server receiving malformed, unanticipated page requests that can cause theserver to respond in unexpected ways. Web developers should keep this in mindwhen designing Web pages and Web services to ensure sufficient resilience isbuilt in. Additionally, they should analyze their own traffic using a tool suchas Fiddler to help foresee any potential problems.

 

Man-in-the-middle attacks are similar to replay attacks,but are more complex. The hacker inserts their computer between a user and the Website the user was intending to visit (this is commonly accomplished byPhishing, although there are other ways, too). It intercepts the traffic comingfrom the user and extracts useful information, such as passwords and creditcard numbers. In some cases, the hacker then bails out because he has theinformation he sought but this is often a giveaway that something suspicioushappened. So more sophisticated tactics involve forwarding the traffic(sometimes slightly modified) to the Web site the user was intending to visit. Repliesfrom that Web site can be similarly intercepted and examined before being sentback to the user. If done properly, neither the user nor the Web site will haveany idea that anything unusual happened until perhaps later when the gatheredinformation is used maliciously.

 

The most common defense against network snooping like replayand man-in-the-middle attacks is Secure Sockets Layer (SSL). All networkcommunication is securely encrypted when SSL is used, rendering networksnooping rather pointless. Because this encryption requires a lot of processing(which slows things down considerably), it tends to be used only on pages thatdeal with sensitive information, such as passwords and credit card numbers. Usersvisiting an SSL-secured page will see a little lock icon in their browser, andthe page s address will start with https: instead of simply http: .

 

Sensitive ASP.NET pages should also consider calling thePage.RegisterRequiresViewStateEncryption method to ensure all data being storedin ViewState is encrypted (http://msdn2.microsoft.com/en-us/library/system.web.ui.page.registerrequiresviewstateencryption.aspx).The extra server processing required for this feature is worth it for pagesthat deal with information that users (or hackers) should not see.

 

Bots are infectious bits of software that pretend to behuman Web site users. They can replay network traffic, surf Web sites, sign upfor user accounts, and even send out spam through those accounts (via e-mail,messages, etc.). The worst bots can even take over a user s computer completely,turning it into a remote-control zombie at the mercy of the originating hacker.Often times these brainwashed computers are then used to execute denial ofservice attacks or other evil deeds. Bots are usually stopped cold by Turingtest technologies, such as CAPTCHA (for more on CAPTCHA, see CAPTCHASP).

 

Denial of service attacks happen when a Web site isbombarded with phony page requests. When successful, such an attack willoverwhelm a Web site s servers, causing the Web site to be unable to respond tolegitimate page requests from legitimate users. In effect, the hacker hasbrought down the Web site, making it inaccessible to the world. To helpmitigate such problems, large-scale Web sites should have server farms to sharethe load amongst many computers. No matter how large or small the Web site, itshould ideally be designed with a scalable architecture that can respond tochanging numbers of page requests and allow flexible deployment scenarios. It salso good to write intelligent code that fails as early as possible. Forexample, a quick validation of input parameters could weed out immediately asuspiciously malformed request, instead of blindly passing invalid parametersto a pointless, time-consuming database query.

 

Complex software applications often consist of many layers(presentation, business objects, data access, etc.) that may eventually bescattered across many servers at many locations. Every method on every objectin every layer is a potential hacker target, especially those that are publiclyexposed. Therefore, security should be carefully considered when designingevery method on every object in every layer. This already complex task iscomplicated further by the fact that there are usually many users in many rolesperforming many kinds of functions. For large applications, it can be virtuallyimpossible to perfectly analyze the nearly infinite number of ways that users(and hackers) could potentially interact with the system unless you have somegood tools to help you. One such tool is the free Microsoft Threat Analysis andModeling Tool (see Figure 2), available for download via the MicrosoftApplication Threat Modeling home page at http://msdn2.microsoft.com/en-us/security/aa570413.aspx.

 


Figure 2: Microsoft s free ThreatAnalysis and Modeling Tool can ferret out security holes while you re still inthe design phase, and identify potentially undiscovered holes in your existingapplications, as well.

 

Code Injection

Code injection is a common exploit that causes a hacker scode to be executed on another computer. This kind of exploit is widely coveredelsewhere, so I won t dive into it too deeply but I will cover the basics andpoint you toward more detailed references.

 

SQL injection is caused by a hacker entering carefullyconstructed bits of SQL code into an unsuspecting input field. Perhaps the useris normally expected to enter a ZIP code, but, instead, a hacker enters someSQL into that field. This exploit can only happen when a Web site blindlyaccepts unvalidated user input and concatenates it into a dynamicallyconstructed SQL string. Always use ADO.NET parameter objects for supplyingparameters instead of dynamically concatenating user input directly into a SQLstring. For more information on avoiding SQL injection attacks, visit http://msdn2.microsoft.com/en-us/library/ms998271.aspx.

 

Cross Site Scripting (XSS) is also caused by hackersentering carefully constructed malicious input into unsuspecting fields but insteadof SQL code, bits of JavaScript are entered into the field. In situations whereone user s input is later displayed to other users (such as a wiki or messageboard), the script is then executed on those other users computers. In manycases, this code is operating under the security context of that user or the Website they are visiting. Any security warnings that may pop up are often ignoredby users because they trust the site they are visiting and because they don tknow a hacker has compromised it.

 

XPath injection is another variation on the abovetechniques, where bits of XPath code are inserted into an unvalidated inputfield. In cases where that input is blindly concatenated into an XPathstatement, it can completely change the execution of that statement,potentially releasing reams of private data to the hacker.

 

To avoid code injection attacks, user input should alwaysbe validated and user-generated output should always be encoded.

 

User input should be validated on the client side withJavaScript for such reasons as usability and efficiency. User input shouldalways be validated on the server side, as well, as hackers have various tricksfor getting around client-side validation. ASP.NET s validation controls (see Validate User-entered Data) are useful for this becausethey are flexible and provide both client-side and server-side validation.

 

User input should be validated against a white listinstead of the more common black list approach. A black list contains a list ofcharacters or other input characteristics that are not permitted. The problemis, a clever hacker can often figure out what is contained in that list, thencarefully construct their malicious input to avoid those triggers. Conversely,a white list contains a more limited list of characters that are allowed allother input is rejected.

 

In case some malicious script does sneak its way into ashared content store, all user-entered content displayed in a Web page shouldfirst be encoded. Methods such as Server.HTMLEncode (http://msdn2.microsoft.com/en-us/library/ms525347.aspx)and Server.URLEncode (http://msdn2.microsoft.com/en-us/library/ms525738.aspx)can be used to help ensure the content is displayed as text and not executed asscript. Unfortunately, these classic methods use a black list approach thatonly encodes four potentially malicious characters. Any hacker that knows thiscan carefully construct malicious script that avoids those four characters and stillcause you problems. This is why I recommend using Microsoft s free Anti-CrossSite Scripting Library. It provides intuitive encoding and decoding functionsthat use a far more secure white list approach, which stops hackers in theirtracks. You can download the free Anti-Cross Site Scripting Library from http://msdn2.microsoft.com/en-us/security/aa973814.aspx.

 

Armored Authentication

When authenticating a user, essentially the question thatneeds to be answered is: Who are you? Unfortunately, the existence ofdishonest people necessitates the answers be verified. The best verificationsare obtained by having the user provide proof of knowledge and/or possessions.

 

Knowledge-based verification requires information that(theoretically) only the user knows. It is most often implemented in the formof a password, although secret question/answer pairs are a popular backup incases where the user has forgotten their password.

 

Possession-based verification requires users to providesomething that (theoretically) only they have. Modern companies tend toimplement possession-based verification in one of two ways: biometrics or smartcards.

 

Biometrics is a burgeoning industry. Because yourfingerprints are unique to the fingers that only you possess, a scan of them isa convincing way to verify your identity. Fingerprint readers are commonlybuilt in to many laptops these days. Retinal eye scanners seem to be morecommon in the movies, but they do exist sporadically in the real world, too. Similarsystems are catching on that use voice and face recognition. While biometricsare indeed valuable, they not infallible. For example, some scanners are betterthan others about telling the difference between a real finger and a fake onewith prints on it that were lifted from a recently touched drinking glass. Youshould also consider that any scan of body parts is (like all data) ultimatelybroken down into a series of ones and zeros inside the computer. If a hacker isable to obtain a copy of your unique pattern and replay it into the system,then they ve effectively stolen your identity possibly forever (you can t getnew fingers).

 

Smart cards are the only widely accepted form ofpossession-based verification besides biometrics. Employees are givenidentification badges that look much like credit cards. Each card has auniquely coded tamper-resistant computer chip embedded within it that isassociated only with its assigned owner. When a user wishes to enter a securebuilding or computer system, they insert their smart card into a card reader toverify their identity. Many people are more comfortable with smart cards thanbiometrics because smart cards are less invasive and they can be immediatelydeactivated and replaced if lost or stolen.

 

The most secure approach is to combine two or more of theabove verification techniques, preferably with a mix of both knowledge-basedand possession-based verification. Security experts agree that two-factor authenticationis a must for any organization that wishes to pride itself on rock-solidsecurity. For example, Microsoft requires its workers to provide both apassword and a successful smart card scan before being granted access to somesensitive internal resources.

 

Two-factor authentication makes a hacker s job nearlyimpossible. Even if they somehow extract your password, they cannot do anythingwith it because they don t have your smart card. Conversely, if they manage tosuccessfully pickpocket your smart card, they ll continue to suffer in futilitywithout your password. You could even take things a step further byimplementing three-factor authentication. There are some new smart cards on thehorizon that have built-in fingerprint scanners. A two-factor possession-basedverification device like that, combined with (knowledge-based) passwordverification, would be as close to 100% secure as any modern-day data guardiancould hope to achieve.

 

Because not all computer systems deal with top-secret,highly sensitive data, there are some other less-secure verification techniquesthat are often considered good enough for more casual scenarios. For example,verification e-mails are often sent to the e-mail address associated with auser. The user must then reply or click a link within the e-mail to prove theyreceived it, thereby verifying they are indeed the user associated with that e-mailaddress. Keep in mind that e-mail is not especially secure. E-mails oftenbounce through countless servers all over the globe before finally reachingtheir final destinations after being cached in many places. This exposesnumerous scenarios for interception. Because of this, you should avoid sendingpasswords via e-mail. Even if your system stores no sensitive data, be considerateof the possibility that your users may reuse passwords across systems, so youmay be inadvertently exposing a more valuable password than you think.

 

It should go without saying that passwords should bestored only in encrypted form, and should remain in encrypted form as much ofthe time as possible even in memory at run time. I suggest hashing passwordsbefore storage (http://SteveOrr.net/faq/Encrypt.aspx)so they are computationally infeasible to decrypt (even by you).

 

If you must store credit card numbers, then of course theyshould also be encrypted but I strongly recommend you avoid storing creditcard numbers at all. It s impossible to accidentally expose data that you donot possess, and therefore you cannot be held financially liable for thepotentially devastating effects that such a security breach could cause. Once acredit card has been processed, delete all records of it, except perhaps thelast four digits (for reference purposes).

 

Conclusion

There is no such thing as 100% secure. In the never-endingcat and mouse game between hackers and security professionals, every measure iseventually met with a countermeasure. Whenever valuable new technologies arereleased, new security holes are eventually discovered in them. In the unlikelyevent a perfect piece of software is ever written, it may still end upvulnerable through the components upon which it depends. For example, third-partycontrols, the underlying operating system, or the network infrastructure mayhave security holes that allow hackers to gain administrator access and wreakunlimited havoc.

 

Even though it s impossible to achieve a 100% securesoftware system, a good developer will strive to get as close as possible tothat goal. Armed with the information covered in this article, you can craftsoftware secure enough to deflect hackers toward easier targets elsewhere.

 

Steve C. Orr is anASPInsider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and authorof the book Beginning ASP.NET 2.0 AJAX by Wrox. He sbeen developing software solutions for leading companies in the Seattlearea for more than a decade. When he s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:[email protected].

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like