The goal of the Windows Security Push, as it became known, was to educate the entire team about the latest secure codingtechniques, to find design and code flaws, and to improve test cod
Trang 1Copyright © 2003 by Microsoft Corporation
Trang 3Press International directly at fax (425) 936-7329 Visit our Web site at www.microsoft.com/mspress Sendcomments to mspinput@microsoft.com
Trang 5During February and March of 2002, all normal feature work on Microsoft
Windows stopped Throughout this period, the entire development team turnedits attention to improving the security of the next version of the product,
Windows NET Server 2003 The goal of the Windows Security Push, as it
became known, was to educate the entire team about the latest secure codingtechniques, to find design and code flaws, and to improve test code and
documentation The first edition of this book was required reading by all
members of the Windows team during the push, and this second edition
documents many of the findings from that push and subsequent security pushesfor other Microsoft products, including SQL Server, Office, Exchange, SystemsManagement Server, Visual Studio NET, the NET common language runtime,and many others
The impetus for the Windows Security Push (and many of the other securitypushes) was Bill Gates's “Trustworthy Computing” memo of January 15, 2002,which outlined a high-level strategy to deliver a new breed of computer systems,systems that are more secure and available Since the memo, both of us havespoken to or worked with thousands of developers within and outside Microsoft,and they've all told us the same thing: “We want to do the right thing—we want
to build secure software—but we don't know enough yet.” That desire and
uncertainty directly relates to this book's purpose: to teach people things theywere never taught in school—how to design, build, test, and document secure
The consequences of compromised systems are many and varied, including loss
of production, loss of customer faith, and loss of money For example, if anattacker can compromise your application, such as by making it unavailable,your clients might go elsewhere Most people have a low wait-time threshold
Trang 6The real problem with numerous software development houses is that security isnot seen as a revenue-generating function of the development process Because
of this, management does not want to spend money training developers to writesecure code Management does spend money on security technologies, but that'susually after a successful attack! And at that point, it's too late—the damage hasbeen done Fixing applications post-attack is expensive, both financially and interms of your reputation
Protecting property from theft and attack has been a time-proven practice Ourearliest ancestors had laws punishing those who chose to steal, damage, or
trespass on property owned by citizens Simply, people understand that certainchattels and property are private and should stay that way The same ethics apply
to the digital world, and therefore part of our job as developers is to create
applications and solutions that protect digital assets
You'll notice that this book covers some of the fundamental issues that should becovered in school when designing and building secure systems is the subject.You might be thinking that designing is the realm of the architect or programmanager, and it is, but as developers and testers you need to also understand theprocesses involved in outlining systems designed to withstand attack
We know software will always have vulnerabilities, regardless of how muchtime and effort you spend trying to develop secure software, simply because youcannot predict future security research We know this is true of Microsoft
Windows NET Server 2003, but we also know you can reduce the overall
number of vulnerabilities and make it substantially harder to find and exploitvulnerabilities in your code by following the advice in this book
Trang 7If you design applications, or if you build, test, or document solutions, you needthis book If your applications are Web-based or Win32-based, you need thisbook Finally, if you are currently learning or building Microsoft NET
Framework–based applications, you need this book In short, if you are involved
in building applications, you will find much to learn in this book
Even if you're writing code that doesn't run on a Microsoft platform, much of thematerial in this book is still useful Except for a few chapters that are entirelyMicrosoft-specific, the same types of problems tend to occur regardless of
platform Even when something might seem to be applicable only to Windows, itoften has broader application For example, an Everyone Full Control accesscontrol list and a file set to World Writable on a UNIX system are really thesame problem, and cross-site scripting issues are universal
Trang 8The book is divided into five parts Chapters 1 through 4 make up Part I,
“Contemporary Security,” and outline the reasons why systems should be
secured from attack and guidelines and analysis techniques for designing suchsystems
The meat of the book is in Parts II and III Part II, “Secure Coding Techniques,”encompassing Chapters 5 through 14, outlines critical coding techniques thatapply to almost any application Part III, “Even More Secure Coding
Techniques,” includes four chapters (Chapters 15 through 18) that focus onnetworked applications and NET code
Part IV, “Special Topics,” includes six chapters (Chapters 19 through 24) thatcover less-often-discussed subjects, such as testing, performing security codereviews, privacy, and secure software installation Chapter 23 includes generalguidelines that don't fit in any single chapter
Part V, “Appendixes,” includes five appendixes covering dangerous APIs,
ridiculous excuses we've heard for not considering security, and security
checklists for designers, developers and testers
Unlike the authors of a good many other security books, we won't just tell youhow insecure applications are and moan about people not wanting to build
secure systems This book is utterly pragmatic and, again, relentlessly practical
It explains how systems can be attacked, mistakes that are often made, and, mostimportant, how to build secure systems (By the way, look for margin icons,which indicate security-related anecdotes.)
Trang 9You can download the sample files from the book's Companion Content page onthe Web by connecting to http://www.microsoft.com/mspress/books/5957.asp
To access the sample files, click Companion Content in the More Informationmenu box on the right side of the page This will load the Companion ContentWeb page, which includes a link for downloading the sample files and
connecting to Microsoft Press Support The download link opens an executablefile containing a license agreement To copy the sample files onto your hard disk,click the link to run the executable and then accept the license agreement that ispresented By default, the sample files will be copied to the My
Documents\Microsoft Press\Secureco2 folder During the installation process,you'll be given the option of changing that destination folder
Trang 10Most samples in this book are written in C or C++ and require Microsoft VisualStudio NET, although most of the samples written in C/C++ work fine withmost compilers, including Microsoft Visual C++ 6.0 The Perl examples havebeen tested using ActiveState Perl 5.6 or ActivateState Visual Perl 1.0 from
http://www.activestate.com Microsoft Visual Basic Scripting Edition and JScriptcode was tested with Windows Scripting Host included with Windows 2000 andlater All SQL examples were tested using Microsoft SQL Server 2000 Finally,Visual Basic NET and Visual C# applications were written and tested usingVisual Studio NET
All the applications but two in this book will run on computers running
Windows 2000 that meet recommended operating system requirements TheSafer sample in Chapter 7 and the UTF8 MultiByteToWideChar sample in
Chapter 11 require Windows XP or Windows NET Server to run correctly
Compiling the code requires somewhat beefier machines that comply with therequirements of the compiler being used
Trang 11panion content Microsoft Press provides corrections for books through theWorld Wide Web at http://www.microsoft.com/mspress/support/ To connectdirectly to the Microsoft Press Knowledge Base and enter a query regarding aquestion or issue that you have, go to
Every effort has been made to ensure the accuracy of this book and the com-http://www.microsoft.com/mspress/support/search.asp
Trang 12When you look at the cover of this book, you see the names of only two authors,but this book would be nothing if we didn't get help and input from numerouspeople We pestered some people until they were sick of us, but still they wereonly too happy to help
First, we'd like to thank the Microsoft Press folks, including Danielle Bird foragreeing to take on this second edition, Devon Musgrave for turning our “prose”into English and giving us grammar lessons, and Brian Johnson for making sure
we were not lying Much thanks also to Kerri DeVault for laying out the pagesand Rob Nance for the part opener and other art
Many people answered questions to help make this book as accurate as possible,including the following from Microsoft: Saji Abraham, Ümit Akku, Doug Bayer,Tina Bird, Mike Blaszczak, Grant Bolitho, Christopher Brumme, Neill Clift,David Cross, Scott Culp, Mike Danseglio, Bhavesh Doshi, Ramsey Dow, WernerDreyer, Kedar Dubhashi, Patrick Dussud, Vadim Eydelman, Scott Field, CyrusGray, Brian Grunkemeyer, Caglar Gunyakti, Ron Jacobs, Jesper Johansson,Willis Johnson, Loren Kohnfelder, Sergey Kuzin, Mike Lai, Bruce Leban, Yung-Shin “Bala” Lin, Steve Lipner, Eric Lippert, Matt Lyons, Erik Olson, Dave
Quick, Art Shelest, Daniel Sie, Frank Swiderski, Matt Thomlinson, Chris
Walker, Landy Wang, Jonathan Wilkins, and Mark Zbikowski
We also want to thank the entire Windows division for comments, nitpicks, andimprovements—there are too many of you to list you individually!
Some people deserve special recognition because they provided copious materialfor this book, much of which was created during their respective products'
security pushes Brandon Bray and Raymond Fowkes supplied much bufferoverrun help and material Dave Ross, Tom Gallagher, and Richie Lai are three
of the foremost experts on Web-based security issues, especially the cross-sitescripting material John McConnell, Mohammed El-Gammal, and Julie Bennettcreated the core of the internationalization chapter and were a delight to workwith The secure NET code chapter would be a skeleton if it were not for thehelp offered by Erik Olson and Ivan Medvedev; Ivan's idea of “CAS in pictures”
Trang 13McKay wrote vast amounts of material that led to the documentation chapter.The chapter on conducting security code reviews benefited from insightful
feedback and references provided by Ramsey Dow and a PowerPoint
presentation by Neill Clift Vadim Eydelman provided a detailed analysis of the
potential problems with using SO_EXCLUSIVEADDR and solutions that went
into both this book and a Microsoft Knowledge Base article Your eagerness toprovide such rich and vast material is as humbling as it is encouraging
The following people provided input for the first edition, and we're still thankfulfor their help: Eli Allen, John Biccum, Thomas Deml, Monica Ene-Pietrosanu,Sean Finnegan, Tim Fleehart, Damian Haase, David Hubbard, Louis Lafreniere,Brian LaMacchia, John Lambert, Lawrence Landauer, Paul Leach, Terry Leeper,Rui Maximo, Daryl Pecelj, Jon Pincus, Rain Forest Puppy, Fritz Sands, EricSchultze, Alex Stockton, Hank Voight, Richard Ward, Richard Waymire, andMark Zhou
Many outside Microsoft gave their time to help us with this book We'd like togive our greatest thanks to Peter Gutmann (it's an urban myth, Peter!), SteveHayr of Accenture, Christopher W Klaus of Internet Security Systems, JohnPescatore of Gartner Inc., Herbert H Thompson and James A Whittaker ofFlorida Tech, and finally, Chris “Weld Pond” Wysopal of @Stake
Most importantly, we want to thank everyone at Microsoft for taking up theTrusthworthy Computing rallying cry with such passion and urgency We thankyou all
Trang 14Contemporary Security
Trang 15interconnected In the “good old days,” computers were usually islands of
functionality, with little, if any, interconnectivity In those days, it didn't matter ifyour application was insecure—the worst you could do was attack yourself—and
so long as an application performed its task successfully, most people didn't careabout security This paradigm is evident in many of the classic best practices
books published in the early 1990s For example, the excellent Code Complete
(Microsoft Press, 1993), by Steve McConnell, makes little or no reference tosecurity in its 850 pages Don't get me wrong: this is an exceptional book andone that should be on every developer's bookshelf Just don't refer to it for
Trang 16computer systems susceptible to attack because the application developerssimply didn't plan for the applications to be networked and accessible by
malicious assailants Ever wonder why the World Wide Web is often referred to
as the Wild Wild Web? In this chapter, you'll find out The Internet is a hostileenvironment, so you must design all code to withstand attack
I'm Not Crying Wolf
On Friday the 13th, July 2001, http://www.sans.org, the Web site
operated by the SANS (System Administration, Networking, and
mail to all subscribers of their SANS NewsBytes with the following
Trang 17to media criticism, more attractive to users, and less expensive to fix and
support Because you cannot have quality without security, you must use tact or,
in rare cases, subversion to get everyone on your team to be thinking aboutsecurity I'll discuss all these issues in this chapter, and I'll also give you somemethods for helping to ensure that security is among the top priorities in yourorganization
If you care about quality code, read on
Trang 18On a number of occasions I've set up a computer on the Internet just to see whathappens to it Usually, in a matter of days, the computer is discovered, probed,
at the time to battle-test Microsoft Windows 2000 before it shipped to users Wesilently slipped the Web server onto the Internet on a Friday, and by Monday itwas under massive attack Yet we'd not told anyone it was there
The point is made: attacks happen To make matters worse, attackers currentlyhave the upper hand in this ongoing battle I'll explain some of the reasons forthis in “The Attacker's Advantage and the Defender's Dilemma” later in thischapter
Some attackers are highly skilled and very clever They have deep computerknowledge and ample time on their hands They have the time and energy toprobe and analyze computer applications for security vulnerabilities I have to behonest and say that I have great respect for some of these attackers, especially
the white-hats, or good guys, many of whom I know personally The best white-hats work closely with software vendors, including Microsoft, to discover andremedy serious security issues prior to the vendor issuing a security bulletinprompting users to take mitigating action, such as applying a software fix orchanging a setting This approach helps prevent the Internet community frombeing left defenseless if the security fault is first discovered by vandals whomount widespread attacks
How Was the Windows 2000 Test Site Discovered?
Trang 19write exploit code for the security bugs they find An exploit (often called a
sploit) is a way of breaking into a system.
This is where things can get sticky Imagine that you ship an application, anattacker discovers a security vulnerability, and the attacker goes public with anexploit before you have a chance to rectify the problem Now the script kiddiesare having a fun time attacking all the Internet-based computers running yourapplication I've been in this position a number of times It's a horrible state ofaffairs, not enjoyable in the least People run around to get the fix made, andchaos is the order of the day You are better off not getting into this situation inthe first place, and that means designing secure applications that are intended towithstand attack
The argument I've just made is selfish I've looked at reasons to build secure
Trang 20in turn can lead to the loss of sales as customers switch to a competing productperceived to have better security support Now let's look at the viewpoint thatreally matters: the end user's viewpoint!
Your end users demand applications that work as advertised and the way theyexpect them to each time they launch them Hacked applications do neither Yourapplications manipulate, store, and, hopefully, protect confidential user data andcorporate data Your users don't want their credit card information posted on theInternet, they don't want their medical data hacked, and they don't want theirsystems infected by viruses The first two examples lead to privacy problems forthe user, and the latter leads to downtime and loss of data It is your job to createapplications that help your users get the most from their computer systems
without fear of data loss or invasion of privacy If you don't believe me, ask yourusers
Trang 21Trustworthy computing is not a marketing gimmick It is a serious push towardgreater security within Microsoft and hopefully within the rest of the industry.Consider the telephone: in the early part of the last century, it was a miracle thatphones worked at all We didn't particularly mind if they worked only some ofthe time or that we couldn't call places a great distance away People even put upwith inconveniences like shared lines It was just a cool thing that you couldactually speak with someone who wasn't in the same room with you As phonesystems improved, people began to use them more often in their daily lives And
as use increased, people began to take their telephones for granted and depend
on them for emergencies (One can draw a similar analogy with respect to
electricity.) This is the standard that we should hold our computing infrastructure
to Our computers need to be running all the time, doing the tasks we boughtthem to do; not crashing because someone sent an evil packet, and not doing thebidding of someone who isn't authorized to use the system
We clearly have a lot of work to do to get our computers to be considered
trustworthy There are difficult problems that need to be solved, such as how tomake our systems self-healing Securing large networks is a very interesting andnon-trivial problem It's our hope that this book will help us all build systems wecan truly consider trustworthy
Trang 22“Security is a top priority” needs to be a corporate dictum because, as we'veseen, the need to ship secure software is greater than ever Your users demandthat you build secure applications—they see such systems as a right, not a
privilege Also, your competitor's sales force will whisper to your potentialcustomers that your code is risky and unsafe So where do you begin instillingsecurity in your organization? The best place is at the top, which can be hardwork It's difficult because you'll need to show a bottom-line impact to yourcompany, and security is generally considered something that “gets in the way”and costs money while offering little or no financial return Selling the idea ofbuilding secure products to management requires tact and sometimes requiressubversion Let's look at each approach
Using Tact to Sell Security to the Organization
The following sections describe arguments you can and should use to show thatsecure applications are good for your business Also, all these arguments relate
to the bottom line Ignoring them is likely to have a negative impact on yourbusiness's success
Secure Products Are Quality Products
This is a simple issue to sell to your superiors All you need to do is ask them ifthey care about creating quality products There's only one answer: yes! If theanswer is no, find a job elsewhere, somewhere where quality is valued
OK, I know it's not as simple as that, because we're not talking about perfectsoftware Perfect software is an oxymoron, just like perfect security (As is oftensaid in the security community, the most secure system is the one that's turnedoff and buried in a concrete bunker, but even that is not perfect security.) We'retalking about software secure enough and good enough for the environment inwhich it will operate For example, you should make a multiplayer game securefrom attack, but you should spend even more time beefing up the security of anapplication designed to manipulate sensitive military intelligence or medicalrecords
Trang 23Despite the fact that the need for security and the strength of security is context-security For example, a solution that protects secret data need not necessarily bereliable If the system crashes but does so in a manner that does not reveal thedata, it can still be deemed secure As Figure 1-1 shows, if you care about
quality or reliability, you care about security
Figure 1-1 Secure software is a subset of quality software and reliable software.
Why Would You Protect a Multiplayer Game from Attack?
It might not seem obvious, but multiplayer games are also susceptible toattack Imagine you have written and published a multiplayer strategy
The Media (and Your Competition) Leap on Security Issues
Like it or not, the press loves to make headlines out of security problems Andsometimes members of the press don't know what they're talking about and
mischaracterize or exaggerate issues Why let the facts get in the way of a goodstory? Because people often believe what they read and hear, if your product is
in the headlines because of a security issue, serious or not, you can bet that yoursales and marketing people will hear about the problem and will have to
determine a way to explain the issue The old adage that “any news is good
news” simply does not hold true for security incidents Such publicity can leadpeople to start looking for solutions from your competitors because they offerseemingly more secure products than you do
Trang 24Once news gets around that your product doesn't work appropriately because it'sinsecure, some people will begin to shy away from your product or company.Worse yet, people who have a grudge against your product might fan the fire byamassing bad security publicity to prove to others that using your product isdangerous They will never keep track of the good news, only the bad news It's
an unfortunate human trait, but people tend to keep track of information thatcomplies with their biases and agendas Again, if you do not take security
seriously, the time will come when people will start looking to your competitionfor products
Don't Be a Victim
There is a misguided belief in the market that people who can break into systemsare also the people who can secure them Hence, there are a lot of would-beconsultants who believe that they need some trophies mounted on their wall forpeople to take them seriously You don't want your product to be a head on
someone's wall!
Security Vulnerabilities Are Expensive to Fix
Like all engineering changes, security fixes are expensive to make late in thedevelopment process It's hard to determine a dollar cost for a fix because thereare many intangibles, but the price of making one includes the following:
The cost of the fix coordination Someone has to create a plan to get thefix completed
Trang 25The cost of writing the supporting documentation
The cost of handling bad public relations
Bandwidth and download costs if you pay an ISP to host fixes for you.The cost of lost productivity Chances are good that everyone involved
in this process should be working on new code instead Working on thefix is time lost
The cost to your customers to apply the fix They might need to run thefix on a nonproduction server to verify that it works as planned Onceagain, the people testing and applying the fix would normally be
working on something productive!
Finally, the potential cost of lost revenue, from likely clients deciding toeither postpone or stop using your product
As you can see, the potential cost of making one security fix could easily be inthe tens, if not hundreds, of thousands of dollars If only you had had security inmind when you designed and built the product in the first place!
http://www.cybercrime.gov This superb site summarizes a number of prosecutedcomputer crime cases, outlining some of the costs necessitated and damagesinflicted by the criminal or criminals Take a look, and then show it to the CEO
Trang 26Luckily, I have had to use this method of instilling a security mind-set in only afew instances It's not the sort of thing you should do often The basic premise isyou attack the application or network to make a point For example, many yearsago I found a flaw in a new product that allowed an attacker (and me!) to shutdown the service remotely The product team refused to fix it because they wereclose to shipping the product and did not want to run the risk of not shipping theproduct on time My arguments for fixing the bug included the following:
The bug is serious: an attacker can remotely shut down the application.The attack can be made anonymously
The attack can be scripted, so script kiddies are likely to download thescript and attack the application en masse
occurred Regression bugs can be common when security bugs are fixed In fact,based on experience, I'd say regressions are the number one reason why testinghas to be so intensive when a security fix is made The last thing you need is tomake a security fix, only to find that it breaks some other feature
Even with all this evidence, the product group ignored my plea to fix the
product I was concerned because this truly was a serious problem; I had alreadywritten a simple Perl script that could shut down the application remotely So Ipulled an evil trick: I shut down the application running on the team's server theyused each day for testing purposes Each time the application came back up, Ishut it down again This was easy to do When the application started, it opened
a specific Transmission Control Protocol (TCP) port, so I changed my Perl script
to look for that port and as soon as the port was live on the target computer, myscript would send the packet to the application and shut it down The team fixed
Trang 27if she doesn't mind, I'd like to perform a live demonstration The threat of
performing this action is often enough to get bugs fixed
IMPORTANT
Never use subversive techniques except when you know you're dealingwith a serious security bug Don't cry wolf, and pick your battles
Now let's change focus Rather than looking at how to get the top brass into thegame, let's look at some ideas and concepts for instilling a security culture in therest of your organization
Trang 28Now that you have the CEO's attention, it's time to cultivate a security culture inthe groups that do the real work: the product development teams Generally, I'vefound that convincing designers, developers, and testers that security is
important is reasonably easy because most people care about the quality of theirproduct It's horrible reading a review of your product that discusses the securityweakness in the code you just wrote Even worse is reading about a serioussecurity vulnerability in the code you wrote! The following sections describesome methods for creating an atmosphere in your organization in which peoplecare about, and excel at, designing and building secure applications
Get the Boss to Send an E-Mail
Assuming you've succeeded in getting the attention of the boss, have him send
an e- mail or memo to the appropriate team members explaining why security is
a prime focus of the company One of the best e-mails I saw came from JimAllchin, Group Vice President of Windows at Microsoft The following is anexcerpt of the e-mail he sent to the Windows engineering team:
I want customers to expect Windows XP to be the most secure operatingsystem available I want people to use our platform and not have to worryabout malicious attacks taking over the Administrator account or hackersgetting to their private data I want to build a reputation that Microsoft
ships
Trang 29message comes from the top Of course, it doesn't mean no security bugs willend up in the product In fact, some security bugs have been found since
Windows XP shipped, and no doubt more will be found But the intention is tokeep raising the bar as new versions of the product are released so that fewer andfewer exploits are found
The biggest call to action for Microsoft came in January 2002 when Bill Gatessent his Trustworthy Computing memo to all Microsoft employees and outlinedthe need to deliver more secure and robust applications to users because thethreats to computer systems have dramatically increased The Internet of threeyears ago is no longer the Internet of today Today, the Net is much more hostile,and applications must be designed accordingly You can read about the memo at
news.com.com/2009-1001-817210.html
Nominate a Security Evangelist
Having one or more people to evangelize the security cause—people who
understand that computer security is important for your company and for yourclients—works well These people will be the focal point for all security-relatedissues The main goals of the security evangelist or evangelists are to
Stay abreast of security issues in the industry
Interview people to build a competent security team
Provide security education to the rest of the development organization
Trang 30—whatever it takes!
Provide security bug triaging to determine the severity of security bugs,and offer advice on how they should be fixed
Let's look at some of these goals
Stay Abreast of Security Issues
Two of the best sources of up-to-date information are NTBugTraq and BugTraq.NTBugTraq discusses Windows NT security specifically, and BugTraq is moregeneral NTBugTraq is maintained by Russ Cooper, and you can sign up at
http://www.ntbugtraq.com BugTraq, the most well-known of the security
vulnerability and disclosure mailing lists, is maintained by SecurityFocus, which
is now owned by Symantec Corporation You can sign up to receive e-mails at
http://www.securityfocus.com On average, you'll see about 20 postings a day Itshould be part of the everyday routine for a security guru to see what's going on
in the security world by reading postings from both NTBugTraq and BugTraq
If you're really serious, you should also consider some of the other
SecurityFocus offerings, such as Vuln-Dev, Pen-Test, and SecProg Once again,you can sign up for these mailing lists at http://www.securityfocus.com
Interviewing Security People
In many larger organizations, you'll find that your security experts will be
quickly overrun with work Therefore, it's imperative that security work scalesout so that people are accountable for the security of the feature they're creating
To do this, you must hire people who not only are good at what they do but alsotake pride in building a secure, quality product
When I interview people for security positions within Microsoft, I look for anumber of qualities, including these:
A love for the subject The phrase I often use is “having the fire in yourbelly.”
A deep and broad range of security knowledge For example,
Trang 31vulnerabilities, prevention, accountability, real-world security
requirements that affect users, and much more
An intense desire to build secure software that fulfills real personal andbusiness requirements
The ability to apply security theory in novel yet appropriate ways to
mitigate security threats
The ability to define realistic solutions, not just problems Anyone cancome up with a list of problems—that's the easy part!
The ability to think like an attacker
Often, the ability to act like an attacker Yes, to prevent the attacks, youreally need to be able to do the same things that an attacker does
servers There is a fine line between secure systems and usable secure
systems that are useful for the intended audience The best security
people understand where that line is
The primary trait of a security person is a love for security Good security peoplelove to see IT systems and networks meeting the needs of the business without
Trang 32Another important trait is experience, especially the experience of someone whohas had to make security fixes in the wild That person will understand the painand anguish involved when things go awry and will implant that concern in therest of the company In 2000, the U.S stock market took a huge dip and peoplelost plenty of money In my opinion, many people lost a great deal of moneybecause their financial advisors had never been through a bear market As far asthey were concerned, the world was good and everyone should keep investing inhugely overvalued com stocks Luckily, my financial advisor had been throughbad times and good times, and he made some wise decisions on my behalf.Because of his experience with bad times, I wasn't hit as hard as some others
If you find someone with these traits, hire the person
Provide Ongoing Security Education
When my wife and I were expecting our first child, we went to a newborn CPRclass At the end of the session, the instructor, an ambulance medic, asked if wehad any questions I put up my hand and commented that when we wake uptomorrow we will have forgotten most of what was talked about, so how does herecommend we keep our newfound skills up-to-date? The answer was simple:reread the course's accompanying book every week and practice what you learn.The same is true for security education: you need to make sure that your not-so-security-savvy colleagues stay attuned to their security education For example,the Secure Windows Initiative team at Microsoft employs a number of methods
to accomplish this, including the following:
Create an intranet site that provides a focal point for security material.This should be the site people go to if they have any security questions.Provide white papers outlining security best practices As you discovervulnerabilities in the way your company develops software, you shouldcreate documentation about how these issues can be stamped out
Perform daylong security bug-bashes Start the day with some securityeducation, and then have the team review their own product code,
Trang 33homework—it strengthens the knowledge they learned during the
morning Finding bugs is icing on the cake
Each week send an e-mail to the team outlining a security bug and
asking people to find the problem Provide a link in the e-mail to yourWeb site with the solution, details about how the bug could have beenprevented, and tools or material that could have been used to find theissue ahead of time I've found this approach really useful because itkeeps people aware of security issues each week
of bugs from the code!
Provide Bug Triaging
There are times when you will have to decide whether a bug will be fixed
Sometimes you'll come across a bug that will rarely manifest itself, that has lowimpact, and that is very difficult to fix You might opt not to remedy this bug butrather document the limitation However, you'll also come across serious
security bugs that should be fixed It's up to you to determine the best way toremedy the bug and the priority of the bug fix
Trang 34I've outlined the requirement to build more secure applications, and I've
suggested some simple ways to help build a security culture However, we
should not overlook the fact that as software developers we are always on theback foot Simply put, we, as the defenders, must build better quality systemsbecause the attacker almost certainly has the advantage
Once software is installed on a computer, especially an Internet-facing system, it
is in a state of defense I mean that the code is open to potential attack 24 hours aday and 7 days a week from any corner of the globe, and it must therefore resistassault such that resources protected by the system are not compromised,
corrupted, deleted, or viewed in a malicious manner This situation is incrediblyproblematic for all users of computer systems It's also challenging for softwaremanufacturers because they produce software that is potentially a point of attack
Let's look at some of the reasons why the attackers can have fun at the defender'sexpense You'll notice as you review these principles that many are related
Principle #1: The defender must defend all points; the
attacker can choose the weakest point.
Imagine you are the lord of a castle You have many defenses at your disposal:archers on the battlements, a deep moat full of stagnant water, a drawbridge, and5-foot-thick walls of stone As the defender, you must have guards constantlypatrolling the castle walls, you must keep the drawbridge up most of the timeand guard the gate when the drawbridge is down, and you must make sure thearchers are well-armed You must be prepared to fight fires started by flamingarrows, and you must also make sure the castle is well-stocked with supplies incase of a siege The attacker, on the other hand, need only spy on the castle tolook for one weak point, one point that is not well-defended
The same applies to software: the attacker can take your software and look forjust one weak point, while we, the defenders, need to make sure that all entrypoints into the code are protected Of course, if a feature is not there—that is, notinstalled—then it cannot be attacked
Trang 35Principle #2: The defender can defend only against known attacks; the attacker can probe for unknown vulnerabilities.
Now imagine that the castle you defend includes a well that is fed by an
underground river Have you considered that an attacker could attack the castle
by accessing the underground river and climbing up the well? Remember theoriginal Trojan horse? The residents of Troy did not consider a gift from theGreeks as a point of attack, and many Trojan lives were lost
Software can be shipped with defenses only for pretheorized or preunderstoodpoints of attack For example, the developers of IIS 5 knew how to correctlydefend against attacks involving escaped characters in a URL, but they did notprepare a defense to handle an attack taking advantage of a malformed UTF-8sequence because they did not know the vulnerability existed The attacker,however, spent much time looking for incorrect character handling and foundthat IIS 5 did not handle certain kinds of malformed UTF-8 escaping correctly,which led to a security vulnerability More information is at
http://www.wiretrip.net/rfp/p/doc.asp/i2/d57.htm
The only way to defend against unknown attacks is to disenable features unlessexpressly required by the user In the case of the Greeks, the Trojan horse wouldhave been a nonevent if there was no way to get the “gift” into the city walls
Principle #3: The defender must be constantly vigilant; the attacker can strike at will.
The defender's guard must always be up The attacker's life, on the other hand, ismuch easier She can remain unnoticed and attack whenever she likes In someinstances, the attacker might wait for just the right moment before attacking,while the defender must consider every moment as one in which an attack mightoccur This can be a problem for sysadmins, who must always monitor theirsystems, review log files, and look for and defend against attack Hence,
software developers must provide software that can constantly defend againstattack and monitoring tools to aid the user in determining whether the system isunder attack
Principle #4: The defender must play by the rules; the
Trang 36This is not always true in the world of software, but it's more true than false Thedefender has various well-understood white-hat tools (for example, firewalls,intrusion-detection systems, audit logs, and honeypots) to protect her system and
to determine whether the system is under attack The attacker can use any
intrusive tool he can find to determine the weaknesses in the system Once again,this swings the advantage in favor of the attacker
Trang 37As you can see, the world of the defender is not a pleasant one As defenders,software developers must build applications and solutions that are constantlyvigilant, but the attackers always have the upper hand and insecure software willquickly be defeated In short, we must work smarter to defeat the attackers Thatsaid, I doubt we'll ever “defeat” Internet vandals, simply because there are somany attackers, so many servers to attack, and the fact that many attackers assailInternet-based computers simply because they can! Or, as George Mallory
(1886-1924) answered the question, “Why do you want to climb Mt Everest?”:
“Because it is there.” Nevertheless, we can raise the bar substantially, to a pointwhere the attackers will find software more difficult to attack and use their skillsfor other purposes
Finally, be aware that security is different from other aspects of computing.Other than your own developers, few, if any, people are actively looking forscalability or internationalization issues in software However, plenty of peopleare willing to spend time, money, and sweat looking for security vulnerabilities.The Internet is an incredibly complex and hostile environment, and your
applications must survive there
Trang 38The Proactive Security Development
Process
Many books that cover building secure applications outline only one part of thesolution: the code This book aims to be different by covering design, coding,testing, and documentation All of these aspects are important for deliveringsecure systems, and it's imperative that you adopt a disciplined process thatincorporates these aspects Simply adding some “good ideas” or a handful of
“best practices” and checklists to a poor development process will result in onlymarginally more secure products In this chapter, I'll describe in a general waysome methods for improving the security focus of the development process I'llthen spend a good amount of time on educational issues because education isboth crucial to creating secure products and a pet subject of mine Then I'll move
on to more specific discussion of the techniques you should use to instill securityawareness and discipline at each step in the development process
However, let's first look at some of the reasons why people choose not to buildsecure systems and why many perfectly intelligent people make security
Trang 39The second reason is an oft-noted view, and it is somewhat misguided Securitydisables functionality that should not be available to the user For example, if forusability reasons you build an application allowing anyone to read personalcredit card information without first being authenticated and authorized, anyonecan read the data, including people with less-than-noble intentions! Also,
consider this statement from your own point of view Is security a “disabler”when your data is illegally accessed by attackers? Is security “something thatgets in the way” when someone masquerades as you? Remember that if youmake it easy for users to access sensitive data, you make it easy for attackers,too
The third reason is true, but it's not a reason for creating insecure products
Unlike performance, which has tangible analysis mechanisms—you know whenthe application is slow or fast—you cannot say a program has no security flawsand you cannot easily say that one application is more secure than another unlessyou can enumerate all the security flaws in both You can certainly get into
heated debates about the security of A vs B, but it's extremely difficult to saythat A is 15 percent more secure than B
That said, you can show evidence of security-related process improvements—forexample, the number of people trained on security-related topics, the number ofsecurity defects removed from the system, and so on A product designed andwritten by a security-aware organization is likely to exhibit fewer security
defects than one developed by a more undisciplined organization Also, you canpotentially measure the effective attack surface of a product I'll discuss this inChapter 3, “Security Principles to Live By,” and in Chapter 19, “Security
Testing.”
Note also that the more features included in the product, the more potential
security holes in it Attackers use features too, and a richer feature set gives themmore to work with This ties in with the last reason cited in the previous bulletedlist New functions are inherently more risky than proven, widely used, moremature functionality, but the creativity (and productivity) of many developers issparked by new challenges and new functions or new ways to do old functions.Bill Gates, in his Trustworthy Computing memo, was pointed about this when hesaid, “When we face a choice between adding features and resolving security
Trang 40Ok, let's look at how we can resolve these issues