Tải bản đầy đủ (.pdf) (553 trang)

Addison wesley the dot NET developers guide to windows security oct 2004 ISBN 0321228359

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.96 MB, 553 trang )






TableofContents
Index

The.NETDeveloper'sGuidetoWindows
Security
ByKeithBrown

Publisher :AddisonWesley
PubDate :September27,2004
ISBN :0-321-22835-9
Pages :408


"Asusual,Keithmasterfullyexplainscomplex
securityissuesindown-to-earthandeasy-tounderstandlanguage.Ibetyou'llreachfor
thisbookoftenwhenbuildingyournext
softwareapplication."
--MichaelHoward,coauthor,WritingSecure
Code
"WhenitcomestoteachingWindows
security,KeithBrownis'TheMan.'InThe
.NETDeveloper'sGuidetoWindows


Security,Keithhaswrittenabookthat
explainsthekeysecurityconceptsof


WindowsNT,Windows2000,WindowsXP,
andWindowsServer2003,andteachesyou
bothhowtoapplythemandhowto
implementtheminC#code.Byorganizing
hismaterialintoshort,clearsnippets,Brown
hasmadeacomplicatedsubjecthighly
accessible."
--MartinHeller,seniorcontributingeditorat
Byte.comandownerofMartinHeller&Co.
"KeithBrownhasauniqueabilitytodescribe
complextechnicaltopics,suchassecurity,in
awaythatcanbeunderstoodbymere
mortals(suchasmyself).Keith'sbookisa
mustreadforanyoneattemptingtokeepup
withMicrosoft'senhancementstoitssecurity
featuresandthenextmajorversionof.NET."
--PeterPartch,principalsoftwareengineer,
PMConsulting
"Keith'sbookisacollectionofpractical,
concise,andcarefullythoughtoutnuggetsof
securityinsight.Every.NETdeveloperwould
bewisetokeepacopyofthisbookcloseat
handandtoconsultitfirstwhenquestionsof


securityariseduringapplication
development."
--FritzOnion,authorofEssentialASP.NET
withExamplesinC#
The.NETDeveloper'sGuidetoWindows

Securityisrequiredreadingfor.NET
programmerswhowanttodevelopsecure
Windowsapplications.Readersgainadeep
understandingofWindowssecurityandthe
know-howtoprogramsecuresystemsthat
runonWindowsServer2003,WindowsXP,
andWindows2000.
AuthorKeithBrowncrystallizeshisapplication
securityexpertiseinto75short,specific
guidelines.Eachitemisclearlyexplained,
cross-referenced,andillustratedwithdetailed
examples.Theitemsbuildononeanother
untiltheyproduceacomprehensivepictureof
whattoolsareavailableandhowdevelopers
shouldusethem.
ThebookhighlightsnewfeaturesinWindows
Server2003andpreviewsfeaturesofthe
upcomingversion2.0ofthe.NETFramework.
AcompanionWebsiteincludesthesource


codeandexamplesusedthroughoutthe
book.
Topicscoveredinclude:
Kerberosauthentication
Accesscontrol
Impersonation
Networksecurity
Constraineddelegation
Protocoltransition

Securingenterpriseservices
Securingremoting
Howtorunasanormaluserandlivea
happylife
ProgrammingtheSecuritySupport
ProviderInterface(SSPI)inVisual
Studio.NET2005


Battle-scarredandemergingdevelopersalike
willfindinThe.NETDeveloper'sGuideto
WindowsSecuritybona-fidesolutionsto
theeverydayproblemsofsecuringWindows
applications.







TableofContents
Index

The.NETDeveloper'sGuidetoWindows
Security
ByKeithBrown

Publisher :AddisonWesley
PubDate :September27,2004

ISBN :0-321-22835-9
Pages :408











Copyright
PraiseforThe.NETDeveloper'sGuidetoWindowsSecurity
Microsoft.NETDevelopmentSeries
TitlesintheSeries
Preface
Acknowledgments
PartI.TheBigPicture
Chapter1.WhatIsSecureCode?




Chapter2.WhatIsaCountermeasure?





Chapter4.WhatIsthePrincipleofLeastPrivilege?




Chapter6.WhatIsAuthentication?




Chapter8.WhatIsaNonprivilegedUser?




