Comments 0

Document transcript

From the authorsof the bestsellingHACK PROOFING™YOUR NETWORKThe Only Way to Stop a HackerIs to Think Like One• Complete Coverage of ColdFusion 5.0 and Special BonusCoverage of ColdFusion MX• Hundreds of Damage & Defense,Tools & Traps,and Notesfrom the Underground Sidebars,Security Alerts,and FAQs• Complete Coverage of the Top ColdFusion Hacks™1YEAR UPGRADEBUYER PROTECTION PLANFrom the authorsof the bestsellingHACK PROOFING™YOUR NETWORKGreg MeyerDavid AnRob RusherSargeDaryl BanttariSteven CascoTechnical Editor193_HPCF_FC.qxd 3/22/02 3:10 PM Page 1solutions@syngress.comWith more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Ciscostudy guides in print, we continue to look for ways we can better serve theinformation needs of our readers. One way we do that is by listening.Readers like yourself have been telling us they want an Internet-based ser-vice that would extend and enhance the value of our books. Based onreader feedback and our own strategic plan, we have created a Web sitethat we hope will exceed your expectations.Solutions@syngress.com is an interactive treasure trove of useful infor-mation focusing on our book topics and related technologies. The siteoffers the following features:

One-year warranty against content obsolescence due to vendorproduct upgrades. You can access online updates for any affectedchapters.

“Ask the Author” customer query forms that enable you to postquestions to our authors and editors.

GetCollectionLanguage(collectionName)193_HPCF_TOC.qxd 3/19/02 2:52 PM Page xxiiIn preparation for the creation of this book I spent a weekend at my home inMassachusetts setting up one of my personal computers to be a testing server.Myhome is serviced by AT&T and we have a high-speed modem with a ﬁxed IPnumber.This,combined with the installation of some new software,made for a veryfun weekend of tweaking and adjusting until I had a very stable and solid develop-ment Web server to begin my work.The real fun,however,lay ahead.I let the machine run for the weekend and on Monday afternoon,I reviewed mylog ﬁles.Within 90 seconds of the machine being online and public to the world,itwas being sniffed and prodded.I took the liberty of tracing some of these invasivesurfers to their home computers.Here is what I found:Someone north of SeattleWA,for one,had (within two minutes of my being online) identiﬁed my IP number,determined that I was running a Microsoft Web server,and was trying to pass bufferoverﬂows and cryptic parameters to directories and pages in my Web root.Fortunately this script kiddie was trying to send URL parameters to folders and ﬁlesthat I had already removed during setup and all they got on their end were 404errors (ﬁle not found)—my way of saying:Go bug someone else’s machine!This small exercise turned into an excellent example of what is out there.When Isay out there,I mean anywhere out there.The attacker from Washington State mayhave just as easily come from overseas.Just being online means that you have all ofthe beneﬁts and all of the danger of being attached to the largest computer networkin the world.That being said,one of the reasons why so many people choose to go online isthe experience and content found in many Web sites,chat rooms and e-mail com-munication.Much of this content was built with the ColdFusion Markup Language(CFML).CFML came onto the market and has been adopted by hundreds of thou-sands of developers since 1995.The ColdFusion Server was the ﬁrst applicationserver available on any platform and their creators were ahead of their time.xxiiiForeword193_HPCF_Fore.qxd 3/19/02 11:42 AM Page xxiiixxiv ForewordOne of the key elements of ColdFusion is that it talks to and binds together coreInternet protocols and leading software vendor applications.With its tag based devel-opment environment,the ColdFusion developer is much more productive than his orher Java or C++ equivalents and as any economist will tell you,value and wealth areboth built on top of productivity.This book,Hack Prooﬁng ColdFusion,is the result of intense effort to bring thereader the most comprehensive and relevant info needed to help develop and deploysecure applications.This book came together by the joint effort of many developersand we hope that our experience and wisdom will help you in all stages of yourdevelopment efforts.Hack Prooﬁng ColdFusion opens up with a chapter helping the ColdFusion coderto begin thinking like a hacker;once you understand how most hackers approachtheir work,you will understand more clearly why and how you should secure yourColdFusion development.In the next chapter.we talk about common ways to breakinto systems as well as the countermeasures for protection against malicious users.The two chapters that follow will advise you on how to secure your ColdFusion tagsand advise you on best practices for your ColdFusion applications.As most ColdFusion developers know,there are two sides to creating applica-tions—there is the client-side development and the server-side conﬁguration;we’llcover this in detail in Chapter 5.In Chapters 6 and 7,we dive into securing yourColdFusion server and help you with the adjustments you need to make even whenthe installation is complete.The next two chapters deal with all of the issues related to the most popularoperating systems that ColdFusion runs on,discussing secure development issues forWindows,Solaris,and Linux.Chapter 10 explores the range of industry leadingdatabases and the security pitfalls that come with each of them,and Chapter 11 looksinto some of the complementary technologies and techniques that will help ensurethat your work will be secure.Chapter 12 takes a look ahead at the enhanced secu-rity features ColdFusion MX brings us.Whether you are trying to validate data types on your Web site or you are tryingto understand the best practices for tightening up your ColdFusion server’s operatingsystem,it’s all here.Best of luck to you.Code it right and make your app tight!—Steven CascoDirector of Interactive Technology,Philip Johnson AssociatesFounder and Chair of the Boston ColdFusion User GroupAdjunct Faculty Member,Northeastern Universitywww.syngress.com193_HPCF_Fore.qxd 3/19/02 11:42 AM Page xxivThinking Like aHackerSolutions in this chapter:

Understanding the Terms

Mitigating Attack Risk in Your ColdFusionApplications

Recognizing the Top ColdFusionApplication Hacks

Understanding Hacker Attacks

