Security for Microsoft Visual Basic .NETby Ed Robinson and Michael James Bond ISBN:0735619190 Microsoft Press © 2003 396 pages With this text, readers master common security principles
Trang 1Security for Microsoft Visual Basic NET
by Ed Robinson and Michael James Bond
ISBN:0735619190
Microsoft Press © 2003 (396 pages)
With this text, readers master common security principles and techniques, such as how to do private key encryption, implement
a login screen, configure Microsoft NET policy tools, and perform a security audit.
Chapter 8 - Handling Exceptions
Trang 2Chapter 12 - Securing Databases
Part IV - Enterprise-Level Security
Chapter 13 - Ten Steps to Designing a Secure
Enterprise System Chapter 14 - Threats—Analyze, Prevent,
Detect, and Respond Chapter 15 - Threat Analysis Exercise
Chapter 16 - Future Trends
Appendix A - Guide to the Code Samples
Appendix B - Contents of SecurityLibrary.vb Index
List of Figures
List of Tables
List of Sidebars
Trang 3Learn essential security techniques for designing,
developing, and deploying applications for Microsoft Windows and the Web Visual Basic NET experts Ed Robinson and Michael Bond introduce critical security concepts using straightforward language and step-by- step examples You get clear, end-to-end guidance— covering application design, coding techniques, testing methods, and deployment strategies, along with
direction on how to help secure the operating system and related infrastructure and services.
Discover how to:
Use techniques that help secure your application architecture
Understand the most common vulnerabilities and how to write code to help prevent them
Implement authentication and authorization
techniques in your applications
Write routines for encryption, input validation, and exception handling
Add Passport, Forms, and Windows authentication
to Microsoft ASP.NET applications
Perform a security threat analysis and implement countermeasures
Think like a hacker—and help uncover security holes
Trang 4Create a deployment package with security policy updates for your application
Implement security-enhancing features for the Windows operating system, Microsoft IIS,
Microsoft SQL Server, and Microsoft Access
databases
About the Authors
Ed Robinson, a lead program manager for Microsoft, helped drive the development of security features for Visual Basic NET and other Microsoft products He has
13 years’ experience in the software industry and
speaks at developer conferences worldwide.
Michael James Bond is a development lead on the
Visual Basic NET team He has supported, developed, and helped secure many features of Visual Basic over the past 13 years You can find Mike in the Visual Basic chat rooms on MSDN, the Microsoft Developer
Network, as well as at industry events.
Ed and Mike are two of the coauthors of award-winning
Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic NET (Microsoft Press).
Trang 5Includes index
ISBN 0-7356-1919-0
1 Computer security 2 Microsoft Visual Basic 3 Basic (Computerprogram
Trang 6www.microsoft.com/mspress. Send comments to
mspinput@microsoft.com.
Microsoft, Microsoft Press, the NET logo, Visual Basic, Visual Studio,and Windows are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries Other product
and company names mentioned herein may be the trademarks of theirrespective owners
The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are
fictitious No association with any real company, organization, product,domain name, e-mail address, logo, person, place, or event is intended
—M.J.B.
About the Authors
Ed Robinson
Ed Robinson, a lead program manager for Microsoft, helped drive thedevelopment of security features for Visual Basic NET and other
Microsoft products He has 13 years of experience in the software
industry and speaks at developer conferences worldwide
Trang 7Michael Bond is a development lead on the Visual Basic NET team Hehas supported, developed, and helped secure many features of VisualBasic over the past 13 years You can find Mike in the Visual Basic chatrooms on MSDN, Microsoft Developer Network, as well as at industryevents
Trang 8This book is an introduction to security for Visual Basic programmers.You’ll find it useful both as a prescriptive guide for writing secure
applications and as a technical reference for how to actually implementsecurity techniques in your own code For example, in Chapter 1,
“Encryption,” we explain what encryption is and when to use the differenttypes of encryption, and we provide examples that show you how to
actually encrypt and decrypt information
Although there is already a wealth of information available about security,very little has been written that targets the Visual Basic programmer Inwriting this book, we set out to change this We have followed three
principles that make this book better for the Visual Basic programmerthan any other publication you will find on security:
Make it simple Many security publications are shrouded in hard-to-understand jargon and difficult-to-work-out acronyms, and theyassume you already have a background in security This book isdifferent: we spell out every acronym, use easy-to-understandlanguage, and explain in clear terms each security concept
Clear guidance Some security books explain security techniques
without telling you where or where not to use them This book isdifferent: we offer clear guidance on how, when, and where youshould use each security technique
Complete assistance Although this is an introductory-level book,
it covers everything from coding techniques to designing a securearchitecture to performing a security audit Our intention was toprovide an end-to-end introductory guide for producing secureapplications
Trang 9The authors of this book, like you, are Visual Basic programmers Weuse straight, no-nonsense talk, offer clear and simple solutions, and
provide step- by-step examples—written entirely in Visual Basic, of
course To make it easier to find what you’re looking for, this book is
divided into four sections, each section dealing with a different aspect ofsecurity:
Section 1 jumps straight into programming techniques such asencryption, role-based security, code access security, MicrosoftASP.NET authentication, and securing Web applications
Section 2 is about identifying threats to your Visual Basic NETapplication and neutralizing them by safe-guarding input, properlyhandling exceptions, and testing your application for securityvulnerabilities
Section 3 discusses how to lock down the environments that yourapplication runs in or depends upon such as the Microsoft
Windows operating system, Internet Information Services, NETruntime, Microsoft SQL Server, and Microsoft Access databases
In addition, this section discusses how to lock down your
application for deployment
Section 4 focuses on architecture, how to design secure systems,perform a security audit of your application, come up with a
contingency plan, and execute the contingency plan if an intruderdoes make his or her way past the security measures you haveput into place
Microsoft Visual Basic NET is built on a number of technologies,
including the NET platform, Microsoft Visual Studio NET, and of coursethe Microsoft Visual Basic NET compiler For the sake of simplicity andbrevity, unless the distinction is important, we refer to all of these
technologies collectively as Microsoft Visual Basic NET As a MicrosoftVisual Basic NET developer, you don’t need to think about these
Trang 10composite technologies to get your job done.
Trang 11You’ll find many samples—both Windows Forms and ASP.NET Webapplications—throughout this book that demonstrate important securityconcepts The code samples are available on this book’s Web site at
http://www.microsoft.com/mspress/books/6432.asp To download the
sample files, simply click the Companion Content link in the More
Information menu on the right side of the Web page This will load theCompanion Content page, which includes links for downloading the
sample files To install the sample files, run the executable setup filedownloaded from the Companion Content page, and follow the
instructions in the setup program A link to the sample code will be
created on your Programs menu under Microsoft Press
There are two sets of sample code, one set for Visual Basic NET 2002and one set for Visual Basic NET 2003 The two sets are functionallyequivalent; the reason for providing two sets is that Visual Basic NET
2003 projects use a different file layout than Visual Basic NET 2002 Thesetup program installs the two sets of sample code to directories namedVB.NET 2002 and VB.NET 2003, with subdirectories organized by
chapter number, having names such as CH01_Encryption, underneaththese directories Within the text, we refer you to the appropriate sample
by directory name, such as CH01_Encryption, as needed If you like toperform the steps as presented in the step-by-step exercises, start withthe sample application located in the Start directory; or if you’d prefer toview the completed code, open the application located in the Finish
directory The system requirements for running the sample code files arethe same as the requirements for Visual Basic NET itself—ensure yourcomputer has Visual Basic NET 2002 or Visual Basic NET 2003
Nothing extra is required In addition, to run the Web samples, you’ll alsoneed Microsoft Internet Explorer 5.5 or later and Internet InformationServices (IIS) 5.0 or later Although some exercises in this book refer toMicrosoft Access or Microsoft SQL Server, these particular exercises arecompletely optional—the code in the sample files has been designed torun perfectly even if you haven’t installed these products
Create a Desktop Shortcut for Running Tools
Trang 12to the Visual Studio NET command prompt to your desktop The
prompt link to your desktop:
following steps show you how to add a Visual Studio NET command-1 Open the Start menu, and navigate to the Visual Studio NETCommand Prompt located under the Visual Studio NET Toolsmenu (located under the Microsoft Visual Studio NET menu)
2 While holding down the right mouse button, drag the VisualStudio NET Command Prompt to your desktop
3 Release the right mouse button, and choose Create ShortcutsHere from the shortcut menu
You should now have a convenient link to the Visual Studio NET
Command Prompt on your desktop
Trang 13For many programmers, security has been something to avoid—becausethey don’t understand security concepts, they shy away from
implementing security features for fear of making a mistake Above allelse, we hope this book will spark your interest in security This is a
fascinating and rapidly evolving area of computing, and the techniques
we discuss in this book are no longer simply for security specialists; theyare essential for every programmer
Trang 14Every effort has been made to ensure the accuracy of this book and thesample files If you run into a problem, Microsoft Press provides
corrections for its books through the World Wide Web at the followingWeb site: http://www.microsoft.com/mspress/support/
If you have problems, comments, or ideas regarding this book, pleasesend them to Microsoft Press You can contact Microsoft Press by
sending e-mail to: mspinput@microsoft.com Or you can send postal mailto
Trang 15The authors wish to thank the following people: Our first and most
influential reader, Mike “Shhh… don’t mention big brother systems” Pope;technical advisors, Erik “security god” Olson, David “Mr Policy” Guyer,Dave “Mr Deployment” Templin, Mike Neuburger, Michael Kogotkov,Ashvin Naik, John Hart and Adam Braden; our Microsoft Press supportteam, Denise “We can’t print that!” Bankaitis, Sally Stickney, DanielleVoeller, Roger LeBlanc, Chris “Brains” Wille; our boss, Rick “It’s a bookabout baseball? Sure I’ll approve it” Nasci; and our families, without
whom none of this would be possible, Jane Bond, Sarah and Katie Bond,and Catherine Robinson and Stella Robinson
Trang 16Part I: Development Techniques
Trang 18Chapter 1: Encryption
Trang 19Knowing where to use encryption in your own applications
If you read the Introduction, you’ll recall that this book is for Visual Basic.NET programmers new to security, not security experts new to VisualBasic NET This book unashamedly simplifies concepts and leaves outunnecessary techno-babble with the goal of making security easier tounderstand and implement—without sacrificing accuracy For many
programmers, this simplified look at security is all they will ever need,whereas others, after given a taste of security, will want to know more In
a nutshell, this book is not the last word in security; instead, it is the firstbook you should read on the subject
What is encryption? Before discussing how to implement encryption withVisual Basic NET, you need to have an understanding of encryption ingeneral Encryption is about keeping secrets safe by scrambling
messages to make them illegible In encryption terms, the original
message is known as plain text, the scrambled message is called cipher text, the process of turning plain text into cipher text is called encryption,
and the process of turning cipher text back into plain text is called
decryption.
Encryption isn’t just used in cyberspace or in mysterious governmentwork either You can find examples of it in everyday activities such as
Trang 20algorithm, for exactly the same reason that only aviation engineers
should build their own airplanes
It’s a common misconception that encryption algorithms and hash
functions must be secret to be secure The encryption algorithms andhash functions used in this book are commonly understood, and the
associated source code is distributed freely on the Internet They are,however, still secure because they are designed to be irreversible (in thecase of hash functions) or they require the user to supply a secret key (inthe case of encryption algorithms) As long as only the authorized partiesknow the secret key, the encrypted message is safe from intruders
Encryption helps to ensure three things:
Confidentiality Only the intended recipient will be able to decrypt
the message you send
Trang 21encryption for storing and retrieving information in a database We’ll alsobegin building a library of easy-to-use encryption functions that you canreuse in your Visual Basic programs
Trang 22If you haven’t already installed the practice files, which you can downloadfrom the book’s Web site at
http://www.microsoft.com/mspress/books/6432.asp, now would be a good
time to do so If you accept the default installation location, the sampleswill be installed to the folder C:\Microsoft Press\VBNETSec, although
you’ll be given an opportunity to change the destination folder during theinstallation process The practice files are organized by version of
Microsoft Visual Basic, chapter, and exercise The practice files for eachchapter give a starting point for the exercises in that chapter Many
chapters also have a finished version of the practice files so that you cansee the results of the exercise without actually performing the steps Tolocate the practice file for a particular exercise, look for the name of theexercise within the chapter folder For example, the Visual Basic NET
2003 versions of the practice files for the following section on using hashdigests for encrypting database fields will be in the folder
C:\Microsoft Press\VBNETSEC\VB.NET 2003\CH01_Encryption\EncryptDatabaseField\Start
In many of the exercises in this book, you’ll modify an employee
management system, adding security features to make the program moresecure The employee management system is a sample program that
changes to the database structure
Trang 23As we mentioned earlier in this chapter, a hash is a type of one-way
cryptography Some people refer to hashing as encryption; others feel it’snot strictly encryption because the hash cannot be unencrypted A hash
is a very large number, generated by scrambling and condensing theletters of a string In this chapter, you’ll use the SHA-1 algorithm SHA-1
is an acronym for Secure Hashing Algorithm The “-1” refers to revision 1,which was developed in 1994 SHA- 1 takes a string as input and returns
a 160-bit (20-byte) number Because a string is being condensed into a
fixed-size number, the result is called a hash digest, where digest
indicates a shortened size, similar to Reader’s Digest condensed books.
Hash digests are considered to be one-way cryptography because it’simpossible to derive the original string from the hash A hash digest is like
a person’s fingerprint A fingerprint uniquely identifies an individual
without revealing anything about that person—you can’t determine
someone’s eye color, height, or gender from a fingerprint Figure 1-2
shows the SHA-1 hash digests for various strings Notice that even verysimilar strings have quite different hash digests
Figure 1-2: SHA-1 hash digests
It’s common, as shown in Figure 1-2, to display a hash as a base-64encoded 28-character string This is easier to read than a 48-digit (160-bit) number
Hash digests are useful for verifying that someone knows a password,without actually storing the password Storing passwords unencrypted inthe database opens two security holes:
If an intruder gains access to the database, he can use the
information to later log on to the system using someone else’susername and password
Trang 24Dim uEncode As New UnicodeEncoding()
Trang 27"‘" & strUsername & "‘ As Field3"
Trang 287 Press F5 to run the project You can log on using the usernameRKing with the password RKing, as shown in the following
illustration Congratulations—you are now checking passwordswithout storing passwords! Even if an intruder gains access tothe database, the password hash digests can’t then be used tolog on
How Does a Hash Digest Work?
How does a hash digest work? If each unique string results in a uniquehash digest, is it possible to decrypt the hash digest and derive theoriginal string?
To answer these two questions, let’s create a simple hash algorithm.We’ll start by assigning every letter in the alphabet a unique number,
so A is equal to 1, B equal to 2, C equal to 3, and so on up to Z, which
is equal to 26 Next we’ll use these values to create a hash by addingthem together for each character in a string The string VB generates ahash of 24 because V is the 22nd letter in the alphabet and B is thesecond letter (22 + 2 = 24)
Can the hash of 24 be reverse-engineered to derive the original
string? No The hash doesn’t tell us the length, starting character, oranything else about the original string In this simple example, thestrings VB, BV, BMDACA, FEJAAA, and thousands of other
combinations all give a hash of 24 When different strings produce the
same hash value, this is known as a collision A good hashing
algorithm should produce unique results and be collision-free SHA-1
produces collision-free results, and it scrambles and condenses theoriginal string in such a way that it’s considered computationally
infeasible to derive the original string
Trang 29application that opens a database directly For a client-server application
or a Web application, this mechanism does not protect against “spoofing” the server component—where an intruder who knows the hashesconstructs a fake client appli cation that submits the hash to the server.However, if an intruder gains access to the list of passwords, they can doless damage if the passwords are hashed
Trang 30While hash digests are useful for one-way encryption, when you need todecrypt the encrypted information, you need to use two-way encryption.The most common two way-encryption technique is key-based
encryption A key is simply a unique string that you pass together with aplain-text message to an encryption algorithm, which returns the
message encrypted as cipher text The cipher text bears no resemblance
to the original message To decrypt the cipher text, you again pass thekey with the cipher text to a decryption algorithm, which returns the
Trang 31’Private key
Dim slt(0) As Byte
Trang 32’Return result as a Base64 encoded string
Return Convert.ToBase64String(stmCipherText.ToArray()) End Function
Trang 36The Triple-DES encryption algorithm we use accepts a 24-character
string for a key The 24 characters are treated as a passphrase that is
used to derive a 192-bit byte array, which is then used as the actual key.This is known as 192-bit encryption The number of bits in the key
determines the total combination of possible keys—for example, a 192-bitkey has 6.3 × 1057 possible values A common method intruders use totry to crack encryption is a brute force attack, which means trying everydifferent key combination available until they find the key that works Themore bits in the key, the longer it takes for a brute force attack to find thekey An intruder using the latest hardware would take a long time to crack
a 192-bit key—supposing the intruder can try 1,000,000,000,000 keys asecond, it would take about
200,000,000,000,000,000,000,000,000,000,000,000,000 years to tryevery combination Even if the intruder got lucky, and found the key aftertrying only 0.0000000001% of the available combinations, the task wouldstill take trillions of years
Another method intruders use for cracking encryption is to find where thekey is stored and then simply read the key How can you store the key toprotect against this? The least secure method is to store the key
unencrypted in a file or in the registry accessible to everyone, since if anintruder gains access to your machine, all he needs is notepad.exe toread the file or RegEdit.exe to read the registry Hard-coding the key inthe application (as the employee management system currently does) isalso not a good idea since if an intruder gets a copy of your application,
he could easily use a de-compiler or debugger to find the key A bettermethod is to encrypt the key and store it in a file that is protected by thefile system so that only authorized users of the system can read it Thisimmediately raises the questions of where to store the key you use toencrypt the private key? Windows helps with this by providing methodsfor encrypting and decrypting sensitive data by using logon credentials as
a key When using these methods, there are several things to be awareof:
Data encrypted by one user cannot be decrypted by another
Trang 39Public key encryption (also called asymmetric encryption) has an
important difference from private key encryption Public key encryptionuses two different keys: one key for encryption and another key for
decryption Why don’t they simply call this two-key encryption and callprivate key encryption one-key encryption? While it is well known thatsecurity experts like to invent jargon to justify their high consultancy fees,there is also a logical reason for this naming, which lies in the way thetwo types of encryption are used
While private key encryption assumes that both the encrypting and
decrypting parties already know the private key, public key encryptionprovides a method to securely issue a key to someone and have thatindividual send you information that only you can decrypt It works likethis: Our system creates a public/private key pair We send the public key
to someone who uses it to encrypt a message She sends the encryptedmessage to us, and we decrypt the message with the private key (Note:The private key is not the same as the key used in private key
encryption.) Even if an intruder gains possession of the public key, hecannot use it to decrypt the encrypted message because only the privatekey can decrypt the message, and this is never given away In contrastwith private key encryption, the keys used in public key encryption aremore than simple strings The key is actually a structure with eight fields:two of the fields are used for encrypting with the public key, and six areused for decrypting with the private key The public key is obtained byextraction from the private key, which is why the private key can be usedfor both encryption and decryption Figure 1-4 shows how public keyencryption and decryption work, using the example of a system
requesting a credit card number from a user
Trang 40Figure 1-4: Public key encryption and decryption
Public key encryption is slower than private key encryption and cannotprocess large amounts of data The RSA algorithm (RSA refers to theinitials of the people who developed it: Ron Rivest, Adi Shamir, and
Leonard Adleman) can encrypt a message of only 116 bytes (58 unicodecharacters) A common use for public key encryption is for securely
passing a private key, which is then used for encrypting and decryptingother information
Add public key encryption to the security library
In this exercise, you will add public key encryption functions to your
security library
1 In Visual Studio NET, open the project CH01_Encryption\EMS\Start\EMS.sln
2 Open SecurityLibrary.vb Add the following code:
Namespace PublicKey
Module PublicKey