Chapter3.WhatIsThreatModeling?
Chapter5.WhatIsthePrincipleofDefenseinDepth?
Chapter7.WhatIsaLuringAttack?
Chapter9.HowtoDevelopCodeasaNon-Admin
TheSecondaryLogonService
ButIHatetheCommandPrompt!





NetworkCredentials





Debugging




WritingCodeThatCanBeUsedbyaNon-Admin




InstallationTips

ASampleSetupforaVS.NETDeveloper
CreatingWebProjectsinVS.NET
IsolatedStorage
Chapter10.HowtoEnableAuditing

Chapter11.HowtoAuditAccesstoFiles


PartII.SecurityContext
Chapter12.WhatIsaSecurityPrincipal?




Chapter13.WhatIsaSID?





Chapter15.WhatIsSecurityContext?




Chapter16.WhatIsaToken?




Chapter18.WhatIsaWindowStation?




Chapter20.WhatIsaGroup?




Chapter14.HowtoProgramwithSIDs
SecurityContextinthe.NETFramework
Chapter17.WhatIsaLogonSession?
Chapter19.WhatIsaUserProfile?
TheMechanicsofGroupExpansion
ButWhataboutNTLM?
LatencyandAuthenticity





Chapter21.WhatIsaPrivilege?




Chapter23.HowtoGrantorRevokePrivilegesviaSecurityPolicy




Chapter25.HowtoCreateaWindowsPrincipalGivenaToken




Chapter22.HowtoUseaPrivilege
Chapter24.WhatAreWindowsIdentityandWindowsPrincipal?
Chapter26.HowtoGetaTokenforaUser
CallingLogonUser
TheSSPIWorkaround




Chapter27.WhatIsaDaemon?





Chapter29.HowtoDisplayaUserInterfacefromaDaemon




Chapter31.WhatIsImpersonation?




Chapter32.HowtoImpersonateaUserGivenHerToken

Chapter28.HowtoChooseanIdentityforaDaemon
Chapter30.HowtoRunaProgramasAnotherUser
PitfallstoWatchFor
ImpersonationinASP.NET




Chapter33.WhatIsThread.CurrentPrincipal?




Chapter34.HowtoTrackClientIdentityUsingThread.CurrentPrincipal





Chapter36.WhatIsaGuestLogon?

Chapter35.WhatIsaNullSession?
Chapter37.HowtoDealwithUnauthenticatedClients


PartIII.AccessControl
Chapter38.WhatIsRole-BasedSecurity?

Chapter39.WhatIsACL-BasedSecurity?




Chapter40.WhatIsDiscretionaryAccessControl?




Chapter42.WhatIsaSecurityDescriptor?




Chapter44.WhatIsaPermission?





Chapter46.HowtoTakeOwnershipofanObject




Chapter48.HowtoPersistaSecurityDescriptor

Chapter41.WhatIsOwnership?
Chapter43.WhatIsanAccessControlList?
Chapter45.WhatIsACLInheritance?
Chapter47.HowtoProgramACLs
Chapter49.WhatIsAuthorizationManager?




IntroducingAuthorizationManager




AuthorizationStore




Stores,Applications,andScopes





Scripts




Auditing

ASampleApp:TheCorporateLibrary
TheAzManRuntimeInterface
ApplicationGroups
SupportingAuthorizationScripts
Conclusion


PartIV.COM(+)andEnterpriseServices
Chapter50.WhatIstheCOM(+)AuthenticationLevel?

Chapter51.WhatIstheCOM(+)ImpersonationLevel?




Chapter52.WhatIsCoInitializeSecurity?



Chapter53.HowtoConfigureSecurityforaCOM(+)Client




Chapter54.HowtoConfiguretheAuthenticationandImpersonationLevelsfor
aCOM+Application
Chapter55.HowtoConfiguretheAuthenticationandImpersonationLevelsfor
anASP.NETApplication
Chapter56.HowtoImplementRole-BasedSecurityforanEnterpriseServices
Application




WindowsXPServicePack2


Chapter57.HowtoConfigureProcessIdentityforaCOM(+)ServerApplication


PartV.NetworkSecurity
Chapter58.WhatIsCIA?




MessageAuthenticationCodes
Chapter59.WhatIsKerberos?





Cross-DomainAuthenticationandDomainTrusts




User-to-UserAuthentication

