We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

ASP.NET: Don’t do that... do this!

00:00

Formal Metadata

Title
ASP.NET: Don’t do that... do this!
Alternative Title
Don’t do that, do this! Recommendations from the ASP.NET team
Title of Series
Number of Parts
150
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
ASP.NET’s been around for a number of years and the team’s developed some DOs and DON’Ts. Let’s explore out very best list of DON’Ts that you can apply today at work! Come see Damian Edwards, Senior Program Manager on the ASP.NET team, share internals, secrets and not-so-secrets of the ASP.NET APIs that you should be exploiting and the ones you should be avoiding.
31
59
Thumbnail
1:00:41
89
Thumbnail
1:00:33
90
Thumbnail
1:00:33
102
Software developerHacker (term)Presentation of a groupInformation securityStandard deviationControl flowCross-site scriptingHypermediaView (database)GUI widgetMarkup languageMobile WebLatent heatComputer fontLevel (video gaming)Web pageWeb pageMobile WebGame controllerWeb browserGraph coloringEvent horizonString (computer science)Web 2.0Form (programming)Standard deviationPoint (geometry)Social classInformation securityPhysical systemType theoryCategory of beingView (database)Template (C++)System callLink (knot theory)SmartphoneCuboidGoodness of fitLevel (video gaming)LaptopPower (physics)QuicksortMultiplication signExterior algebraBitElectronic mailing listRevision controlWeightElectronic program guideIntelCASE <Informatik>MeasurementMetropolitan area networkPortable communications deviceAdaptive behaviorDependent and independent variablesCartesian coordinate systemLatent heatSheaf (mathematics)Internet service providerArmGroup actionRun time (program lifecycle phase)Extension (kinesiology)RoutingUniform resource locatorWebsiteMathematicsVirtual machineLogicHypermediaForcing (mathematics)Right angleCellular automaton1 (number)Presentation of a groupCausalityResultantDot productSoftware frameworkWireless Markup LanguageGodDifferent (Kate Ryan album)Drop (liquid)Demo (music)Asynchronous Transfer ModeCodeClassical physicsBeta functionComputer fontLine (geometry)Application service providerSoftware testingVolumenvisualisierungPerfect groupCross-site scriptingBootingKeyboard shortcut.NET FrameworkCodeXMLUMLComputer animation
Web pageGUI widgetControl flowWeb browserRevision controlClient (computing)Information securityWebsiteCodeJava appletString (computer science)Physical systemNumbering schemeMultiplication signString (computer science)Software testingType theoryMassoutputEmailKeyboard shortcutUniform resource locatorPoisson-KlammerRevision controlDomain nameCodierung <Programmierung>Hash functionParameter (computer programming)Web browserForm (programming)Regulärer Ausdruck <Textverarbeitung>AngleAddress spaceValidity (statistics)Library (computing)Medical imagingDatabaseWeightUtility softwareServer (computing)CodeModule (mathematics)Goodness of fitExpressionWebsiteGodQuery languageSoftware developerClient (computing)Function (mathematics)Patch (Unix)Web 2.0Web pageOrder (biology)Default (computer science)Content (media)Application service providerGame controllerSpherical capCuboidSign (mathematics)Token ringElectronic mailing listStandard deviationBitElement (mathematics)Vulnerability (computing)ParsingNumberPhysical systemTouchscreenInformation securityReal-time operating system.NET FrameworkTemplate (C++)File formatResultantInterior (topology)Mobile WebFluid staticsHTTP cookieQuicksortBackupPlanningUnicodeExtension (kinesiology)Endliche ModelltheorieMereologyInstance (computer science)Right angleFamilyArchaeological field surveyLevel (video gaming)SequelPlastikkarteScripting languageSystem callCross-site scriptingCASE <Informatik>Office suitePressureGoogolArmJava appletPrime numberInternet service providerInternet forumGame theoryComputer animation
Java appletString (computer science)CodeNumbering schemePhysical systemWebsiteHTTP cookieForm (programming)SpywareAuthenticationInformationWeb pageState of matterView (database)Systems engineeringComputer configurationIRIS-TCase moddingBoundary value problemInformation securityIdentity managementState of matterProcess (computing)Internet service providerView (database)Boundary value problemInformation securityEqualiser (mathematics)Category of beingTask (computing)Block (periodic table)Set (mathematics)Configuration spaceCartesian coordinate systemSemiconductor memoryHypermediaArithmetic meanWeb pageGame controllerServer (computing)Point (geometry)Identity managementRevision controlLevel (video gaming)Validity (statistics)Physical systemFormal languageExecution unitCodeAuthenticationHTTP cookieQuicksortLink (knot theory)WindowArmType theoryInformationComputer iconSoftwareOffice suiteForm (programming)Scripting languageWeb browserWebsiteInstance (computer science)Uniform resource locatorLattice (order)DatabaseConnected spaceEvent horizonStructural loadMessage passingMereologyRight angleMultiplicationMobile appCASE <Informatik>Archaeological field surveySystem callPlastikkarteSound effectAttribute grammarCellular automatonString (computer science)WeightToken ringFlagHidden variable theoryDefault (computer science)BuildingPower (physics)Different (Kate Ryan album)TheoryMappingAreaTwitterWeb 2.0Knowledge baseGrand Unified TheoryDomain name.NET FrameworkVulnerability (computing)Application service providerPartial derivativeCross-site scriptingSoftware bugAuthorizationHyperlinkCodierung <Programmierung>Multiplication signVector potentialElectronic mailing listComputer wormComputer animation
Identity managementBoundary value problemInformation securityServer (computing)Patch (Unix)Coma BerenicesApplication service providerWeightElement (mathematics)Key (cryptography)Configuration spacePoint (geometry)Token ringBoolean algebraData typeCodeProcess (computing)Event horizonCoding theorySoftware developerUniform resource locatorWeb pageLoginCartesian coordinate systemAttribute grammarClient (computing)String (computer science)outputQuery languageParameter (computer programming)Modul <Datentyp>OvalSynchronizationTask (computing)Information securityAttribute grammarEvent horizonSet (mathematics)Positional notationPatch (Unix)Link (knot theory)Lambda calculusEmailCross-site scriptingSoftwareSoftware developerElement (mathematics)Mobile appConfiguration spaceString (computer science).NET FrameworkWeb 2.0Key (cryptography)Social classModule (mathematics)Codierung <Programmierung>Content (media)Vulnerability (computing)CodeBitApplication service providerWeightComputer fileDomain nameDatabaseMathematicsCartesian coordinate systemMultiplication signWeb pageElectronic mailing list1 (number)Knowledge baseProduct (business)Query languageUniform resource locatorDemo (music)Form (programming)Task (computing)Message passingOvalConnectivity (graph theory)Structural loadStandard deviationCondition numberWindowCASE <Informatik>Information technology consultingServer (computing)Run time (program lifecycle phase)Moving averageoutputHyperlinkReading (process)Water vaporRevision controlEndliche ModelltheorieOffice suiteDirected graphInternet service providerSingle-precision floating-point formatNumbering schemePlastikkarteSynchronizationCountingPresentation of a groupLevel (video gaming)Metropolitan area networkMereologyInternet forumState of matterEscape characterHypermediaDisk read-and-write headWordScripting languageRight angleComputer animation
Task (computing)Web pageOvalSynchronizationEvent horizonInternet service providerMaxima and minimaForm (programming)Streaming mediaoutputBuffer solutionThread (computing)Electric currentCodeSoftware frameworkDependent and independent variablesContext awarenessWeb pageDirected graphQueue (abstract data type)Mobile appWeb 2.0Default (computer science)Multiplication signComputer programmingApplication service providerInternet service providerStructural loadoutputThread (computing)WindowServer (computing)Process (computing)Computer fileEvent horizonGroup actionContext awarenessCodeTrailDependent and independent variablesSoftwarePattern languageString (computer science)Object (grammar)Streaming mediaDomain nameType theoryCartesian coordinate systemTask (computing)OvalSoftware frameworkInformation overload2 (number)Form (programming)Exception handlingWeightLine (geometry)Functional (mathematics)Crash (computing)Visualization (computer graphics)MiniDiscSystem callOrder (biology)Game controllerClient (computing)Point (geometry)SynchronizationProjective planeState of matterRun time (program lifecycle phase)Variable (mathematics)Forcing (mathematics)AeroelasticityLevel (video gaming)ArmWritingDifferent (Kate Ryan album)Module (mathematics)Endliche ModelltheorieBlogInternet forumComputer networkMultitier architectureSemiconductor memoryImpulse responseRight angleGraphics tabletWave packetSpeech synthesisComputer animation
Electric currentThread (computing)CodeSoftware frameworkDependent and independent variablesContext awarenessWeb pageGUI widgetRead-only memoryOverhead (computing)Socket-SchnittstelleOperations researchSemiconductor memoryWeightType theoryBitCodeElement (mathematics)Internet service providerBoolean algebraState of matterThread (computing)Default (computer science)Tracing (software)Web pageForm (programming)Dependent and independent variablesLevel (video gaming)View (database)Set (mathematics)Web 2.0Universe (mathematics)Software framework2 (number)Information overloadPhysical systemConnectivity (graph theory)Musical ensembleContext awareness1 (number)Asynchronous Transfer ModeServer (computing)FreewareWeb serviceService PackGame controllerObject (grammar)InternetworkingObject-relational mappingMultiplication signHierarchyCompact spaceException handlingOverhead (computing)DatabaseSoftware bugDirection (geometry)Application service providerVisualization (computer graphics)Structural loadRaw image format.NET FrameworkTemplate (C++)Operator (mathematics)TwitterSheaf (mathematics)Group actionNetwork socketError messageSocket-SchnittstelleCausalitySoftwareMobile appCondition numberSoftware testingRight angleResultantInternational Date LineStack (abstract data type)Reading (process)Boss CorporationEmailGoodness of fitSubsetControl flowEvent horizonStatement (computer science)PseudonymizationWebsiteArithmetic meanOracleArmDirected graphSequelMetropolitan area networkSystem callMaizePlastikkartePoint (geometry)Subject indexingSingle-precision floating-point formatComputer animation
Computer animationXMLUML
Transcript: English(auto-generated)
Turn me on on you can hear me now. Okay. I'm just waiting for my as you can see welcome I'm just waiting for my machine to boot up I just finished another talk and my machine decided to have a bit of a rest in between as I walked over here
So I'm trying to get started up again We're gonna talk about some interesting stuff today I've given this talk a couple of times already It's really designed around. Well. I'm probably gonna hurt some people's feelings in this talk This is advice from the ASP.NET team based on things that we've seen people do in the wild
Given that ASP.NET is a fairly old framework now. It's over 10 years old. There's a fair bit of legacy There's some security things that are interesting to talk about that, you know have been fixed along the way But some people may not be know know about them and are doing things incorrectly And there are some API's that we kind of wish that we'd never invented or they serve their purpose and now we don't want you
To use them anymore, and so I'm going to tell you about those So for every one of the ones I tell you not to do I will give you an alternative of what you should do instead But as I said, I'm pretty much guaranteed to offend at least one person in this room We thought I'm about to tell people not to do and if I'm really good
I'll freak someone out enough that they call back to work and ask them to pull down their website immediately Because they're doing something that's completely insecure We'll get there. Come on, come on laptop. Who watched who was in my last session with David? Okay, there is no coding in this session. All right, this is all me
Talking about API's and what not to use and what to do There is a PowerPoint and I link off to some examples and things but there is no coding in this demo I'm coded out today Come on, come on, come on How many people here have been using ASP.NET for two years or more? Okay, three years or more keep your hand up four years or more five years or more six years or more
Seven years or more the stay is eight years or more Dropping off now nine years or more What we back to that's out of 2004 ten years or more eleven years or more
Came out in 2002 by the way So this is where it stops unless you use the beta twelve years or more Thirteen years or more first beta who use ASP classic Okay, a lot of people. Okay. Hey, here we go. It's up. Yeah, that filled in the time beautifully Plug this in and
Demo gods willing this will just work this time Do do do I want that one and just for good measure I'm gonna paste it out to the desktop I'll come on. Come on
Yeah There we go, I Was checking you. Okay. No do not start in safe mode. Just start. Yeah, we go. Whoo
Alright, and I last time I gave this talk. There were a lot of Scott's on stage Scott hack the little-known Scott hag This time it's just me Okay. All right ASP.NET don't do that. Please do this instead. So
Absolutely obligatory disclaimer written by the security guy on our team that we never question about anything He says about security This is not intended to be like the complete guide where if you follow everything in this guide in this presentation Then that's it. You're golden. We're signing off on your application ship it. You're never gonna have any problems
This is not that of course This is stuff that we would like to bring your attention based on previous guidance that we've given you and perhaps we're changing our guidance It's only intended to call out the most common incorrect or Undesirable uses that we encounter when we look at people's applications people file bugs. They send up repros and we go Oh, you're doing that. Please don't do that
And so this is a collection of those things. Okay So we've broken the talk into sections The first one is around standards compliance and we're talking about HTML standards compliance JavaScript CSS that type of thing first Okay, so control adapters whoever use control adapters in web forms, there's a lot of web form stuff in here believe it or not
Yes control adapter. So control adapters were originally designed to support mobile controls we had this fantastic feature in ASP.NET 2 About mobile controls you drag a text box a mobile text box onto the page and it would render different HTML or WML or
XHTML or XML depending on what the device was and it did that using our Braille browser Capability system and these things called control adapters now The one control could adaptively in a pluggable fashion change what it renders at runtime We don't want to support it anymore. So please don't use it. Okay, it's an old technology
We deprecated the mobile controls themselves, but a lot of people are still using control adapters So we would prefer that you do this using CSS render standards compliant HTML either using a control that you wrote or one of the ones in the box or just Basic HTML and then you CSS media queries responsive design all that good stuff To do the mobile specific logic in your application who is doing the stuff on the right today?
Responsive design media queries great. Perfect. Who has ever used the stuff on the left to do mobile websites anyone? Okay, good that served its purpose before we had CSS there was a time We it was or with devices that didn't support CSS you had to do this now
We just sort of assume that everyone has a smartphone or at least a phone with a browser That supports some level of HTML CSS. So don't use them anymore if you can avoid it. Okay style properties on controls So this is code behind text box dot style sir, I think dot Edit item template alternate item font for color opacity level
There are hundreds and hundreds of these properties on the web forms controls and I hate them You're in your markup and you're doing grid view colon blah blah blah And then you hit E and you get a list of IntelliSense with a hundred items in it That's just full of this garbage. Okay, you shouldn't be setting your CSS in line on your HTML
Anyway, we all know that you should be attaching it By CSS now, I would love to in a future version of ASP.NET and webforms Literally delete all of these properties just get rid of the style collection class and get rid of the styles property and force people to Use CSS to do it the right way quote unquote So please if you are using this today very common if you're doing things like data binding
You're handling the on item data bound event and you go in you navigate through the cells Look at the value if it's less than zero Then you say Oh current cell dot style dot for color equals color dot red Okay, don't do that do current cell dot for dot CSS class
equals string Negative then add a CSS style sheet with a classical negative has a semantic name and set the for color of the font That way much more maintainable You don't have colors and all types of style crap and better than you see sharp And you know, we will be able to clean up this IntelliSense in the future for you as a result But please don't use style properties page and control callbacks isn't introduced in dotnet to
This is the thing that lets the grid view do paging and sorting without having to do a full page request This is not update panels. That was different anyone used page or control callbacks. Okay, also known as page methods You could have a static method on your page and then you can invoke it using Ajax. Okay, kind of nice
ish Just don't use them we have better ways of doing this now and These cause some issues with some of the newest stuff like friendly URLs the stuff we added in web forms this year That gives you this extension list URLs for web forms doesn't work Well with this routing does not work well with this
So if you want the modern URLs the ability to control your URLs using routes And have them separate to your pages and your controls and whatnot. It doesn't work well with page callbacks and controls for callbacks So just use anything else anything but that okay Update panel is fine. Update panel is an amazing piece of technology. It really is. I've seen the patent. Okay, it's patented
It's really cool Just don't abuse it okay know how it works understand what's going on and then use it for the portion of the page that you want to use It for and just be mindful of it and test it You know performance test and whatnot or just use Ajax MVC action methods web API SignalR whatever it is you want to do to get that
Ajaxy type non full page refresh back But try and avoid page and control callbacks if you're using the grid view or a control that itself uses control callbacks Just turn that feature off or don't enable it in the first place. None of the controls will use it by default You have to turn it on In order for it to work. So just don't turn it on
Okay capability detection. So we have this feature in ASP.NET called browser caps or browser capabilities Which is this massive XML database that's installed on the server that says hey this browser with this user agent string is IE whatever or Firefox whatever and it supports Active X cookies this type of image format. It has this wider screen blah blah blah blah. Okay, and there are third-party vendors who sell
expanded versions of these Databases for mobile devices and things and people have used this for a long time the mobile controls that I talked about before They use this but we generally now know that doing browser detection or capability detection from a static reference is
Generally frowned upon. Okay. We don't like doing that anymore. We don't do user agent sniffing We don't test for one thing and then assume that something else will be there because that thing was there We know that's bad, right? So we should be doing feature detection So we should be lighting up our features in the client Where we can test for those features in real time using JavaScript or clever CSS tricks
Oh I know that this browser supports ping images because I tried to write some code that Should result in this element appearing and it didn't or now I know it didn't support ping images But you get the idea So we have tools like modernize a great library from a couple of guys guy at Google a guy to a few other guys
You pop Paul Irish a couple other guys we ship it in our templates. It's a client-side library that helps you determine What are the capabilities of the current browser but it does it using feature detection not By some big static list of features that it understands. Okay, so please use feature detection and not capability detection
Okay, so that's everything about standards compliance. I'll stop ranting about that now and we'll talk about Security This is where it gets a bit scary Okay, so request validation who knows what request validation is an ASP. NET It's that really annoying thing that gets in the way when you try and post back anything that looks like HTML
Yes, you turn it off, which is what most people end up doing Which is bad because it means that we probably didn't design the feature very well So the idea behind request validation was that hey Let's not have the developer have to worry about cleansing all the input coming in from the browser
On the odd chance that they may echo that input back out To the browser or they may inject that input into a SQL string. Okay, we'll detect detect any Malicious type of content. Oh, there's an angle bracket. Oh, there's a question mark after or whatever
Shut down the request before your handler even gets assigned So it's a module that runs really really early in the HTTP pipeline and ASP.NET It inspects the request so it looks at the form body It looks at the query string and it looks at the request path and it sees anything It doesn't like it just kills the request on the spot and you get that yellow screen of death Hey and a potentially dangerous
Token was found in the blah blah blah blah blah blah and you go. Ah, damn it You turn it off. You never use it again Now we did add features in version 4.0 that let you do it more granularly So in MVC, for instance, you could say I just want this text box in MVC To not go through a request validation, but let the rest of the page go through a request validation. So that was nice
Okay, you could turn it on for the whole page But does not have it on for this control and I'm sorry to say we actually did the work in ASP.NET 4.5 To support that same thing in web forms and then we decided that we didn't want people to use it anymore After we did all the work So we do not want you to depend on request validation There's a reason is that because request validation is a game of whack-a-mole
We find or we get reported a vulnerability where browser foo version X Doesn't like it if you send in a request with a form body with this seven character string escaped with Unicode 7 or something crazy That gets through request validation. So now we have to patch request validation send it out to the world
That's a really expensive effort and we just can't win because this stuff changes all the time There are new browsers every week new versions that introduce new vulnerabilities And we can't keep request validation up-to-date. And in any way it's a bad idea. It actually encourages bad practice We're giving you a crutch that you shouldn't be relying on. So what should you do instead?
Who knows what you should be doing instead? Come on, I have nothing to give you but I'll be impressed if someone can give me the answer. What's the answer? No one knows, okay, so Encoding is one half of it. Well done, sir. You need to encourage your output Whether it's going into SQL or a parameter or going into the HTML via HTML encoding and you need to
Validate your input. Okay, if you're expecting a URL From as the is the input from some text box that user has typed into Validated as a URL don't use regex for God's sake don't use regex We have types in dot nets one of the nice things about dot nets is big library of useful features
And then we have like a type like system dot URI Which you can pass the string into and it will tell you whether it's validation You P what sorry a valid URL or not, and it's it is written to the spec So if it says it's an HTML URL, it's a new URL. It says it isn't it isn't okay You don't have to do that
So validate the import on the way in if it should be a number make sure it's a number if it should be a String without certain characters write a parser. Maybe you could use regex in that case. There should be an email What's the best way to validate email? Send an email to the address and wait for a reply And I am not kidding It is the best way and really the only way you will ever truly guarantee that the email address that someone is written in
Is a valid email it may look like a valid email But it's not valid unless they can get email on it. And if you've read the email spec Including supporting international characters in your email, which all modern clients do modern mail servers Do I can type an email address that contains a domain which contains a Unicode extended character pairs?
So Chinese, they're kanji and hieroglyphics and all types of wonder wingings, whatever I want, right? Emoji characters I could have an email totally made of emoji. Does your regex support emoji email? I'd pretty much guarantee not. All right, so all you should really do is go it's an email
Okay I know it has to have an at sign in there somewhere and it can't be the first character and it can't be the Last character. So check for that. Okay, that's fine Although technically you could escape the at sign. So anyway, you can do that and then once you get the string Send an email to it. Okay, and then just say to them. Hey, yeah, we got your email address. That's great
Sometime in the future. You'll get an email. Please reply to it and then we'll activate your account Whatever it is that you're doing with that email. Okay, and then on the way out Always encode your data. So if you're in razer good news, it does it for you by default All right, you just do at foo where foo is some variable a string or an int or some user provided data Something you got from a database that your business users might have had access to you need to protect against that as well
Then just do at foo. It'll automatically HTML encode it for you. There is no way they can get bad data into the page that sort of it would result in a Cross-site scripting vulnerability in your page if using ASP X in version 4 of dotnet we introduced
Angle bracket percent or bumblebee as we call it colon So angle bracket percent equals should never ever ever ever ever be used anymore. Just don't use it Okay, you can't do it in razer There's no way to say don't encode it the way you say don't encode it is to give it a variable of type I HTML string Okay, then it will go. Oh, it's I know it's HTML already. I don't need to encode it
Okay, you have explicitly stated that this is not a string. It's an HTML string So don't use and colon supports the same thing. Just don't use equals anywhere Okay, who currently knows that they have angle bracket percent equals in their site Okay, that's the first thing you're gonna do when you get back. Okay seriously
And if you're using a data binding in web forms And you're using angle bracket percent pound or hash and then like bind or eval in dot net for five We added hash Colon which does the same thing it performs the data binding expression gets the value and then encodes it automatically for you If you're not using dot net for five, I'm sorry
You'll have to order you'll have to manually call HTML We have HTML with a server utility dot HTML dot HTML in code and then pass in the result of the binding expression If you're using two-way data binding the bind angle bracket percent colon Angle bracket percent hash bind who's using that anyone using that in web forms Okay, there is no way to encode that unless you're in a ship in a spin at four five
okay, so Upgrade to four five and change that to hash colon bind then you're safe, okay Excellent. Ah, yes, cuz that's required for four five it is. Yes Otherwise, you have to actually encode the values that you're binding to so the thing you're binding to has to already have been encoded
Okay, that's the way you'd have to do it and don't forget about JavaScript If you're emitting stuff from server code into a script block or into a CSS attribute into style equals You have to do different encoding. They're different languages You can't HTML encode in there and we have methods for those JavaScript string encodes CSS encode URL encode if you're emitting a string
Into an H ref attribute. That's not HTML anymore. It's an it's a URL again you have to correctly encode the value to ensure that people aren't trying to pass values in through a URL which people do it's how you get cross-site scripting in your site. It's a really really nasty bug to have All right cookie list forms auth and session
Another brilliant feature of ASP.NET since 1.0 Who's using who who knows what cookie list forms auth and session is? Okay, who's using it? Great, don't do anything. It's fine. Who has used it in the past anyone? Okay, good So in the end, basically it was designed in the early days when a lot of browsers didn't support cookies
We cared about browsers that didn't support cookies and we wanted to use forms auth and session But you know what? It just don't use it. It's insecure. Okay, you should never be passing around this stuff in the URL Which is what cookie list does it appends it to the URL? It's just a really really bad idea. So enable require cookies for these features. There's actually a flag that says require cookies
Okay, so you can turn that on to ensure that you'll never accidentally support a browser that turns up with cookies turned off and then you'll start passing around tokens that are potential security vulnerability and Consider using only SSL cookies for site serving sense of information so that means if you're writing a cookie or using forms off then if that cookie contains sensitive info like a
authentication ticket You should only be sending it over SSL and the cookie should be marked as only being able to be sent over SSL There's actually a secure flag on a cookie and the browser will not send it unless it's an HTTPS connection
And that's all configurable in ASP.NET whether you create the cookie yourself in code behind There's a flag on the cookie is secure set it to true or if you're using forms off or session You can set that flag as well in the configuration Enable view state Mac. Oh boy. This one's a good one. Who knows what this is enable view state Mac
Okay, everyone knows what view state is right the thing we love to hate So view state Mac is the thing that ensures that the view state that was posted when you do a form post is valid It's it ensures that the view state came from the server originally, okay
Because if you think about what's in view state what's in view state its state to do with the controls that were rendered okay, or it's stuff that you put in there manually and Whatever is in that state affects what the controls do it may rehydrate a bunch of properties that you would set after page load or It may trigger an event and then call into your code
So you really want to make sure that when someone does a post to your website To an ASP X page that the view state payload that comes up, which is a base 64 Bunch of characters we undecode it and then basically we deserialize it into binary types And then we run code you should already be worried at this point
You need to make sure that that's a valid piece of view state that only came from your server You need to ensure that it hasn't been tampered with Someone hasn't tried to manipulate the view state in such a way that they can make your code do something You didn't want it to do So do not ever ever ever turn this off We should never have let you turn this off Has anyone here ever turned this off?
This is a setting in the page or in web.config enable view state Mac equals false. Has anyone ever done it? Will anyone ever admit to doing it now that I've said that? But I'm not using view state is not a valid excuse Unfortunately, we called the property enable views view state Mac But then we used it to enable other things that don't do with view state
like control state and Event validation and all the other things that web form sticks in hidden variables and then use this to sort of rebuild the page When you post back, okay It's incredibly important that you never ever turn this off and in a future version of dotnet We will remove the support for this if you set this to false. We'll just blow your application up. It is incredibly dangerous
There's actually published vulnerabilities About this thing. Yeah, so just tease us forever allowing it. So here is a public vulnerability I Get the hyperlink. Where's the hyperlink? Ah, give me the hyperlink
it's You know what? It's formatted as a hyperlink Seriously PowerPoint that was a hyperlink last time I did this There is actually a public Public public known vulnerability if you turn this if you turn this off which it is not by default
Of course, it is on by default meaning is secure But if you turn it off in your app, there are public publicly reported vulnerabilities that you could Be susceptible to that will enable cross-site scripting in your app means I can make a malicious request to a page Where this is turned off I can manipulate the view state because it's not encrypted and it's not verified
it's not signed with a Mac H Mac and then I can Tell your site to do something that you didn't intend it to do get it to render stuff into a page For another user that makes it run my JavaScript for instance really really bad stuff Medium trust who uses medium trust in ASP.NET really everyone's running full trust
Really who doesn't know what medium trust is? Okay, so dotnet Supports a partial trust system the idea of having your application code run inside an app domain that is restricted Okay, it we've actually locked down what API's are available for you to call and we protect in the same process
So w3 WP dot XE two applications running in the same process Okay, but in different app domains that are set to medium trust in theory It prevents those two applications from accessing each other's state or calling into each other doing bad things Calling into each other's memory in theory turns out that didn't work out so well
Okay, we publicly announced last year we changed our guidance Please do not use medium trust. Okay, it is not a security boundary Or any other trust level, okay You should just be running full trust because the trust level system in ASP.NET is no longer a security boundary
it was for ten years and then we found out it wasn't and there's no way to fix it and so We just tell you not to use it So, how should you do isolation then if you have a situation where you have to applicant if you're a web hosting company You have two applications running on the same server in IS and you need to protect one application from the other
Okay, I mean it's pretty important right if I'm Multi-tenanting if I have Fowler's app and my app running on the same server and we have nothing to do with each other I need to ensure that I can't like scan the world as soon as you're deployed to a shared host and like start reading Secrets from other people's applications like their database connection strings and stuff, right? So what should you do? How do you protect against this?
Application pools process level isolation. It's the only guaranteed Security boundary in Windows essentially Windows is built around process isolation Okay, and so is dotnet it turns out so place all untrusted applications into their own app pools
Because the application pool is the unit that then results in the actual process running So if you're going to task explorer, you'll see w3 WP dot XE. That's the process that maps to an application pool Okay, the app runs inside that Okay
Okay, we should get you should introduce him to my guy run Run each application pool under its own unique identity very important. Okay, so by default from is7 and above Automatically every application pool runs in its own identity. We have those strange app pool identities Which confused everybody when we released IS servers like oh used to be network service
Which just worked and now it's this Apple thing and like nothing works anymore, right? So everyone just change it back to network service, which is fine if everything on the server Runs at the same trust level, but if you're trying to do multi-tenanting every Apple has to be running as a separate User account, right? It's the only way you're gonna restrict access to each other
And since Windows Vista and above Windows is that that really cool process isolation one process cannot call into another process at all Unless they have a pre-agreed token blah blah blah blah stuff. I don't understand and so Follow the guidance. There's a great link there knowledge base article two six nine eight nine eight one Will we basically admit? That we're changing our guidance and don't use medium trust and we show you how to set up this
If using is7 and above we have this special application pool thing that will just create basically it creates a user account on the fly As the Apple starts and you can use that user account to set ACLs and give you a database access and all Stuff as well. Okay, if you're running in a domain then generally you'll create domain accounts Anyway, and you'll run your app pools using a domain account Okay
If you're a hosting company Please don't use medium trust if you're using a hosting company and they still run in medium trust Move to a different hosting company now talk to them Please get them to read this knowledge base article and then get them to move off medium trust or send them to me And we'll talk to them. Okay Okay app settings Great feature dotnet 2
So there are a whole bunch of settings Now you can set in app settings. These app settings is the string based one not the strongly typed one, right? Magic string key magic string value magic happens, right? Turns out we it's not just there for you
We have a whole bunch of magic strings that we know about that if you put in app settings, we change ASP.net And you'll be going well, why isn't it just first level config? Why did you put in app settings? Why don't you just add a new element in the configuration schema to let me do this bell A lot of the times when we do a security fix and we send out a patch We'll add a back door that lets you turn the patch off
We have to because a lot of these security fixes break applications compatibility And we have to give you a way to roll out the patch but have it turned off So that while you're rolling up the patch say in a web farm Well, you can't roll out the patch like at once to 20 servers You can only do it one at a time You have to be able to in your application turn the patch off before it even exists
So we can't add schema because that's strongly typed. It has to be a magic string So we give you the switch to turn it off. You set that in your app. You redeploy your app Okay, then you go through and you read up and you deploy the fix to every server And then once that's done, you just redeploy the app with the switch removed and now you're secure Okay
That's the only time you should ever use these settings these app settings to turn off these fixes The only time you should ever use it and there's a link hope this one works They are documented We did the work of documenting every single app setting last year Because there was a lot and we added more in dotnet four five. Come on Network. It's a really good list
Really okay cool. So this documents all the magic keys That asp.net itself supports to turn things on and off now
Some of these are marked as you know important this setting should only be modified by advanced developers Which of course everyone goes why I'm advanced. I found the documentation. I must be advanced right? I even knew it existed Some of them are marked a little bit more forcefully like this
Setting this attribute to true can pose a security risk allow relaxed HTTP username So here's an example of someone reported a vulnerability We issued a patch that patch would break certain applications that were essentially taking the pendency on this vulnerability And so we needed to give you a way to turn that patch off Without you only want to install it obviously and so we say please do not set this
Okay, it could pose a security risk and they're all documented and I will admit there's quite a lot of them Okay, it's an old asp.net's been it's a it's a mature product 13 years as we determined before okay So be careful You're all passing code who can tell me what this method does
It's a trick question. No one can tell me what this method does Because the method shouldn't exist But people use it because they think it encodes URL paths. I don't know where they got that idea oh Wait, I see what we did there. Yeah, yeah, don't do it, please
This method was intended to solve one problem, and it was to solve a problem in Netscape to handling UNC links We should have called it make links safe for Netscape to href attribute But we didn't we called it URL path and code and so people thought that they could use it to encode query string values or
Segments of a URL and that it would be safe and protect you from cross-site scripting it doesn't So do not use it do what we talked about before sanitize your inputs instead Check make sure that anything that's submitted as a URL is an actual URL by using the URI class It's what it's for and then use URL encode which is the method that
Okay, URL encode is the right one to use So if you need to take a value and put it in the query string of a link you're generating a hyperlink And you need to put a value into a query string use URL encode not URL path encode Okay, that's safe to put into a query string Okay
Do not use your own path and code. We will probably delete this method in a future release of dotnet Okay, or make it throw or something equally heinous Okay, enable vstate Mac. We really really meant it Do not turn this off if you take anything if you're a consultant and you deal with customers who use ASP.NET
Check this every single application that you ever lay your eyes on ensure that they are not setting this to false you know, we should do we should search github and see if there are any web.config files that have this set to off and Then send them a polite email or a mail. He can't message through github. Can you?
Send a pull request that fixes it. That's a great idea We really mean it see it windows update while windows update that changes people's code they'd love that Wait that config file wasn't like that before patch Tuesday and we That would be really cool. All right, we really mean it. Okay a crappy clip either side. We really mean it
All right, do not turn that off. Okay reliability performance. So we've done What do we do? We get standards compliance and we've done security. So that's all the security stuff Okay Have I scared anyone enough yet that they're gonna go back and change their code when they get back to their workplace Come on, it's gonna be worth my time. I see some nods No one's putting their hands up, but people are nodding so or moving their eyes up and down or like looking away like this
Or looking like this for the other people who have done it so good I got through to some people. Okay reliability and performance There is these two events pre send request headers and pre send request content anyone using these they're pretty rare Okay, someone put their hand up. Okay
Try to avoid them Registering for these events from within within manage I should be module So if you're using from a native module, that's okay is native module Okay, if you're using from a dotnet ASP net I should be module that they have issues. Okay, so use the native ones instead. I Don't know what the issues are
My runtime guy said don't actually give me notes. No, he didn't give me notes such a shame But don't use them they cause issues with asynchronous requests Doing overlapping things and like sending headers at the wrong time in the pipeline after headers have already been sent It's possible to do it using the managed API the native API just solves all that for you. So don't use them
Even if you're not using directly you may be using a component that you bought or downloaded that is So anyone here ever used a large file upload component phrase p.net Anyone no one a couple of people hands, okay A lot of those use these events in the past Okay, because they want to do stuff just before they send a request back or as the request is coming in. So
Okay, async page events So this is in web forms To do with the task based asynchrony that we added in dotnet 4 5 which I spoke about here last year I think or the year before Try to avoid writing async void methods so you can do
Protected void Protected async void page underscore load and then write a weight code inside your page load And that does work Okay work for the simplest of scenarios But what we want you to do really and same for like button click handlers
You can do like a protected void async void my button underscore on click You know some async code and that kind of works ish in the really simple demo cases It works as soon as you do anything more complicated. You can introduce race conditions in your code So what you should be using is the first class API for telling the page that there is going to be async work and that is
Page dot register async task, which has been around since dotnet 2, okay It's been there forever, but we updated it in 4 5 to support task returning delegates asynchronous lambdas Okay You should be using that what that does is it cues up the async work
When you call it from page in it page load a button click handler Whatever it is, and then once you get to pre-render complete Then it runs the async work in a coordinated fashion and because that method that you register with that method You have to give it a delegate That must return a task. We have an object that will tell us when that async work is finished Async void we have no way of knowing when that async work is truly finished
We can kind of track it using the synchronization context Because it raises an event when async work starts and then when it finishes But if async work kicks off more async work that kicks off more async work then that can just all fall over okay, but if you use register async task, it just works and
Do make sure that you set HTTP runtime target framework equal to 4 5 if you're doing any type of task Asynchrony in web forms or in MVC or web API or signaler Okay If you're running on 4 5 make sure you set target framework equals 4 5 that flips in the new Asynchronization context that we added in .NET 4 5 it's opt-in
We don't do it by default because it changes behavior of async work Okay, so you need to turn that on if you're doing anything with tasks In ASP.NET if you do file a new project in Visual Studio 2012, it's turned on for you by default, okay Fire and forget work Try and avoid
Having code in ASP.NET where you handle a request So in an MVC action method or in a web forms page load or an Ajax or handler or something Try and avoid kicking off fire and forget work thread pool queues a work item Starting a timer that calls a delegate every so many seconds from within ASP.NET The reason is at any point in time. We may decide just to completely destroy the app domain
While that Async work is running. We generally won't do it while a request is running But if you fire off fire and forget work by definition the request will be over very shortly afterwards And that work will keep going right because it's fire and forget you don't care about it So if you do that
We can just tear down the app domain and you'll get all types of strange exceptions in your background work And you may even we may even corrupt your state and that can lead to really bad things Maybe you were writing stuff to a database in such a way or a text file now We've corrupted your text file. Okay, because we just literally crashed your thread If you want to do background work in ASP.NET
first of all don't Move it to a different process Write a Windows service or if you're an Azure user worker role Queue it and then have some other process pick it up where you manage lifetime yourself If you absolutely must do it inside ASP.NET you can check out web backgrounder. It's a new get package that Phil hack wrote that Let's use scheduled background work in ASP.NET
Now work that happens on a background thread inside the ASP.NET app domain But it listens for the correct events And so when the app domain gets torn down we give it a chance to finish the work Gracefully before we destroy the world underneath it okay, so look at web backgrounder if you need to do that type of work rather than just starting time as in app start or
Doing thread pull.q as a work item. Okay use web backgrounder. Okay, the request Entity body try to avoid reading request.form input stream before the handler This is a pretty advanced stuff So if you're writing a handler and you want to be able to get the actual network stream
That represents the request coming in from the client because you want to you know Do large file upload you want to inspect the stream as it comes in to do whatever it is Log it out or something like that You shouldn't really do that before handler execute Okay, you don't want to do that Or request.form but for that matter
You really want to try and defer it to when handlers execute Yeah, handler execute is the event where your action method and MVC runs or your page In web forms runs like page init will fire. Okay, that's the handler That's the handler page or the MVC controller is the handler and handler execute will execute those things if you read
request.form or input stream before that Either from a module that's generally where you'll do it from from a module then you can cause issues What you want to do instead is use these APIs here getBuffaloos input stream and getBuffaloos input stream So getBuffaloos input stream was added in 4.0 And getBuffaloos input stream was added in 4.5 and they do what they say a buffaloos input stream
Gives you the raw stream from the request which you call before handler execute But be warned if you call this API you're telling ASP.net. I am taking over this request completely I don't care what was going to run after me
I am in charge of this request from now on and I'm gonna read from the stream manually Which means things like request.form won't work because they usually get populated by ASP.net by reading the stream But if you start reading the stream Buffaloos input stream then you read the stream you read the bytes into your own variable Which means no one else can read them. It's a stream right once you read them. You can't look at them again
It's not a buffered stream by default. It's literally a network stream So if you call this method you can't call request.form you can't call request.files Because that won't work. If you call getBuffered input stream you can GetBuffered input stream will give you the bytes as they come up
But it will also buffer them away into memory or spool them to disk So that if later on in the request lifecycle you do call request.form It'll still work because we took a copy of it before we gave it to you. Okay, so low-level APIs But we've seen issues reported Where people had called these events and then they kept called server crashes and types of things because they're doing things in the wrong order
Well, they're doing things after certain things have happened and things like that Anyone actually using these anyone actually used done input stream processing in ASP.net Okay, so that all fell on deaf ears nevermind If you ever need to do it check out those, okay Response.redirecting. This is more of a be aware rather than a don't do this or do something else
If you call the overload of response.redirect, which just takes a string that cancels the request So when you call response.redirect.string The next line of code after that doesn't run Because we call response.end which throws a thread abort
Exception synchronously inside your code and literally tears your function call your stack in half Okay, you were calling this function you were this point in the in the call You called response.redirect and then we just cancel the thread by calling thread abort so we can return it Okay Which may or may not cause really odd things to happen in your application depending on what you were doing
Okay, if you'd set up certain types of state memory, and then we just kill it on the fly For asynchronous handlers response.end does not abort it But code execution continues so the behavior differs whether you're doing async programming or not in async programming We change the behavior when you call response.redirect, sorry when you call response.end in async programming. It doesn't actually end
We let the rest of the requests run through and then we let it finish So basically don't recall response.end from an async handlers. Okay to end an async response. You have to return the task That you returned originally from the async method that we showed in the signal I taught just before
That's when the request will end only when that task finishes Or if you're using the old pattern when the end method when you call the callback that was passed into before into begin Sorry, so response.end doesn't do anything in async If you want to redirect the response, you should be using the appropriate method given to you by the framework
You're using now if you're using web forms response.redirect is fine, but you just need to be aware of what's going on Okay, there is an overload of response.redirect that takes a boolean which you can say redirect But don't thread abort, right redirect after you've finished executing the page, right? in MVC
You'd return a redirect result. Do not call response.redirect from inside your action method That is absolutely the wrong thing to do. Okay, you need to return a redirect result from your action method and then the MVC pipeline will see that at the appropriate time in the lifetime of the request and then Send it back. Now remember this section is about performance and reliability. We're not saying
That this is going to cause issues immediately, but it does make your app less reliable It may cause issues under load Doing some of these things introduces certain race conditions or possible memory corruption or stack corruption problems that you may not see Until you get lots and lots of load or you may see one in a million requests
Okay, but they can be the hardest bugs to track down I'm sure you all have experiences of looking the event log and seeing obscure error from ASP.NET and you have no idea Why it was there and you never saw it again or you see it once every week You don't know why it's there. Okay, a lot of the time it's these type of things and you may not be doing it you might be using some code a Component that you bought or something you downloaded from the internet that's doing it and you don't realize it. Okay
Enable view state and view state mode so Try to avoid enable view state. Enable view state has always been there. Okay, it's how you turn off view state It's on every control in the hierarchy in web forms, but when you turn it off There's no way to turn it on again underneath that control
If you turn it off at the page, it's off. You can't turn it on for one control Okay, but view state mode which we introduced in .NET 4 lets you do granular view state control You can set view state off at the page level which we thoroughly recommend by the way Just turn view state off by default set view state mode equals to disabled at the page directive level at page
View state mode equals disabled that will set view state off for the page Then on the controls that your testing has determined need view state to work Turn it back on just for that control That will save you an awful lot of view state that you otherwise would be taking up Which is one of the biggest bug bears that people have with web forms
It's really easy to fix in .NET 4 just turn it off and then turn it on for the controls that need it You'll see your view state shrink dramatically Is anyone anyone doing this already people know about this already? No one person to be good Okay, SQL membership provider, this is the inbox provider that we shipped
You know forever for doing membership support in .NET in ASP.NET using SQL Server We replaced this with an out-of-band component called the universal providers system.web.providers There's a NuGet package It's used by default in the templates since I think Visual Studio 2010 Service Pack 1 and it's in all the templates in Visual Studio 2012
And it works with all databases that Entity Framework supports because it uses EF It doesn't talk to SQL directly. It uses EF So it'll work with SQL, Azure SQL, SQL Compact and if you have and the Oracle Entity Framework provider or the MySQL Entity Framework provider It'll work with those as well. Okay, so Just be mindful of that if you're still using SQL membership provider The other thing is that you know, we made some improvements the universal providers have they're better
If you're still using SQL Server, these ones are better. They don't use stored procs. They're a bit more flexible. They're faster They're better written and they we can update them out of band. They're not in the framework. They're on NuGet So they're easier for us to improve as we go forward and if you're deploying to Azure, you really need to use these ones, okay
Long running requests That is requests that run longer than 110 seconds now really Any request that runs longer than a couple of seconds seconds is by definition a long running request I mean request generally should be over very very quickly, right? I mean, that's what we want our things to do be quick as possible. That's how HTTP was designed to work
But some interesting things happen When you let your request run over 110 seconds now by default, that's the request timeout setting So depending on what framework you're using whether you're running a raw handler or webforms or MVC We may or may not just destroy the request and give you an exception request timeout exception But things like the session object, so who's using session state in ASP.NET
Hey begrudgingly Okay Okay, so session state in ASP.NET is not my favorite feature and I own ASP.NET as a feature wise so I don't like it Okay Long running requests ASP.NET takes a lock on the session object
So when two requests from the same user come in at the same time Perhaps because your page makes two AJAX requests or while the page is still loading they hit a button which makes an AJAX request We block the second request while the first one is still active because we've locked the session object for that user Okay, a lot of people have run into this when trying to do long polling in ASP.NET in the past
but after 110 seconds, we release the lock and Maybe that's a bad time Maybe you were in the middle of doing some session work and now suddenly we release the lock and all hell breaks loose Right your session stuff that you were saving doesn't get saved or the read that was going on suddenly happens when it should have been blocked
So don't do it Okay Don't try and have long-running requests that are greater than 110 seconds that use session state and just try not to use session state If you can avoid it Also don't perform blocking IO operations So I think everyone's aware of what a blocking IO operation is now after two years of node being on the scene and we've talked about Async a lot in the last two years
We now have async APIs for all of the type of IO that you would want to do in dotnet whether it's file Network web service socket or Database as of EF6, ADO.NET already supported it but EF6 supports it at the ORM level So you can do asynchronous OI now from webforms or from MVC or web web API signaler and free up that thread
Okay So for long-running operations though in general You're better off to use web sockets if you can or signaler Okay, just inject signaler anywhere web sockets is said As it has a much lower per request overhead. So the other thing a long-running request will do is use memory
Okay, even if it's async an async request that's long-running won't use a thread when it's idle But it still uses memory I mean, there's still data stored in memory that represents that request But a web socket request in ASP.NET special API introduced in dotnet 4.5 is a much lower
Per-request memory overhead when you call accept web socket request and you give us the delegate we unwind the request Free up most of the memory to do with that request and then we invoke your delegate With a restricted context not the full HTTP context just a small set so that we free up a lot of memory It's about five times less
Okay, then a full request now signaler just does the right thing view signaler We use web sockets when we can Otherwise we use long polling or forever frame or service in advance and it's async So we just try and do the best thing we can and That is the end of my talk with other people that I didn't do the talk with. That's my boss cool school His name is Carl Scott hunter cool theater and you all know Scott Hansen
Okay, so, um, I have two minutes if anyone has any questions I can answer them right now on stage or ping me on Twitter and I'll do my best to answer them Otherwise, thanks for coming along Any questions while I before I pack up nope
Okay, awesome