Preventing “Break-ins” by ThinkingLike a HackerChapter 11 Summary Solutions Fast Track Frequently Asked Questions193_HPCF_01.qxd 3/20/02 9:21 AM Page 12 Chapter 1 • Thinking Like a HackerIntroductionMacromedia claims on their Web site that their ColdFusion (CF) product “helpsyou build applications quickly,assemble powerful solutions easily,and deliver highperformance and reliability.” Unfortunately,the same properties that make it easyto produce applications in ColdFusion—rapid design and development,loosevariable typing,and a programming markup language easily accessible to nonpro-grammers—are attractive attributes to hackers.The purpose of this chapter to is to introduce you to the hackers who willtry to break into your ColdFusion Web application,and to suggest tactics thatyou can use in your application building to mitigate the risks of hacking.Hackerswill attempt to target the weakest links in your application:you should know inadvance what those areas are and how you can deter these malicious users fromcausing harm.The goal of hacking is not,however,limited to causing harm to anothercomputer system.Hackers range from inexperienced vandals—just showing offby defacing your site—to master hackers who will compromise your databases forpossible ﬁnancial gain.All of them may attain some kind of public infamy.The name “Kevin Mitnick” is instantly recognized by anyone in the Internetworld.Mitnick served years in prison for hacking crimes and became the posterchild for hackers everywhere,often times being viewed as the sacriﬁcial lamb(and therefore a cult hero) for all other hackers.Mitnick may have helped to bring hacking to the limelight recently,but hecertainly was far from the ﬁrst to partake in hacking.Due largely in part to therecent increase in the notoriety and popularity of hacking,a misconception per-sists among the general population that hacking is a relatively new phenomenon.Nothing could be further from the truth.The origins of hacking superseded theinvention of the Internet,or even the computer for that matter.As we discusslater in this chapter,various types of code breaking and telephone technologyhacking were important precursors.Throughout this book,you will be given development tools to assist you inhack prooﬁng your ColdFusion applications.We’ll give you a basic outline forapproaches to secure site management,writing more secure code,implementingsecurity plans,and helping you learn to think “like a hacker” to better protectyour assets,which may include site availability,data privacy,data integrity,and sitecontent.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 2www.syngress.comUnderstanding the TermsLet’s take a few minutes to be certain that you understand what it means whenwe talk about a “hacker.” Many different terms are used to describe a hacker,many of which have different connotations depending on who is describingwhom.Take a look at The Jargon File (http://info.astrian.net/jargon) to get asense of how the community has developed its own vocabulary and culture.Webster’s Dictionary appropriately deﬁnes hacking as a variety of things,including a destructive act that leaves something mangled,or a clever way to cir-cumvent a problem;a hacker can be someone who is enthusiastic about anactivity.Similarly,in the IT world,not every “hacker” is malicious,and hackingisn’t always done to harm someone.Within the IT community,hackers can beclassiﬁed by ethics and intent.One important deﬁning issue is that of public fulldisclosure by a hacker once he or she discovers a vulnerability.Hackers may referto themselves as white hat hackers,like the symbol of Hollywood’s “good guy”cowboys,meaning that they are not necessarily malicious;black hat hackers arehackers who break into networks and systems for gain or with malicious intent.However,deﬁning individuals by their sense of ethics is subjective and mis-leading—a distinction is also made for gray hat hackers,which reﬂects strong feel-ings in the community against the assumptions that come with either of theother labels.In any case,a unifying trait that all self-described “real” hackers shareis their respect for a good intellectual challenge.People who engage in hackingby using code that they clearly do not understand (script kiddies),or who hacksolely for the purpose of breaking in to other people’s systems (crackers),are con-sidered by skilled hackers to be no more than vandals.In this book,when we refer to “hackers,” we are using it in a general sense tomean people who are tampering,uninvited,with your systems or applications—whatever their intent.A Brief History of HackingHacking in one sense began back in the 1940s and 1950s when amateur radioenthusiasts would tune in to police or military radio signals to listen in on whatwas going on.Most of the time these “neo-hackers” were simply curious “infor-mation junkies,” looking for interesting pieces of information about governmentor military activities.The thrill was in being privy to information channels thatothers were not,and doing so undetected.Thinking Like a Hacker • Chapter 1 3193_HPCF_01.qxd 3/20/02 9:21 AM Page 34 Chapter 1 • Thinking Like a HackerHacking and technology married up as early as the late 1960s,when MaBell’s early telephone technology was easily exploited,and hackers discovered theability to make free telephone calls,which we discuss in the next section.Astechnology advanced,so did the hacking methods used.It has been suggested that the term hacker,when used in reference to com-puter hacking,was ﬁrst adopted by MIT’s computer culture.At the time,theword only referred to a gifted and enthusiastic programmer who was somewhatof a maverick or rebel.The original-thinking members of MIT’s Tech ModelRailroad Club displayed just this trait when they rejected the original softwarethat Digital Equipment Corporation (DEC) shipped with the PDP-10 mainframecomputer and created their own,called the Incompatible Timesharing System(ITS).Many hackers were involved with MIT’s Artiﬁcial Intelligence (AI)Laboratory.In the 1960s,however,it was the ARPANET,the ﬁrst transcontinental com-puter network,which truly brought hackers together for the ﬁrst time.TheARPANET was the ﬁrst opportunity for hackers to work together as one largegroup,rather than working in small isolated communities spread throughout theUnited States.The ARPANET gave hackers their ﬁrst opportunity to discusscommon goals and common myths and even publish the work of hacker cultureand communication standards (The Jargon File,mentioned earlier,was developedas a collaboration across the Net).Telephone System HackingA name that is synonymous with telephone hacking is John Draper,who went bythe alias “Cap’n Crunch.” Draper discovered that a whistle given away in thepopular children’s cereal perfectly reproduced a 2600-Hertz tone,which allowedhim to make free telephone calls.In the mid 1970s,Steve Wozniak and Steve Jobs (the very men who foundedApple Computer) worked with Draper—who had made quite an impression onthem—building “Blue Boxes,” devices used to hack into telephone systems bygenerating tones at certain frequencies that access idle lines.Jobs went by thenickname of “Berkley Blue,” and Wozniak went by “Oak Toebark.” Both menplayed a major role in the early days of phone hacking,or phreaking.Draper actually had a very good system established.He and a group of otherswould participate in nightly “conference calls” to discuss holes they had discov-ered in the telephone system.In order to participate in the call,you had to beable to do dual tone multi-frequency (DTMF) dialing,which is what we now referwww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 4Thinking Like a Hacker • Chapter 1 5to as a touch-tone dialing.During the 1970s,pulse dialing or wheel dialing phoneswere still the standard telephone company issue,so the blue box was the onlydevice a non-phone-company employee could use to emulate the signals a phonewas using.The line was actually an internal line for Ma Bell,and only a few peopleknew of its existence.What the phreaker had to do was DTMF dial into the linevia a blue box.Being able to access the special line was the basic equivalent tohaving root access into Ma Bell.The irony of this elaborate phone phreakingritual was that the trouble spots that were found were actually reported back tothe telephone company.The phreakers would call Ma Bell and advise them of thetrouble areas (all the while,the employees within Ma Bell thought that thephreakers actually worked for the telephone company).Sure,they were advisingMa Bell of stuck tandems and holes,but they were also stealing phone calls.As itturns out,John Draper was arrested repeatedly during the 1970s,and he ulti-mately spent time in jail for his involvement in phone phreaking.But possibly the greatest example ever of hacking/phreaking for monetaryreasons would be that of Kevin Poulsen to win radio contests.What Poulsen didwas hack into Paciﬁc Bell’s computers to cheat at phone contests that radio sta-tions were having.In one such contest,Poulsen did some fancy work andblocked all telephone lines so that he was every caller out of 102 callers.For thatparticular effort,Poulsen won a Porsche 944-S2 Cabriolet.Poulsen did not just hack for monetary gain,though;he was also involved inhacking into FBI systems and is accused of hacking into other governmentalagency computer systems as well.Poulsen hacked into the FBI systems to learnabout their surveillance methods in an attempt to stay in front of the people whowere trying to capture him.Poulsen was the ﬁrst hacker to be indicted underU.S.espionage law.Computer HackingAs mentioned earlier,computer hacking began with the ﬁrst networked com-puters back in the 1950s.The introduction of ARPANET in 1969,and NSFNetsoon thereafter,increased the availability of computer networks.The ﬁrst foursites connected through ARPANET were The University of California at LosAngeles,Stanford,the University of California at Santa Barbara,and theUniversity of Utah.These four connected nodes unintentionally gave hackers theability to collaborate in a much more organized manner.Prior to the ARPANET,hackers were able to communicate directly with one another only if they wereactually working in the same building.This was not all that uncommon of anwww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 56 Chapter 1 • Thinking Like a Hackeroccurrence,because most computer enthusiasts were congregating in universitysettings.With each new advance dealing with computers,networks,and the Internet,hacking also advanced.The very people who were advancing the technologymovement were the same people who were breaking ground by hacking,learning the most efﬁcient way they could about how different systems worked.MIT,Carnegie-Mellon University,and Stanford were at the forefront of thegrowing ﬁeld of AI.The computers used at universities,often the DEC PDPseries of minicomputers,were critical in the waves of popularity in AI.DEC,which pioneered commercial interactive computing and time-sharing operatingsystems,offered universities powerful,ﬂexible machines that were fairly inexpen-sive for the time,which was reason enough for numerous schools to have themon campus.ARPANET existed as a network of DEC machines for the majority of its lifespan.The most widely used of these machines was the PDP-10,originallyreleased in 1967.The PDP-10 was the preferred machine of hackers for almost15 years.The operating system,TOPS-10,and its assembler,MACRO-10,are stillthought of with great fondness.Although most universities took the same path asfar as computing equipment was concerned,MIT ventured out on their own.Yes,they used the PDP-10s that virtually everybody else used,but they did not opt touse DEC’s software for the PDP-10.MIT decided to build an operating systemto suit their own needs,which is where the ITS operating system came into play.ITS went on to become the time-sharing system in longest continuous use.ITSwas written in Assembler,but many ITS projects were written in the language ofLISP.LISP was a far more powerful and ﬂexible language than any other lan-guage of its time.The use of LISP was a major factor in the success of under-ground hacking projects happening at MIT.By 1978,the only thing missing from the hacking world was a virtualmeeting.If hackers couldn’t congregate in a common place,how would the best,most successful hackers ever meet? In 1978,Randy Sousa and Ward Christiansencreated the ﬁrst personal-computer bulletin-board system (BBS).This system isstill in operation today,and was the missing link that hackers needed to unite onone frontier.However,the ﬁrst stand-alone machine—including a fully loaded CPU,soft-ware,memory,and storage unit—wasn’t introduced until 1981 (by IBM).Theycalled it the “personal computer.” Geeks everywhere had ﬁnally come into theirown! As the 1980s moved forward,things started to change.ARPANET slowlystarted to become the Internet,and the popularity of the BBS exploded.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 6Thinking Like a Hacker • Chapter 1 7Near the end of the decade,Kevin Mitnick was convicted of his ﬁrst com-puter crime.He was caught secretly monitoring the e-mail of MCI and DECsecurity ofﬁcials and was sentenced to one year in prison.It was also during thissame time period that the First National Bank of Chicago was the victim of a$70 million computer crime.Around the same time that all of this was takingplace,the Legion of Doom (LOD) was forming.When one of the brightestmembers of this very exclusive club started a feud with another and was kickedout,he decided to start his own hacking group,the Masters of Deception(MOD).The ensuing battle between the two groups went on for almost twoyears before it was put to an end permanently by the authorities,and the MODmembers ended up in jail.In an attempt to put an end to any future shenanigans like the ones demon-strated between the LOD and the MOD,Congress passed a law in 1986 calledthe Federal Computer Fraud and Abuse Act.It was not too long after that lawwas passed by Congress that the government prosecuted the ﬁrst big case ofhacking.Robert Morris was convicted in 1988 for the Internet worm he created.Morris’s worm crashed over 6000 Net-linked computers.Morris believed thatthe program he wrote was harmless,but instead it somehow got out of control.After that,hacking just seemed to take off like a rocket ship.People were beingconvicted or hunted left and right for fraudulent computer activity.It was justabout the same time that Kevin Poulsen entered the scene and was indicted fortelephone tampering charges.He “avoided” the law successfully for 17 monthsbefore he was ﬁnally captured.Evidence of the advances in hacking attempts and techniques can be seenalmost every day on the evening news or in news stories on the Internet.TheComputer Security Institute estimates that 90 percent of Fortune 500 companiessuffered some type of cyber attack over the last year,and between 20 and 30 per-cent experienced compromises of some type of protected data by intruders.Withthe proliferation of hacking tools and publicly available techniques,hacking hasbecome so mainstream that businesses are in danger of becoming overwhelmedor even complacent.With the advent of “Web services” such as Microsoft’sPassport (www.passport.com) or AOL’s upcoming initiative,code-named “MagicCarpet,” the risk of a serious breach of security grows every day.In November2001,Passport’s “wallet” feature was publicly cracked,causing embarrassment forMicrosoft and highlighting the risks of embedding authentication and authoriza-tion models in Web applications that share data.The page at www.avirubin.com/passport.html describes the risk of the Passport system,and the page athttp://alive.znep.com/~marcs/passport/ describes a hypothetical attack againstwww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 78 Chapter 1 • Thinking Like a Hackerthat system.Companies that develop defense strategies will protect not onlythemselves from being the target of hackers,but also the consumers,because somany of the threats to Web applications involve the end user.Why Should I Think Like a Hacker?So,you might be asking at this point,“why does this history of hacking have any-thing to do with the ColdFusion application I’m building at the moment,or withthe legacy code that I am supporting in my enterprise or consulting business?”Learning about hacking will help you to anticipate what attacks hackers may tryagainst your systems,and it will help you to understand the world of the hacker.Stopping every attempted hack is impossible.However,mitigating the effectsof that hack is clearly possible.Armed with knowledge of a hacker’s motivationand the places where your ColdFusion application may be vulnerable,you caneliminate many of the most obvious security holes in your code.What Motivates a Hacker?Notoriety,challenge,boredom,and revenge are just a few of the motivations of ahacker.Hackers can begin the trade very innocently.Most often,they are hackingto see what they can see or what they can do.They may not even realize thedepth of what they are attempting to do.However,as time goes on,and theirskills increase,they begin to realize the potential of what they are doing.There isa misconception that hacking is done mostly for personal gain,but that is prob-ably one of the least of the reasons.More often than not,hackers are breaking in to something so that they cansay they did it.The knowledge a hacker amasses is a form of power and prestige,so notoriety and fame—among the hacker community—are important to mosthackers.(Mainstream fame generally happens after they’re in court!)Another reason is that hacking is an intellectual challenge.Discovering vul-nerabilities,researching a mark,ﬁnding a hole nobody else could ﬁnd—these areexercises for a technical mind.The draw that hacking has for programmers eagerto accept a challenge is also evident in the number and popularity of organizedcompetitions put on by hacker conferences and software companies.Boredom is another big reason for hacking.Hackers may often just look aroundto see what sort of forbidden things they can access.Finding a target is often aresult of happening across a vulnerability,not seeking it out in a particular place.Revenge hacking is very different.This occurs because,somewhere,somehow,somebody made the wrong person mad.This is common for employees whowww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 8Thinking Like a Hacker • Chapter 1 9were ﬁred or laid off and are now seeking to show their former employer what astupid choice they made.Revenge hacking is probably the most dangerous formof hacking for most companies,because a former employee may know the codeand network intimately,among other forms of protected information.As anemployer,the time to start worrying about someone hacking into your computersystem is not after you let one of the network engineers or developers go.Youshould have a security plan in place long before that day ever arrives.Ethical Hacking versus Malicious HackingAsk any developer if he has ever hacked.Ask yourself if you have ever been ahacker.The answers will probably be yes.We have all hacked,at one time oranother,for one reason or another.Administrators hack to ﬁnd shortcuts aroundconﬁguration obstacles.Security professionals attempt to wiggle their way into anapplication/database through unintentional (or even intentional) backdoors;theymay even attempt to bring systems down in various ways.Security professionalshack into networks and applications because they are asked to;they are asked toﬁnd any weakness that they can and then disclose them to their employers.Theyare performing ethical hacking in which they have agreed to disclose all ﬁndingsback to the employer,and they may have signed nondisclosure agreements toverify that they will not disclose this information to anyone else.However,youdon’t have to be a hired security professional to perform ethical hacking.Ethicalhacking occurs anytime you are “testing the limits” of the code you have writtenor the code that has been written by a coworker.Ethical hacking is done in anattempt to prevent malicious attacks from being successful.Malicious hacking,on the other hand,is completed with no intention of dis-closing weaknesses that have been discovered and are exploitable.Malicioushackers are more likely to exploit a weakness than they are to report the weak-ness to the necessary people,thus avoiding having a patch/ﬁx created for theweakness.Their intrusions could lead to theft,a distributed denial-of-service(DDoS) attack,defacing of a Web site,or any of the other attack forms that arelisted throughout this chapter.Simply put,malicious hacking is done with theintent to cause harm.Somewhere in between the deﬁnition of an ethical hacker and a malicioushacker lies the argument of legal issues concerning any form of hacking.Is it evertruly okay for someone to scan your ports or poke around in some manner insearch of an exploitable weakness? Whether the intent is to report the ﬁndings orto exploit them,if a company hasn’t directly requested attempts at an intrusion,then the “assistance” is unwelcome.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 910 Chapter 1 • Thinking Like a HackerMitigating Attack Risk in YourColdFusion ApplicationsKnowing how hackers think and understanding the history of hacking is animportant ﬁrst step toward securing your ColdFusion applications.However,trulyunderstanding the way that hackers work is the most signiﬁcant step you can taketo protect your code and your servers.www.syngress.comHow Much Work Should IDo to Secure My Web Site?Understanding how much work you should undertake to secure yourWeb site depends on how secure you need your Web site to be.You can follow some simple rules to help you decide how muchwork you should do to secure your Web site:

Is the content or data of particularly high value? As the costof replacing your data goes up, you should spend more timereviewing the potential hazards.

What kind of hacker might be attracted to this site, and whatis the type of damage he might easily be able to inﬂict onthe site? Know how your site works, and anticipate both thepotential of attacks and techniques that you will use to repelthese attacks in your code.

Is the rest of your network secure? From “social engineering”techniques such as calling your company on the telephoneand trying to learn secret information, to simply walking intoan insecure server room, there are plenty of tactics hackerscan try that code alone will not deter.The bottom line, however, is to know how valuable your data maybe, both to you and to your customers, whether that data represents alarge consumer venture or private family information. Risk managementis the name of the game, and you need to know what you have beforeyou can adequately assess the level of protection necessary for your site.Err on the side of protecting your data and you’ll have a good start atsolving the problem.Damage & Defense…193_HPCF_01.qxd 3/20/02 9:21 AM Page 10Thinking Like a Hacker • Chapter 1 11Recognizing the top ColdFusion application hacks is one key to your successin repelling hacker attacks.Responding to the issues created by these applicationshortcomings is a more complicated task.You can address common problems cre-ated by the loose variable typing,unstructured application design,and ease of useof the ColdFusion system by following a few easy conventions:

Validate input to your pages.For example,make sure that theinteger you think you are seeking is trapped by your code and revealedto be an integer.We’ll discuss validation later in this section.

Encapsulate commonly used functionality in custom tags.UseColdFusion’s native capability to call templates written in ColdFusionMarkup Language (CFML) as Just-In-Time (JIT) compiled objects andto reference those common objects from multiple places in an applica-tion,keeping your code in easily maintained chunks.You can referencethese custom tags directly in your code,or you may choose to useCFMODULE to call custom tags more seamlessly.We’ll discuss this laterin this section as well.

Use external validation such as rows in a database to maintainyour user information.It may seem like a simple truth,but keepinginformation out of the URL query string can be the smartest and mostdifﬁcult thing to do in maintaining your application’s security.Useunique identiﬁers such as encrypted cookies to mark the user,and changethese identiﬁers periodically to prevent cookie or session spooﬁng.

Document,document,and document your code.Rememberingwhat you were trying to do six months ago when you “only needed toadd a hard-coded value in your staging site” from the code itself mayresult in a security hole being deployed into production accidentally.

Test your code!You’d be surprised to know how many new featuresleak into production with unintended results because a developer wastold to “just launch it” instead of ﬁnishing (or at least writing) the testplan to address the functionality of new code.

Handle your errors,and give yourself a safety net.The sys-temwide error-handling template introduced in ColdFusion 4.5 willgive you the opportunity to display a standard error template whenerrors occur.This blanket protection does not remove the need to traperrors on an application or page basis,but will give you some time to ﬁxerrors before hackers realize the errors are there.Don’t give the hackermore information than he or she needs to know,and conﬁgure yourwww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 1112 Chapter 1 • Thinking Like a HackerColdFusion server appropriately to limit the amount of debugginginformation returned with an error.These conventions will not prevent hackers from trying to break into yourapplication,but they will remove some of the basic mistakes you might make.These are suggestions for ColdFusion applications,but also have implications forRapid Application Development (RAD) in general.For more information,youmight want to review Syngress Publishing’s Hack Prooﬁng Your Web Applications(ISBN 1-928994-25-3),which has signiﬁcant coverage of development best prac-tices,or Steve McConnell’s Code Complete:A Practical Handbook of SoftwareConstruction (ISBN 1-55615-484-4).In addition,you must understand the basic types of attacks commonly perpe-trated by hackers to be successful in protecting your ColdFusion application.Applying these lessons to your code and “thinking like a hacker” will help you todeter hackers from easy access to your site.Knowing the speciﬁc ways hackers may try to attack ColdFusion applicationsis also crucial to protecting your applications.One particular attack occurred in1999,using vulnerabilities built into sample applications distributed withColdFusion before the ColdFusion 4.5 release.It caused particular pain toadministrators of ColdFusion servers.Security researcher Rain Forest Puppy ofWiretrip.net pointed out that these example applications could be exploited toreveal the contents of any text ﬁle on the server,leaving the box vulnerable toattack.Combining this exploit with a ﬁle uploading utility in these same exampleapplications,hackers were able to alter unprotected ColdFusion servers almost atwill.Although the ﬁx to these problems was simply to remove the example appli-cations from the server,many administrators did not heed this advice.Theresulting hacks were covered in a feature story in The New York Times Magazine,and Allaire subsequently changed the way the ColdFusion server installationfunctioned,making such example applications optional rather than mandatory.More recent attacks were acknowledged by Macromedia to cause “…unautho-rized read and delete access to ﬁles on a machine running ColdFusion Server.The other issue could allow ColdFusion Server templates to be overwritten witha zero byte ﬁle of the same name.”For Macromedia’s best practice recommendations regarding the 1999,seeMacromedia Product Security Bulletin (MPSB01-08),8/7/01,www.macromedia.com/v1/handlers/index.cfm?id=21700&method=full.Download Macromedia’ssecurity patches (for ColdFusion 2.0 - 4.5.1 Service Pack 2 on all platforms) forthese vulnerabilities at Macromedia Product Security Bulletin (MPSB01-07),7/11/01,www.macromedia.com/v1/handlers/index.cfm?id=21566&method=full.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 12Thinking Like a Hacker • Chapter 1 13Not everyone can have access to new versions of the server,which allegedlyﬁx these issues.You can recognize the problems inherent to ColdFusion thathackers might likely target,however,and address those defects in your code byvalidating page input and promoting modular code.Validating Page InputValidating page input takes many forms.A few ways in which you can implementinput validation include:Always scope your variables.Never use <cfset myVariable= "some value">when you could use <cfset variables.myVariable = "some value"> to force that vari-able declaration to be local to the page template.Scoping variables also increasesperformance.Using <CFPARAM>.Use <CFPARAM> to set the scope and value type ofthe variable you expect on a page:<CFPARAM NAME="Anniversary" TYPE="Date">.If the variable supplied is not of the speciﬁed scope and type,CF willthrow an error and stop processing the page.Validate form ﬁelds.There are two ways to perform form ﬁeld validation inCF:Server-side and client-side.CF performs server-side form validation whenyou use HTML form hidden ﬁelds to specify one of CF’s validation sufﬁxes:_integer,_ﬂoat,_range,_date,_time,_eurodate.The CFFORM controls,cﬁnput andcftextinput,allow you to specify the validate attribute for validating input data.CFFORM generates client-side JavaScript to perform this validation.Likewise,the other CFFORM controls allow you to specify the onvalidate attribute towhich you can pass valid JavaScript functions to perform input validation.See theCF Help documentation for further details and examples.Using Decision Functions.CF provides numerous functions for validatingstring data:Val,isDeﬁned,isNumeric,isBinary,isDate,isStruct,etc.These functionsreturn a Boolean value,which makes them ideal for CFIF evaluations,such as<CFIF isNumeric(URL.myID)>.See the CFML Language Reference—DecisionFunctions for more details and examples.Using <CFQUERYPARAM>.Use the <CFQUERYPARAM> tag in yourSQL WHERE clauses to validate SQL query parameters against valid SQL datatypes.<CFQUERYPARAM> also tends to speed database processing by usingbind parameters where the database permits.Using the request scope.Use <cfset request.myVariable = "some value"> tocreate a variable in the request scope that will persist for the length of the CFrequest (making it available to all included templates within the request).This is awww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 1314 Chapter 1 • Thinking Like a Hackerhandy way to make data persist beyond the current template,but yet avoid thenecessity to use <CFLOCK> to prevent that data from being dynamically over-written by the server.Locking access to application,server,and session scopes.<CFLOCK> isnecessary to ensure that variables in shared-scopes (application,server,and ses-sion) are not overwritten accidentally during concurrent thread access (reads/writes) in the course of normal application processing by the ColdFusion server.Old code may not have <CFLOCK> calls written into it,as this feature wasintroduced in CF 4.01 to improve server stability and scalability.CF 4.5 improvedthe locking methodology by offering granular server-side locking in theAdministrator,and introducing Scope locking in the <CFLOCK> tag.For moreon locking,see Macromedia TechNote 20370,ColdFusion Locking Best Practicesin (www.macromedia.com/v1/Handlers/index.cfm?ID=20370&Method=Full).Avoiding the need to use <CFLOCK>.<CFLOCK> is difﬁcult to use welland not necessary for many applications.Avoid using it whenever possible.The bestmethod is to move your shared-scoped variables to the Request scope (mentionedabove).Also,you can use Automatic read locking in the CF Administrator (4.5 and up)to catch shared-scope variable reads.This catch-all setting throws an error onshared-scope writes,and also introduces performance overhead.See MacromediaTechNote 14165,Changes to <CFLOCK> in CF server 4.5 (www.macromedia.com/v1/Handlers/index.cfm?ID=14165&Method=Full) for more details.Functionality with Custom Tags and CFMODULEA little-used feature of the Custom Tag framework in ColdFusion is the ability topass all attributes to the AttributeCollection parameter shared by every custom tag.Your code to call the custom tag <cf_foo> might look like this:<cf_foo attribute1 = "myValue"attributes2 = "myOtherValue">or you could assemble these values in a script,and pass them to the custom tagfrom a structure (ColdFusion’s term for an associative array of name-value pairs):<cfscript>stMyVariables = structNew(); //makes a new structurestMyVariables.attribute1 = "myValue";stMyVariables.attribute2 = "myOtherValue";//we can pass in static or dynamic values</cfscript>www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 14Thinking Like a Hacker • Chapter 1 15<cf_foo attributeCollection = "#stMyVariables#">This,of course,is very similar to the way modular code can be called using<CFMODULE>.The same example might look like:<cfmodule name = "mytags.cffoo"attribute_name1 = "myValue"attribute_name2 = "myOtherValue">or<cfmodule name = "/mytags/foo.cfm"attributeCollection = "#stMyVariables#">The larger point here is that modular code is a good thing.Writing modular codeusing custom tags gives you the following beneﬁts:

Easily maintainable changes.Update your code in one place,andchange it globally in the application.

Access to variable scopes.The caller and attribute variable scopesallow you to pass information to and from ColdFusion templates andcustom tags,and to share information dynamically with child tags.

Modular protection.Applying a security layer as one included ﬁle inall of your custom tags can make it easier for you to enforce global pro-tections,such as a global authentication scheme.By writing modular code in general and using conventions like ColdFusioncustom tags and page validation in speciﬁc,you can help yourself to avoid the topColdFusion application hacks.The Top ColdFusion Application HacksBy this point,you have probably thought about entry points in your own appli-cations that may be vulnerable to hackers.Let’s step back for a minute and discussthe most common ColdFusion application hacks you are likely to ﬁnd.By“hack,” remember,we are not only describing unintended consequences perpe-trated by a hacker,but perhaps also unintended functionality that may show up inyour ColdFusion application as it interacts with other applications.So,what are the top ColdFusion application hacks? This chapter describesthem as follows:www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 1516 Chapter 1 • Thinking Like a Hacker

Form ﬁeld manipulation,or the unintended use of form ﬁelds throughthird-party posts to pages or templates.

URL parameter tampering,or using the query string in the URL to accessfunctionality in the application to which the user should not have access.

ColdFusion’s Remote Development Service (RDS),which offers a viewinto the system where ColdFusion is running as the user context under whichthe ColdFusion server is running.This,as you might guess,might not be thesame user context under which the user can normally access the system.In the following section,as we discuss each common problem and the approachto mitigate problems caused by that problem,keep a few themes in mind:

Know what you are getting.Validate input to your pages to avoidform-ﬁeld manipulation and URL tampering.

Reuse code.Use custom tags and other objects such as database storedprocedures to encapsulate access to your data and to limit the number ofplaces where you need to update your code.This will limit your exposureto the number of places where you access ﬁles,thereby reducing mistakes.

Don’t trust the application.Code your templates so that they can beused only by certain other templates;you can use the Application.cfm andOnRequestEnd.cfm templates to assist you in this task.This techniquewill protect your code from being hijacked by malicious clients who mayattempt cross-site scripting.

Employ external validation.Use more than one method to authenti-cate the client.Simply using a cookie is not sufﬁcient;better would bethe use of an encrypted cookie in the browser to identify a record in thedatabase.This technique will help your security be stronger throughoutyour application.

Don’t expose valuable information in URL or Form variables.Instead,use URL or Form variables as pointers to get to the actual data,relying on other tokens for authentication.Leaving these variables on thequery string invites hackers to manipulate this data,to see how easily theycan break your site.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 16Thinking Like a Hacker • Chapter 1 17Form Field ManipulationColdFusion makes handling form input very easy.Simply code an HTML formwith the action set to a page that handles the input,pulling variables from theform scope,and you can gather and respond to user input.Too many developers,however,are careless in their form-handling code.The features offered inColdFusion that were intended to make the product more usable (such as theway the engine searches through all of the variable scopes to ﬁnd a value for anunscoped variable) can be used by hackers to break your application or to causeunintended results.Consider the code shown in Figure 1.1.Figure 1.1Improper Form Action Code<cfparam name="myFieldName" default="fname"><cfparam name="dsn" default="MyDSN"><cﬁf IsDeﬁned("form.ﬁeldnames)"><!---if we've found the variable form.ﬁeldnames, ---><!---a form post has been received---><cfquery name="getUsers" datasource="#dsn#">select #myFieldName#from userswhere userID = #userID#</cfquery><cfoutput>Your column, #myFieldName#, yielded the following result:<br>#valueList(getUsers.myFieldName)#</cfoutput><cfelse><h3>An Extremely Simple, Poorly-Coded Form Action Page</h3><form action="#cgi.script_name#" method="post"><input type="text" name="myFieldName"><br><input type="submit" name="submit" value="submit"></form></cﬁf>www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 1718 Chapter 1 • Thinking Like a HackerThis form action page does a few things well:

The form self-posts—by using the cgi.script_name value,you can create aform that will run wherever it is located.Avoiding the use of a hard-coded directory or action template makes it easier to code a modularform that can be used in many places in your application.If you like,you can use this structure to embed forms in your custom tags.

The form checks for the existence of a variable scope by using the existence of aknown variable,form.ﬁeldnames,to conﬁrm that a form has been submittedand that form scope variables are available.In ColdFusion 5.0,you can usethe <CFDUMP> tag to inspect the contents of a variable scope;forexample,<CFDUMP var="#form#"> to check and output the contentsof the form scope.This capability is available in ColdFusion 4.x,but mustbe coded manually as a custom tag.This capability is available inColdFusion 4.x,but must be coded manually as a custom tag,such as the<cfa_dump> Spectra tag (precursor to the <CFDUMP> CF 5.0 tag).

The template sets default values for variables by using <CFPARAM> to setthe default value for the myFieldname value used on the page and for thedatasource used in the <CFQUERY> call.

The code speciﬁes scopes for output variables,setting the scope ofmyFieldName variable used in the valuelist() call to the myFieldNamevariable returned from the getUsers query,not from some othermyFieldName variable.The code in Figure 1.1,however,does many things poorly:

The form doesn’t scope all of its variables and refers to unscoped variablessuch as myFieldName,dsn,and UserID in the code.Because ColdFusionchecks all of the variable scopes before throwing an error when itencounters an unscoped variable,an attacker could post a form to thisaction page.This action would satisfy the initial error handling thatchecks for the existence of form.ﬁeldnames,and allow the hackers to sub-stitute arbitrary values for the myFieldName,dsn,and UserID variables.Depending upon what your code does,this hack could be an annoyanceor a serious security breach.

This template fails to validate an integer ﬁeld,passing the UserID ﬁeldunchanged to the <CFQUERY> tag.This is a very dangerous codingmistake,because it allows a hacker to insert arbitrary SQL commandswww.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 18Thinking Like a Hacker • Chapter 1 19into your <CFQUERY> tag.Fortunately,this is an easy problem to ﬁx:simply validate the UserID ﬁeld with ColdFusion’s val() function,whichreturns a harmless 0 if the value in the tested variable is not an integer.

The code uses a dynamic SQL query,which although sometimes useful canbe a very dangerous item to include in your templates.Because the spe-ciﬁc ﬁeld is not listed at the time the template is being called,the querycan be manipulated in unpredictable ways.It is not recommended toallow users to return a speciﬁc column name from a query dynamically;instead,consider using stored procedures to return an entire record refer-enced by a key ﬁeld (in this case,UserID).This method allows you toallow the database server to do more processing and extends your abilityto add modular error-handling code inside of your stored procedures.

The code fails to set a speciﬁc scope in deﬁned variables,setting myFieldNamein the <CFPARAM>,rather than variables.myFieldname,which wouldcreate a variable only for the local template,or form.myFieldName,whichwould expect only a value for the myFieldName variable from the formthat you submitted.In addition,the DSN value is not scoped either,leaving it vulnerable to attack.You can use request.dsn to hold the valueof your datasource,and set it in your Application.cfm ﬁle.Because theApplication.cfm is run on every request,this action ensures that yourvariable will be available to every template in your application.

This template doesn’t check the cgi.http_referer value against a list ofknown pages or of known domains to make sure the form is beingcalled from an expected page.Use a simple version of this technique tocheck the cgi.http_referer value conditionally;for a more complicated andfunctional version,you might want to use a stored procedure or acustom tag to look up a list of known pages that correspond to thispage.To implement this,you will need to identify each of your CFMLtemplates in a data table,and load this information as a structure intomemory in your Application.cfm (not recommended),or use a simplequery lookup to ﬁnd the information (recommended).The listing in Figure 1.1 is intended to be an oversimpliﬁed example of poorcoding,but it contains common mistakes to avoid and trap in your code.Thesame code,after ﬁxing these bugs,might look like Figure 1.2.www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 1920 Chapter 1 • Thinking Like a HackerFigure 1.2Improved Form Action Code<cﬁf cgi.http_referer does not contain "myDomain.com"><!---check to see where they are coming from ---><!---this functionality could be encapsulated further ---><cﬂocation url="/index.cfm"></cﬁf><!---set variable scopes ---><cfparam name="variables.myFieldName" default="fname"><cfparam name="variables.dsn" default="#request.dsn#"><cﬁf IsDeﬁned("form.ﬁeldnames)"><cﬁf IsDeﬁned("form.myFieldName")><cfset variables.myFieldName = form.myFieldName><!---ﬁnding the variable form.ﬁeldnames---><!---shows that post has happened ---><!---call stored procedure ---><cfquery name="getUsers" datasource="#dsn#">sp_getUserinfo (#val(form.userID)#,'#variables.myFieldName#')</cfquery><cfoutput>Your column, #variables.myFieldName#,yielded the following result:<br>#valueList(getUsers.myFieldName)#</cfoutput><cfelse><h3>An Extremely Simple, Poorly-Coded Form Action Page</h3><form action="#cgi.script_name#" method="post"><input type="text" name="myFieldName"><br><input type="submit" name="submit" value="submit"></form></cﬁf>www.syngress.com193_HPCF_01.qxd 3/20/02 9:21 AM Page 20Thinking Like a Hacker • Chapter 1 21URL Parameter TamperingOften it is useful to pass variables through the query string in your ColdFusionapplication.Taking static,and sometimes dynamic,values though the URL scope isa handy way to rearrange data without using a form post.Using URL parametersallows you to take action against your application without user effort,but hackersrelish the opportunity to take advantage of this code.Your goal,of course,is to makeit more difﬁcult for these mischievous users to use your code in unintended ways.Your ﬁrst rule of business in deciding which variables to pass in the querystring should be to understand how those variables can be used and abused.AURL such as:http://mydomain.com/index.cfm?user=34&item=cart&method=add&cartitem=34&qItem=3is useful for adding an item to user 34’s virtual cart.However,a malicious usercould use a similar URL:http://mydomain.com/index.cfm?user=34&item=cart&method=chargeCCCard&cartitem=34&qItem=30000to decidedly different effect.Few developers would expose such a careless error;yet many developers are doing just that in their code by failing to validate theURL input they receive from the query string.www.syngress.comDon’t Rely on CFID and CFTOKEN Variables in URLsThe CFID and CFTOKEN variables, set by ColdFusion when using cookies tomaintain session variables, can be spoofed easily by rogue hackers. Avoidthe use of these variables alone to establish session states, using insteadan encrypted cookie or an authentication challenge when a user entersyour site from an outside URL. You can use a UUID token to identify theuser, either stored in a cookie or passed on the query string. Additionally,you can increase the strength of CFTOKEN by making it a UUID value. SeeMacromedia TechNote 22427, ColdFusion Server: How to GuaranteeUnique CFToken Values (www.macromedia.com/v1/Handlers/index.cfm?ID=22427&Method=Full). Also, in a clustered situation, it is possibleto generate duplicate CFID (and less likely, CFTOKEN) variables becauseColdFusion uses an incremental count to establish the CFID value.Damage & Defense…193_HPCF_01.qxd 3/20/02 9:21 AM Page 2122 Chapter 1 • Thinking Like a HackerOnce you decide to pass variables on the query string,you must decide howto validate the input you are receiving from the user.The approaches are similarto those you would use in validating form input:

Use combinations of variables to validate your input.If you are gatheringitems to place in a shopping cart,for example,validate both the categoryof the item and the unique item ID.This will force your attacker tolearn more than one parameter in your application,although it will onlyslow the hacker down.

Require an authentication token or a speciﬁc URL to use the page.Onceagain,check the http_referer value to understand where the http request isoriginating so that you can determine if it is a valid request;if not,sendthe request to an error-handling page or the front page of your applica-tion,where you can set default application values.In addition,you maywant to require the use of a valid user ID,which you can set by usingthe CreateUUID() function in ColdFusion.This is not a foolproofmethod,but will give you a relatively random identiﬁer with which toidentify your client.

Use <CFSWITCH> to limit the number of string values you canreceive when passing actions with known keywords to your application.Figure 1.3 shows an example of the processing you might do onreceiving a request for your CFML template containing the URLparameter “item” deﬁning a module in your code and “method” deﬁningthe method that item should take.Figure 1.3Code Snippet Using CFSWITCH to Limit URL Input<cfparam name="url.item" default="myItem">