WhatElseIsinaTicket?
Chapter60.WhatIsaServicePrincipalName(SPN)?




Chapter61.HowtoUseServicePrincipalNames




Chapter63.WhatIsProtocolTransition?




Chapter65.WhatIsSSPI?




Chapter67.HowtoAddCIAto.NETRemoting


Chapter62.WhatIsDelegation?
Chapter64.HowtoConfigureDelegationviaSecurityPolicy
Chapter66.HowtoAddCIAtoaSocket-BasedAppUsingSSPI
Chapter68.WhatIsIPSEC?

Chapter69.HowtoUseIPSECtoProtectYourNetwork


PartVI.Miscellaneous
Chapter70.HowtoStoreSecretsonaMachine




SecretsinASP.NETConfigurationFiles
TheDataProtectionClass




Chapter71.HowtoPromptforaPassword




Chapter73.HowtoProgrammaticallyLogOfforReboottheMachine

Chapter72.HowtoProgrammaticallyLocktheConsole
Chapter74.WhatisGroupPolicy?


Chapter75.HowtoDeploySoftwareSecurelyviaGroupPolicy


BIBLIOGRAPHY

Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andAddison-Wesley
wasawareofatrademarkclaim,thedesignationshavebeen
printedwithinitialcapitallettersorinallcapitals.
The.NETlogoiseitheraregisteredtrademarkortrademarkof
MicrosoftCorporationintheUnitedStatesand/orother
countriesandisusedunderlicensefromMicrosoft.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedin
quantityforbulkpurchasesandspecialsales.Formore
information,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsideoftheU.S.,pleasecontact:

InternationalSales

VisitAddison-WesleyontheWeb:
www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData


Brown,Keith,1967
The.NETdeveloper'sguidetoWindowssecurity
/KeithBrown.
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-321-22835-9(pbk.:alk.paper)
1.Computersecurity.2.MicrosoftWindows
(Computerfile)3.Microsoft.NET.I.Title.
QA76.9.A25B7752004
005.8--dc22
2004013971
Copyright©2005byPearsonEducation,Inc.
Allrightsreserved.Nopartofthispublicationmaybe
reproduced,storedinaretrievalsystem,ortransmitted,inany
form,orbyanymeans,electronic,mechanical,photocopying,
recording,orotherwise,withoutthepriorconsentofthe
publisher.PrintedintheUnitedStatesofAmerica.Published
simultaneouslyinCanada.
Forinformationonobtainingpermissionforuseofmaterialfrom
thiswork,pleasesubmitawrittenrequestto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300

Boston,MA02116
Fax:(617)848-7047
Textprintedonrecycledpaper
12345678910PH0807060504
Firstprinting,September2004

Dedication


Tothecountlessnumberofprogrammersstrugglingdailyto
writesecurecodeontheWindowsplatform


PraiseforThe.NETDeveloper'sGuideto
WindowsSecurity
"Asusual,Keithmasterfullyexplainscomplexsecurity
issuesindown-to-earthandeasy-to-understandlanguage.
Ibetyou'llreachforthisbookoftenwhenbuildingyour
nextsoftwareapplication."
MichaelHoward,MicrosoftCorporation,coauthor,Writing
SecureCode
"WhenitcomestoteachingWindowssecurity,Keith
Brownis'TheMan.'InThe.NETDeveloper'sGuideto
WindowsSecurity,Keithhaswrittenabookthatexplains
thekeysecurityconceptsofWindowsNT,Windows2000,
WindowsXP,andWindowsServer2003,andteachesyou
bothhowtoapplythemandhowtoimplementthemin
C#code.Byorganizinghismaterialintoshort,clear
snippets,Brownhasmadeacomplicatedsubjecthighly
accessible."

MartinHeller,seniorcontributingeditoratByte.comand
ownerofMartinHeller&Co.
"Keith'sbookisacollectionofpractical,concise,and
carefullythoughtoutnuggetsofsecurityinsight.Every
.NETdeveloperwouldbewisetokeepacopyofthisbook
closeathandandtoconsultitfirstwhenquestionsof
securityariseduringapplicationdevelopment."
FritzOnion,authorofEssentialASP.NETwithExamplesin
C++
"KeithBrownhasauniqueabilitytodescribecomplex


technicaltopics,suchassecurity,inawaythatcanbe
understoodbymeremortals(suchasmyself).Keith's
bookisamustreadforanyoneattemptingtokeepup
withMicrosoft'senhancementstoitssecurityfeaturesand
thenextmajorversionof.NET."
PeterPartch,principalsoftwareengineer,PMConsulting
"Thewritingissuperb.Itprovidesadead-onaccurate
walkthroughverytechnicalterritory."
BillMoseley,professorofcomputerstudies,Bakersfield
College
"KeithBrownwriteswithacombinationofclarityand
compellingstylethatmakeanythingfromhimworth
reading.Combinethiswithhisencyclopedicknowledgeof
theWindowssecurityinfrastructure,andyougetabook
thateveryWindowsdevelopershouldkeepnexttohisor
hercomputer."
CraigAndera,seniorconsultant,WangderaCorporation
"Securityisthenumberonetopicofimportancefor

developerstodayyousimplycan'twriteproductioncode
withoutknowingaboutthingslikepermissionsandbuffer
overruns.Keithwasyearsaheadofthecrowd,spreading
thewordaboutgoodsecurityhygieneandleadingthe
discussionbeforethetopicbecamevital."
JoshuaTrupin,executiveeditor,MSDNMagazine


Microsoft.NETDevelopmentSeries
JohnMontgomery,SeriesAdvisor
DonBox,SeriesAdvisor
MartinHeller,SeriesEditor
TheMicrosoft.NETDevelopmentSeriesissupportedand
developedbytheleadersandexpertsofMicrosoftdevelopment
technologiesincludingMicrosoftarchitectsandDevelopMentor
instructors.Thebooksinthisseriesprovideacoreresourceof
informationandunderstandingeverydeveloperneedsinorder
towriteeffectiveapplicationsandmanagedcode.Learnfrom
theleadershowtomaximizeyouruseofthe.NETFramework
anditsprogramminglanguages.


TitlesintheSeries
BradAbrams,.NETFrameworkStandardLibraryAnnotated
ReferenceVolume1,0-321-15489-4
KeithBallinger,.NETWebServices:Architectureand
Implementation,0-321-11359-4
BobBeauchemin,NielsBerglund,DanSullivan,AFirstLookat
SQLServer2005forDevelopers,0-321-18059-3
DonBoxwithChrisSells,Essential.NET,Volume1:The

CommonLanguageRuntime,0-201-73411-7
MaheshChand,GraphicsProgrammingwithGDI+,0-32116077-0
AndersHejlsberg,ScottWiltamuth,PeterGolde,TheC#
ProgrammingLanguage,0-321-15491-6
AlexHomer,DaveSussman,MarkFussell,AFirstLookat
ADO.NETandSystem.Xmlv.2.0,0-321-22839-1
AlexHomer,DaveSussman,RobHoward,AFirstLookat
ASP.NETv.2.0,0-321-22896-0
JamesS.MillerandSusannRagsdale,TheCommonLanguage
InfrastructureAnnotatedStandard,0-321-15493-2
FritzOnion,EssentialASP.NETwithExamplesinC#,0-20176040-1
FritzOnion,EssentialASP.NETwithExamplesinVisualBasic
.NET,0-201-76039-8
TedPattisonandDr.JoeHummel,BuildingApplicationsand
ComponentswithVisualBasic.NET,0-201-73495-8


ChrisSells,WindowsFormsProgramminginC#,0-321-116208
ChrisSellsandJustinGehtland,WindowsFormsProgramming
inVisualBasic.NET,0-321-12519-3
PaulVick,TheVisualBasic.NETProgrammingLanguage,0321-16951-4
DamienWatkins,MarkHammond,BradAbrams,Programming
inthe.NETEnvironment,0-201-77018-0
ShawnWildermuth,PragmaticADO.NET:DataAccessforthe
InternetWorld,0-201-74568-2
PaulYaoandDavidDurant,.NETCompactFramework
ProgrammingwithC#,0-321-17403-8
PaulYaoandDavidDurant,.NETCompactFramework
ProgrammingwithVisualBasic.NET,0-321-17404-6
Formoreinformationgoto

www.awprofessional.com/msdotnetseries/


Preface
Thisbookwaswrittenforthemanythousandsofpeople
involvedindesigningandwritingsoftwarefortheMicrosoft
.NETplatform.Itischock-fulloftipsandinsightsaboutuserbasedsecurity,whichIliketoterm"Windowssecurity"because
it'sbeenaroundinoneformoranothersinceWindowsNTfirst
shipped.Giventheplethoraofbooksthatcoverthenew
securityfeaturesinthe.NETFramework,suchascodeaccess
securityandASP.NETformsauthentication,Idecidedtowritea
booktohelpfolkswiththebasicsofWindowssecurity,atopic
thatmostotherbooksmissentirelyorgetsubtlyorblatantly
wrong.Thisbookisinsomesenseasecondeditionofmyfirst
securitybook,ProgrammingWindowsSecurity,butIhopethat
youwillfinditimmenselymoreapproachableandpractical.I've
triedtodistilltheZenofthesetopicsintosmalltidbitsof
informationitemsthatlinktooneanotherallowingyoutoread
thebookinanyorderthatsuitsyou.Ihopethatyou'llfindthe
formatof75concisetidbitsofinformationhelpfulasa
reference.The"whatis"itemsfocusonexplainingconcepts,
whilethe"howto"itemsfocusonhelpingyouperforma
commontask.
WithinthesepagesIcoversecurityfeaturesinvariousversions
ofWindowsbasedonWindowsNT.ThisincludesWindows2000,
WindowsXPProfessional,andWindowsServer2003,butdoes
notinclude16-bitWindowsoranyoftheWin9Xflavors
(Windows95/98,WindowsME,WindowsXPHomeEdition).So,
whenItalkabout"Windows"I'mreferringtotheversionsbased
onWindowsNT.WheneverItalkaboutthefilesystem,I'm

assumingthatyou'reusingNTFS,notFATpartitions.Whenever
Italkaboutdomains,I'massumingWindows2000orgreater.If
you'restilllivingwithaWindowsNT4domain,youhavemy
sincerecondolences!


ManypeoplehaveexpressedsurprisethatIoccasionallytalk
aboutWin32APIsandrefertoWin32headerfilesinabookfor
.NETprogrammers.IwishIdidn'thavetodothis,butas
anyonewhohasexperiencewiththe.NETFrameworkknows,
theframeworkclasslibrarywrapsonlyafractionofthe
functionalityoftheWindowsplatformasofthiswriting.The
coveragewillgetbetterovertime,buttodomanythingsin
Windows(includingsecurityprogramming),youoftenneedto
callnativeWin32APIs.Evenasversion2.0oftheframeworkis
beingrevealedinbeta1,youcanseethatcoverageincreasing,
butit'sstillnotcomplete.Inanycase,I'vetriedtomakeitclear
intheprosewhenI'mtalkingaboutaWin32APIversusa.NET
Frameworkclass,andI'veprovidedlotsofsamplecodeand
helperclasseswritteninManagedC++thatyoucanleverageto
avoidhavingtocallthoseAPIsyourself.
Thisbookcanbefoundonline(initsentirety)inhyperlinked
formontheWebatwinsecguide.net,whereIbelieveyou'llfind
ittobeagreatreferencewhenyou'reconnected.Iplanto
continuefillinginmoreitemsovertime,sosubscribetotheRSS
feedonthebookfornews.Youcanalsodownloadsamplesand
toolsthatImentioninthebookfromthisWebsite.Erratawill
bepostedtothissiteaswell,soifyoufindaproblempleaselet
meknow.
Goodluckinyourendeavors!

KeithBrown
HighlandsRanch,CO
/>

Acknowledgments
Thankstomytechnicalreviewers:JohnLambert,PeterPartch,
andBillMoseley.Thebookwouldn'tbethesamewithoutyour
efforts.
I'dliketosayaspecialthankyoutoDonBox,whojumpstartedmywritingandteachingcareerbackin1997whenhe
invitedmetoteachCOMforthetrainingcompanyhefounded.
ItwasDonwhohelpedmelandacolumnwithMicrosoft
SystemsJournal.Heencouragedmetoworkonsecurityback
whennobodyseemedtocareaboutthetopic.I'mstillusinghis
WordtemplatewhenIwritearticlesforMSDNMagazine.
Thankstoallofthepeoplewhoreadtheonlineversionofthe
bookbeforeitwaspublishedandtookthetimetoe-mailin
suggestions.Lotsofthetipsinthesectiononrunningasnonadmincamefromthesefolks.
ThankstoChrisSellsforhissimplesuggestionbeforeIeven
startedwriting."Pleasegivemesomethingpractical,"heasked.
Thankstoallofmystudentsovertheyears.Yourquestionsand
insightshavechallengedandstrengthenedme.Pleasecomeup
andsayhelloifyouseemeatanevent.Stayintouch!
ThankstothefolksatAddison-Wesleyfortheirhelpingetting
thisbookofftheground.KarenGettman,myeditor,didn'tlet
meslip(well,notmuchatleast).Thanksforgivingmethe
leewayIneededtofindthisratheroff-the-wallformatforthe
book.ThankstoElizabethRyanatAddison-Wesleyforher
coordinationofthebookthroughproductionandtoConnie
LeavittatBookwrightsformanagingtheproductionprocess,
evenasIsubmittedentirelynewcontentafterbeta1shipped.

ThankstoCurtJohnsonandhisstaffwhosomehowfiguredout


howtosellallthesepaperweightsI'vebeenwritingoverthe
years.


PartI:TheBigPicture
Chapter1.WhatIsSecureCode?
Chapter2.WhatIsaCountermeasure?
Chapter3.WhatIsThreatModeling?
Chapter4.WhatIsthePrincipleofLeastPrivilege?
Chapter5.WhatIsthePrincipleofDefenseinDepth?
Chapter6.WhatIsAuthentication?
Chapter7.WhatIsaLuringAttack?
Chapter8.WhatIsaNonprivilegedUser?
Chapter9.HowtoDevelopCodeasaNon-Admin
Chapter10.HowtoEnableAuditing
Chapter11.HowtoAuditAccesstoFiles


Chapter1.WhatIsSecureCode?
Oneofthemajorgoalsofthisbookistohelpclarifyhow
Windowssecurityworkssoyou'llbeabletouseiteffectivelyin
yourapplicationsandalsoinyoureverydaylife.Butevenifyou
haveaperfectunderstandingofallthesecurityfeaturesofthe
platform,andmakealltherightAPIcallsandconfiguresecurity
policyverycarefullytokeepoutattackers,ifyoudon'twrite
yourcodewithsecurityinmind,noneofthatwillmatter
becauseyou'llstillbevulnerabletoattack.

LookatthefollowingC#methodandcountthenumberof
securityAPIsthatituses.

//thiscodehasareallynastysecurityflaw
voidLogUserName(SqlConnectionconn,stringuserName){

stringsqlText="insertuser_namesvalues('"+userName+"'
SqlCommandcmd=newSqlCommand(sqlText,conn);
cmd.ExecuteNonQuery();
}


That'sright,itdoesn'tcallanysecurityAPIs.However,ifwe
assumetheuserNameparameterhasbeengiventousby
someonewedon'tfullytrust(akaauserofourapplication)
thenthisbenign-lookingcodehasahorriblesecurityflaw.Ifthe
abovefunctionhadbeenwrittenwithsecurityinmind,here's
howitmighthavelookedinstead:

//muchmoresecurecode
voidLogUserName(SqlConnectionconn,stringuserName){
stringsqlText="insertuser_namesvalues(@n)";
SqlCommandcmd=newSqlCommand(sqlText,conn);
SqlParameterp=cmd.Parameters.Add("@n",
SqlDbType.VarChar,userName.Length);
p.Value=userName;
cmd.ExecuteNonQuery();
}

Notethedifferenceinthecodingstyle.Inthefirstcase,the

coderappendeduntrusteduserinputdirectlyintoaSQL


statement.Inthesecondcase,thecoderhardcodedtheSQL
statementandencasedtheuserinputinaparameterthatwas
sentwiththequery,carefullykeepinganypotentialattackersin
thedatachannelandoutofthecontrolchannel(theSQL
statementinthiscase).
Theflawinthefirstbitofcodeisthatauserwithmalicious
intentcantakecontrolofourSQLstatementanddopretty
muchwhateverhewantswiththedatabase.We'veallowedan
attackertoslipintoacontrolchannel.Forexample,whatifthe
userweretosubmitthefollowingstringasausername?

SeeYa');droptableuser_names--

OurSQLstatementwouldnowbecome

insertuser_namesvalues('SeeYa');droptableuser_names--')


×