.NET DECK Flashcards
Four phases of web application attacks
Recon, Mapping, Discovery, Expoit
Most attacks are ________ specific to .NET; they are found in….
NOT specific to .NET, and don’t need any knowledge of it to exploit it. Found generically in HTTP, AJAX, JS, XML, SQL.
Four main things that can be attacked on a page
Verbs. (Using Gets vs. Posts, etc)
URL
Headers (User agents, referrers, cookies)
Content in the page (Page forms, JS, CSS, etc)
Places where data validation needs to happen
Between every layer of the model. From application to middleware to back end DB, and from DB back to the application.
Should be parameterized and encoded, validated w/whitelists.
Before performing data validation, it’s important to identify every _________ in your system diagram/threat model.
trust boundary
How should validation be performed?
- At every layer/tier.
- By senior, experienced developers
- Consistently, simply, and in a way that it can be audited.
What are some validation techniques?
Indirect Selection (moving a string variable to an integer, etc) Blacklists Whitelists (better) Parse CMD Regex
A WAF is a big, shiny, _________.
blacklist. It blocks known bad characters. (better than nothing)
Whitelists
Validation construct that allows only known good, established chars. Better than blacklists.
Indirect Selection
Change input adding fields to drop downs, associate strings as integers so they can be parsed and don’t allow free form, don’t directly access objects.
By storing a string with a number representation, it means that validation just needs to be an integer check.
Validation Paradigm
How to validate:
- White list input
- Constrain/reject in that sample
- Assign input to a local variable so it can be referenced w/o touching the value. (validate the input, assign the original value to CleanString, then only reference CleanString)
TryParse()
Built in .NET/C# method. Easy way to take invalid strings and parse them into corresponding type w/o generating an exception. Easy way to constrain places where users enter input.
Why use TryParse()
Common way to convert strings into a usable integer; lots of classes are set up this way. Easy way to constrain user input.
What happens when TryParse() has an error
Rather than throwing an exception, it will return a converted number or a zero.
How to test regex
Deconstruct them and run them through a tool, such as the regex coach/the Regulator/Expresso
what is (^\d{3}-\d{2}-\d{4}$)
the SSN regex
What is (\p{Lu}) and (\p{LI})
Regex to match one Unicode uppercase character and lowercase character.
What is (\w) or \d)
Regex for matching a word character or a digit
How do data annotations work?
Data annotations are patterns (in the form of attributes) for standard input validation in MVC. They include things like “Credit Card” or “Phone” or “URL” that validate a specific set of rules on a a field.
Annotations are decorated on the method to enforce the behavior.
How do errors get added to ModelState, so that that it can be valid or invalid?
Model binding automatically adds errors to the state when it receives POST form data. If any POST data has an error in validation, it automatically adds it. You can also manually have code add an error to the state.
For example, you can have an if/else block where the “else” throws an error and adds it to the model state, for custom errors.
When does Model State binding happen?
When POST form data is received, it “binds” the value pairs to the model, with any errors its received.
What is under-posting and over-posting?
When an attacker adds post value/pair fields that aren’t there in the standard request, or deletes ones that are.
How to prevent under-posting and under-posting
ViewModel design.
Create a ViewModel with a 1 to 1 mapping between the specific view and a model. Model is then mapped to an entity object by the controller.
.NET custom annotations
.NET has options for annotation (attribute) driven validation. You can make your own, add it to the model. (Like with SANS.Appsec.Name annotation referencing a common validation custom validation scheme
Can create your own ModelState errors to check against the IsValid library.
ASP .NET MVC “helpers”
when you you @.property style fields (such as @html.Displayfor) it automatically HTML encodes the field
- most of the frameworks try to encode these fields
How to force validation in Web Forms
By calling Page.Validate (runs on client and server)
RegularExpressionValidator does not run…
if the target value is an emoty string. Used in conjuction with RequiredFieldValidator to make sure the field exists and has the correct regular expression.
Can group validators in web forms together on a form, and then have it checked by…
the Page.IsValid before handling any data.
Web forms validators run on
both client and server
Deferred Validation
Added to .NET in version 4.5, deferred (or lazy) validation only runs on an item in the reuqest collection when the app code accesses it.
For example, Requests.Form[“Feedback”] or Model.Feedback would check to make sure that specific field is validated.
Parameter Manipulation vulnerability
Ability to manipulate parameters in post data; headers, cookies, hidden fields.
Can jack with session IDS.
How to defend against parameter manipulation
- keep service-side session state, storing in object on the server.
- Encrypt request parameters with AES and MAC to protect anything you dont want the user to manipulate. (put in HMAC viewstate)
- Perform server side auth checks.
what is an unvalidated redirect vulnerability?
When unvalidated data is used to redirect or forward a user to another site.
Can lure victims to an evil forged version of a site. (that is vulnerable to other attacks)
Protection from unvalidated redirect attacks
Always have the input validated
Use whitelists for authorized redirect locations
Web Forms Unvalid Redirect defense
use the TryCreate() method, to make sure the redirect is relative (in the same application/domain path)
What is an unvalidated forward vulnerability
when the 302 (redirect) code is provided via the server and not the browser. All the redirecting action is run on the back end, not visible to the user.
If the user can control the URL involved in that back end transfer, its a problem.
What process/method is manipulated with the unvalidated forward vulnerability?
its a problem with the server.Transfer method; not an MVC/.NET issue.
Unvalidated Forward defenses
keep user-controllable data OUT of the server.Transfer. If you have to do it, make sure the user data is auth checked/validated.
In DOM based XSS, rather than the XSS being combined reflected back via the server, the XSS attack _________
is merged with the DOM and JS in the browser executes the XSS attack. (The JS in the page extracts the XSS attack and merges it into the DOM method)
Places to put XSS attacks (Contexts)
HTML elements, attributes, and comments
URLs
JS
VBS/CSS.
Protections vary by conmtext.
Html tag that does no encoding
@html.raw
Levels of a .NET web forms directory that you can disable validation at.
You can bypass or disable request validation at the:
- field (Unvalidated property on HttpRequest object, such as Request.Unvalidated.Form[“Feedback”])
- page (setting ValidateRequestMode on any .Net Control to Disabled)
- application (via validateRequest=False in web.config)
Problem with unvalidated forwards
It bypasses authorization/authentication rules
If you must do it, perform code based authorization before forwarding and on the landing page.
XSS exposes the users of your app to
Malware JS based key-loggers CSRF attacks Phishing, spam, and ads cookie theft
What are some “data preparation” methods for defending code from XSS?
Encoding (ensure server and application are using same consistent UTF style, etc)
Canonicalization (different ways you can represent the same tag, in UTF
Output encoding
What happens if encoding is missing, from an XSS standpoint?
Users can inject code that response and FORCE their own encoding, bypassing validation/encoding roles.
What is canonicalization?
THe different ways to represent characters based on encoding types.
How to represent in a dozen different ways. (UTF-7: +ADw-script+AD4-), %3C%73%, etc
.NET libraries for output encoding
AntiXSSEncoder
MS Web protection library (WPL)
HTTPUtility class
___________ offers additional contexts that aren’t part of AntiXSS class
MS Web Protection Library (WPL)
WPL offers what features?
Whitelist encoding methods
an HTML sanization library
Named entity support (auto encoding of HTML-specific special characters, like , and “
________ can be used to sanitize parts of an HTML doc or an HTML doc fragment
WPL Sanitizer class
MVC has the _________ class to automatically encode dynamic data. It uses tags such as ________.
HTML helper class
Tags such as @Html.DisplayFor() method will encode content and prevent XSS attacks, as will @Html.ActionLink
Shorthand way to variable encode content in .NET 4.5+
Use
What is NOT properly encoded using the shorthand (
JS, VBScript, URL, CSS, or attributes
Razor shortcut to apply HTML encoding to a dynamic value parameter
HTML helper class, via the @ sign.
XSS Header protections include:
- setting the HttpOnly flag (preventing access to cookies from client side scripts)
- X-XSS protections (level 0, 1, and 1;mode=block) for variable levels of protection.
- Content Security Policy (header used to set rigid, granular levels of controls for what sources content can come from, and how.
Prerequisites for Content Security Policy to work
Code can not be placed in tags within the HTML page, or with inline event handlers (such as <a></a>
Can’t have app code that calls to functions that allows JS to execute from strings. (Such as eval, setInterval, etc)</a>
what are CSP directives?
The way Content Security policy defines where content can be retrieved from. Items include script-src, object-src, media-src.
In order for ASP .NET (web forms) and CSP headers to be compatible…
You have to disable the unsafe-inline and unsafe-eval directives, and explicitly allow them. Weakens the security provisions.
SQL injection defenses include
Escape command characters in SQL using:
ADO .NET (Parameterization)
LINQ to SQL (automatically parameterizes)
Entity Framework
Dynamic TSQL params
How does ADO .NET solve SQL injection issues?
Parameterizing queries. Rather than directly inserting dynamically concatenated code, it uses parameters (such as username and password) which are properly encoded. (@username)
LINQ is a framework that can…..
…….translate when applications speak to model objects, like SQL, and they translate the properties/queries so that you don’t have to understand the underlying DB store. The queries are then written in C# versus SQL
Newer version of LINQ, that has improved support for other DBs such as __________
Entity Framework. (EF)
Uses a similar syntax (C# to SQL) as Linq, but has wider support.
Vulnerable class within entity framework that can be used for direct commands to be run against the underlying DB.
DBContext. Contains ExecuteSqlCommand and SqlQuery methods, which runs direct commands at the DB.
Two main places LDAP injection can occur
the LDAP filters (such as & and |, which allow queries to look for specific items) and Distinguished names.
How to mitigate LDAP injection
Encoding the content, with WPL LDAP encoding.
What is an Object Relational Model (ORM)
allows objects to be retrieved in a more object-oriented (vice RDBMS) Most common forms of data not stored as objects are RDBs and XML.
LINQ and EF do this type of object to DB language conversion
Defense against XML injection
Encoding, using the WPL Encoder.XmlEncode or XmlAttributeEncode() methods.
Also, the System.Xml class built into .Net has some encoding.
________ is a Power query language for XML that gives you a syntax for selecting nodes in a document, which are ________.
Xpath
Elements, Attributes, etc.
Defenses against XPath injection, and how it works
3rd party MvpXML project; parameterizes Xpath expressions
Through parameterization, encoding occurs on elements
Types of authentication attacks
Weak passwords
Authentication
Improper Restriction of Authentication ATTEMPTS (vulnerable to brute forcing)
Overly restrictive lockout mechanisms (DoS)
Missing auth checks for critical functions
Authentication Bypass attacks fixate on
- Changing what’s assumed to be immutable data: environment variables, hidden form fields, cookies
- Inject SQL/LDAP language into login fields
- Adjust client side auth details, insert into AJAX
What are rainbow tables for?
Cracking hashes that ARE NOT SALTED
Improper restriction of excessive authentication attempts
Without restricting attacks, vulnerable to brute forcing user accounts
Overly restrictive account account lockout
DoS ‘ing someone’s account
When people accidentally expose admin functions on an app to the web, it’s an example of _______
Missing auth for critical functions
When an actor attempts to access a resource, and the software doesn’t perform an auth check on him, it’s an example of ___________
Missing authorization
When users change their passwords, for any reason, they should:
Be sent the request out of band, and have to provide their old password/have their auth token checked.
For changing passwords, .NET has what two controls to add a second factor?
SMS out of band checks and one-time, time sensitive temporary passwords
When using challenge questions for auth, they’re much more effective when:
- Combined with out of band, rotatinmg 6 digit SMS code
2. Made Safe to store/transit, stable information, memorable, and definitive.
How are passwords salted? How many bits?
The system generates a pseudo-random crypto number have it added to the hash. (Can be stored beside it; doesn’t need secure storage)
Make sure it’s at least 128 bits.
Also referred to as a “nonce”
A salt
What library is required for providing actual randomness for things like salts
system.cryptography.RNGCryptoServiceProvider
Alternatives to recovering passwords
Don’t do it, ever. Don’t allow passwords to be recreated or dispensed; it’s an easy way to steal account info.
- Send a temp password that allows users to change it
- Generate a temporary, non-discoverable password change link
- email the users to alert for a change in status/activity
Secure automated account creation via web app pitfalls
Easy to screw up.
- Don’t echo passwords to the user, especially via email or HTTP. (Which shows that the passwords are stored in the clear or using reversible encryption)
- Make users verify the account, so that attackers can’t just drop in 10k accounts with automation
- Make sure account creation confirmation page is destroyed after the account is verified.
Recommended/typical workflow for account creation
- When created, send a confirmation email to user email.
- User follows the link (over HTTPS) to activate the account and re-authenticate. (confirmation contains only text, no private details)
- Set the confirmation opportunity to expire
- Make sure sensitive parts of the app (anything where private information is displayed) is protected with TLS.
Account lockout best practices
- Auto-unlock accounts after a set time, to eliminate DoS/strain on help desk
- Use a captcha to prevent automation of account cracking
Difference between IIS 7.0 and previous versions for integrating ASP .NET (web forms)
In version 6, all ASP activities were received by ASP .NET, and then sent to IIS via Aspnet_isapi.dll and duplicated by an IIS process. (Gateway between the server and the app framework) clunk and cumbersome.
IN version 7, IIS and .NET ASP are more tightly integrated and have a the features are combined for point Auth, Handlers, and HTTP responses, when set to “Integrated mode”
All configuration for ASP. NET and the underlying IIS structure are combined in the _________ in IIS version _________
applicationhost.config and web.config, IIS 7.0 and later
Limitations to the IIS 7.0 integrated web forms/IIS architecture
Unmanaged code creates a lot of overhead, and forms authentication may not protect unmanaged resources like pics, PDFs, office docs, etc.
Benefits of IIS 7.0+ integrated web forms/IIS architecture
Unified functionality
- Can add custom modules into pipeline. (perfect for security)
- Can define config, tracing, logging, output, authorization, etc.
- all inbound web goes through pipeline; this means you can “bolt on” functionality that isn’t resident in apps to the framework/IIS.
What are .NET modules?
Modules are libraries/classes that HTTP requests treaverse through and do something to the data within requests. (often security focused)
What are .NET handlers?
Handlers are what waits at the end of the request to do the dynamic processing: endpoint for the request.
Relationship of modules and handlers to requests
Modules are: 1 module to many requests Handlers are: 1 handler for every 1 request.
How does data go through modules/handler?
Each module inspects the request, does a specific job (like setup a user session, perform authentication, or do an auth request)
After modules handle flow, it’s passed to the HTTP handler that does the GET/POST, along with the URI (.aspx, trace, asxd, etc)
They’re not built-into the framework, but folks use custom HTTP modules to do:
Can do things like CSRF checks, User input checking/validating, customized auth (SSO, SAML, smart cards, etc)
If you wanted to make your own custom event, such as something that fires when specific HTTP security module events fire. “I’d like to subscribe to the AuthenticateRequest event, and have this custom code fire when XYZ happens” you’d use…
Use the IHttpModuleInterface, and create a custom event. Use things like PostAuthenticateRequest and Endrequest, for example.
Provide specific implementation for all incoming requests. (everything *.aspx, everything *.asmx, WebResource.axd for GET requests, etc)
HTTP Handlers
Specify how to handle custom dynamic content, like what to do for requests for PDFS, Word Docs, gifs, etc. (How to serve a word doc to only specific role-based users)
Http Handlers
Gives HTTP handlers access to the “http context” which includes information like session state, cookies, request parameters, etc
iHttpHandler Interface
To use modules and handlers, add them to the _________
applicationHost.config or the web.config. (Can have modules apply to specifc apps, or go site wide)
ApplicationHost.config is ___________
is the IIS 7.0 global control file for both IIS and .NET.
to set up to set up centralized authentication policies server wide, use
modules and handlers.
Six .NET managed authentication methods (modules)
- ASP .NET Identity
- Forms auth
- Membership Provider
- Windows auth
- Default
- Anonymous
Problem with ASP .NET web forms auth
It’s user/pwd based, and creds are past in the POST in the clear, so it requires TLS to encrypt
What is OWIN, and what is used in .NET 4.5 and later for?
Open Web Interface for .NET (OWIN) provides a managed authentication/authroization foundation for .NET identity. What the identity services are built on.
What service in .NET allows functionality with Oath, SAML/SSO, and most backend DB languages?
.NET identity, via OWIN.
3 Categories of .NET auth options
- Individual users (cookie based, username/pwd, social auth)
- Tied to AD/O365/SSO
- Windows IIS auth. (Intranet)
Important security options for using .NET identity cookie based auth
Configuration of Cookie security options, such as CookieHttpOnly, CookieSecure, ExpireTimeSpan, etc
This module manges all user specific items authentication items. Its methods let you change passwords, enforce password complexity/MFA, Send an SMS message to users, etc
.NET Identity User Manager
This module configuration options let you configure methods from the user manager class, like registering two factor APIs, max failed login attempts before lockout, and pwd complexity
.Net Identity User Manager manager config
crypto.cs
The crypto hashing values used by User manager to hash passwords. (Work factor, characters, salt, etc)
After configuring the .NET Identity User Manager module, go here to begin setting up user registration
AccountController.cs, where the Register action takes place and the relevant info (User account, email address, etc) is passed on to the DB, via UserManager.CreateAsync option.
The ______ class is auto-generated by VS and inherits from MS.ASpNet.Identity.EntityFramework.IdentityUser, , and is used to match the .NET database schema.
ApplicationUser class. Lets you configure what properties are stored in the database, like AccessFailedCount, Email, EmailConfirmed, PasswordHash, PhoneNumber, etc.
Application user class Code first migration for Entity Framework is used to….
add new data attributes for a user into the application, and automatically update the backend DB to make sure that the data is consistent and persistent.
EX: if I add CustomerId, BirthDate to a user profile, the EF Code First migration will update the back end DB with those two fields.
- Enable-Migrations
- Add-Migration Init
- Update-Database
After completion , you’ll see the DB schema will have new columns for these properties.
Problems with OWIN
- Doesn’t enforce account lockout by default
- Weak password length by default
- Missing password expiration/password history (using old passwords is easy) features
- OWIN Cookie Manager bug by default”
OWIN bug and the fix
OWIN uses middleware cookie collection (Separate from application cookies) which are lost if Response.Cookies are modified. (First cookie added overwrites the OWIN cookie)
Fixed via setting the CookieManager to SystemWebCookieManager, which will sync cookies between middleware/app up.
Three main problems with forms auth
- Is older, and only works with SQL/AD out of the box. (oracle and such needs a customer connector)
- Stores in 3 formats: clear, MD5, and SHA1. (not great options)
- Even if hashing the passwords in the web.config, they’re still vulnerable to brute force style/rainbow table attacks.
Bolt on solution to overcome a lot of the security problems with older .NET security problems, like those found in forms auth and old versions
Membership Provider. Provides a bolt-on solution for older .NET versions to hash passwords with SHA256, and store them in a backend DB for use. Blocks poor security features, such as non-complex passwords.
Can customize the hashing/salting done by the membership provider forms auth feature. (for example, change it from SHA1 to PBKDFv2)
Uses Kerberos V5/NTLM for auth, and doesn’t function through a proxy/firewalls
Integrated Windows authentication
Best auth for use on the intranet apps
Integrated Windows authentication
Sole purpose is to make sure there is an IPrincpal object in case nothing was assigned.
Default Auth. Gives everyone accessing the system a “GenericPrincipal” object with no user info.
Grants/denies users and roles access to URLs. Controlled by developers, and configured in web.config with and sections of the web.config.
.NET Managed Url Auth
the tag (In URL auth module) indicates…
a file or folder that you’re applying authorization code to (such as /privateFiles), and then
In some cases, you might have to programmatically check whether a user has access to a resource based on role and URL. You’d use the following tags in the URL Auth module.
Checks based on the and configuration.
Looks like: UrlAuthorizationModule.CheckUrlAccessForPrincipal( "/privateFiles" , User , Request.HttpMethod)
Best practices for configuring the Role Manager (ways roles are stored) include…
avoid caching
protection is set to “all”
requiring TLS, keeping timeouts low
no persistence
Two types of authorization driven by code:
Declarative (preferred: annotation in MVC)
Explicit (secondary: boolean “has this role, y/n”)
Iprincipal object (use, data contained)
Can perform authorization checks. Holds general info about the user, like privileges and roles.
Has a property named “Identity” that contains specific info about user.
Identity property (part of IPrincipal object) contains what info?
Authenticated users user account
User.Identity.IsAuthenticated
User.Identity.Name
Two ways to access the IPrincipal object
Through the current web page (System.Web.UI.Page.User) and HTTP context (HttpContext.Current.User)
MVC uses _________ to do declarative authorization checks
the AuthorizeAttribute class, with [authorize] attributes. Kept in the controller.
Can perform basic “is this account authenticated” checks and more advanced role based checks. (Is this user in the manager role?”)
Explicit authorization checks works by….
Querying the IPrincipal object, performing boolean checks on the response.
(if (User.IsInRole(“Admin”) then do stuff, else log/exit.)
Managed file authorization works by…
Using windows authentication. File authorization uses the Winodws ACL to limit access to the file system. Used mostly for internal network ops.
“get the windows current user token, check it’s ACL”
What are the various .NET session (user) tracking methods?
Session Cookie, Role Cookie, Forms Auth Ticket cookie, custom cookie, custom URL value, or auth headers
What’s the difference between .NET session tracking and general session tracking?
General Session tracking is a way of tracking users, irrespective of .NET session feature (that has its own architecture, use, API, etc)
What is Application State for?
global variable available on every web page in an app by every user..
the state is only stored in memory, and in a single process. Not replicated across application farms, other processes, or if app restarts.
*Only good for use as an app dictionary.
Pros and cons of storing server-side session information in Profile Properties?
Pros:
- Can attach any type of user info to the profile object. (ex, Profile.Name, Profile.Age) How we used to track users. (via profile objects)
- Works for anonymous/unauthenticated users.
- Properties are defined for the Profile oject in the web.config
- Works for Forms/Windows auth, too”
Cons:
- not good for security purposes.
- The profile properties state is stored in a sql database in a single DB column, and all the objects are aggregated into a user ““blob”” which can then be read back to the object. (or anyone else with access to that blob can de-serialize it and see all the stuff) Not good for searching for specific properties, like an age.
How are profile properties stored and utilized by an application?
he profile properties state is stored in a sql database in a single DB column, and all the objects are aggregated into a user ““blob”” which can then be read back to the object. (or anyone else with access to that blob can de-serialize it and see all the stuff) Not good for searching for specific properties, like an age.
anonymous users can have user defined properties set via the:
Profile Properties, which are defined in the web.config
Dictionary that contains information managed between page requests, used to track users
Session Object. Tracked via URL value w/Session ID or via cookie.
Session state can be used for what tasks?
Uniquely identify browsers/client device requests, and map them to a session instance on the server
Store session-specific data on the server for multiple browsers/client device requests within that session
Raise appropriate session mgmt events.
Five .NET session state modes
In-Proc StateServer SqlServer Custom Off
Session object main purpose
Server side storage for state management. MOST secure fashion of storing user info server side. Assigned to one user, and tracked via cookie or URL value that has a session ID
InProc session state mode for .NET
Stores session data in memory w/the web app; very fast but memory intensive
StateServer session state mode for .NET
Windows service to store session info in memory, OUTSIDE of the app pool process state.
SQLserver session state mode for .NET
MAX SCALABILITY. Stores the session state centrally in a sql server (or sql cluster)
Custom session state mode for .NET
Developers can create or use third-party session state storage libaries to extend or enhance capability
________________________ doesnt work for anything aside from single server applications; object doesn’t traverse to other servers, across trust boundaries, etc. Volatile storage. Stored in THE SAME WORKER PROCESS POOL.
.NET “In Proc” state storage
.NET in proc storage is hard to utilize because….
It doesn’t traverse servers, trust boundaries, and is lost in a reboot; memory intensive.
in .NET ________ session state mode, a module reaches out across a process boundary, to the network, and stores state information.
StateServer mode. Very memory intensive, but efficient. Can be used by multiple web servers.
Restrictions for using StateServer .NET session state mode and SQL server mode
Network traffic between worker process and state server (or sql server) is not encrypted. (Must use IPSec/TLS)
Because the data crosses a process boundary, it must be serializable
What is Aspnet_regsql.exe tool used for?
creating the sql database for .NET to use to store state info
Where is the .NET session state mode set? How is it protected?
Which session state configuration mode is used is configured in web.config. Set as InProc, StateServer, SqlServer, Custom, or Off.
Can be protected by encrypting the web.config, but unless its combined with “integrated auth” sql server state management won’t work with an encrypted web.config section. (Will have to store the creds in the clear)
What does integrated auth do for a sql server connection in the web.config?
For sql server state management, just server/DB name required, no creds stored…use trusted_connection=true
If session management in the web.config is set to “custom” options include…
Can use whatever back end you want to store session state info; MySQL, Oracle, Mongo, etc.
How to clean up/end sessions? What are some considerations for the method calls?
- InProc mode: Session_OnEnd event, removes active session fm mem
- Session.Clear() needs to be called before Session.Abandon() for log outs
- in SQLMode, Session.Abandon() doesn’t do anything, DB is cleared out periodically by SQL jobs
”
Pre .NET 2.0, _________ was used to encrypt a web.config
aspnet_setreg.exe (DPAPI)
Post .NET 2.0, __________ is used to encrypt a web.config
aspnet_regiis.exe (RSA or DPAPI)
It’s a smart idea in .NET to use _________ for client side data instead of hidden fields
ViewState
Only _________ session mode supports the Session_OnEnd event, and uses it to ________-
InProc mode, and uses it to remove active session info from memory.
What cleans up SQL server session state info?
Periodic SQL tasks. Should still use Clear() and Abandon() to make sure it gets cleared out.
ViewState is used ONLY in ________
web forms; each viewState is tied to a specific Web Form.
View State is transmitted as ________ and holds ________
a hidden field, and it holds data for a user’s session.
Viewstate weaknesses
Can be extracted and viewed, if not encrypted, and can be replayed from old requests. Not associated with a user or session by default.
Can be used in CSRF attacks, or manipulated.
How to add integrity measures to viewstate
Use HMAC (message auth code) to prevent tampering of view state
Don’t set viewstate encryption to always unless
you have sensitive data to protect. it slows down processing, and isn’t always necessary for non-sensitive fields.
the ______________ is used to create HMAC hash. Can see the decryption key//validation key in the ________.
machineKey element
web.config
you can avoid having someone replay view state by….
….and how does this work?
by tying View State User Key to a specific user (using SessionID, for example)
if someone tries to replay using CSRF, they’ll have a different Session ID, because it will be an old value. (Different HMAC); That SessionID becomes a nonce.
Dont store ________ in cookies.
Sensitive info; if you have to store sensitive info there, encrypt the cookies.
How to secure client side cookies
Turn cookies to secure = true and HttpOnly = true.
Make sure that sensitive data is handled in a transaction: transactions are transactions, one-to-one, and not one step in a process to prevent ________
race conditions
What encryption methods are available for view states?
AES, 3DES w/the machine key
What integrity algorithms are available for view states?
HMAC via SHA1, MD5, 3DES, AES, etc.
SHA1 preferres
Protection against race conditions
- Make sure all modifications to a data record happen in one transaction.
- Use locks for a thread so that nothing can access those objects in different threads
- Use .NET session module; its immune to race conditions
View State User key works by tying a ___________ to a POST, to create a nonce.
SessionID, which means that the server is performing a diff on requests to see if the POST came from a different user
A blob of data created by the server and assigned to/stored on the client
A cookie
When software doesn’t use sufficiently random number values for security token/ID its considered…
A weak session ID. Shoot for 128 bit values, same as salts.
all ___________ don’t support HttpOnly
browsers. (It’s not included in the RFC)
_________ instructs the browser to share only the cookies w/a TLS secured connections
secure
Weak Session ID countermeasures include: (3)
- Use cryptography namespace (library) and RNGCryptoServiceProvider to generate strong, random numbers.
- Use expiring session cookies over persistent cookies or long-lasting tokens.
- Use .NET session features, which are strong.
MITM countermeasures (4)
- Use encrypted (at all times) comms: VPN, TLS, HTTPS, IPSEC.
- Don’t use kerberos, if possible; vulnerable to pass the hash style attacks, vulns in NTLM.
- set secure flag on ALL security-related cookies
- Use .NET session cookies, Role provider cookies.
Why was HSTS created?
In response to the sslsniff/sslstrip vulnerabilities
What is HSTS? (HTTP Strict Transport Security)
When browser receives HSTS header, it forces all comms to always use HTTPS with valid certificates.
Stealing the authentication token by stealing or predicting a valid session is called
Session Hijacking
Happens frequently when session IDs are placed in the URL. Get a valid user ID, Get a user to authenticate using that session ID (using phishing attack or otherwise), and then “share” the authenticated session.
Session Fixation, or “borrowing”
This language constantly passes it’s session id in the url/clear, and is more vulnerable to session fixation as a result of it
JScript
Session hijacking defenses
- Secure auth cookies
- HttpOnly auth cookies
- Strict Transport Security response header (HSTS)
Session fixation defenses
- always assign new session ID during authentication. Throw away old auth cookie.
- no cookieless sessions.
- Always use HTTPOnly
Getting a user to browse to a page and submit a request which you may not have wanted to do is…
CSRF
When a web app can’t verify whether a properly formed,valid, consistent request was intentionally sent by the user who submitted it
CSRF
CSRF defenses (6)
- Anti-CSRF tokens, nonce, or form key that is tied to a session/auth. Even if the user knows everything else to execute a transaction, they wont have the user generated nonce
- reduce session timeout values
- Use session cookies vs. persistent cookies
- Re-authenticate for critical operations
- Use CAPTCHAs
- Use POSTS to modify data, never GET
Biggest .NET specific anti-CSRF mechanism
Validate Anti-Forgery token
What is the Validate Anti-Forgery Token?
built into MVC
- NET uses a syncronizer token, which doesn’t match the original cookie value
- Double submit cookie pattern (The same CSRF token generated using pseudo-random number, and is embedded in a cookie AND hidden form field, and matched up on each request.
What is a synchronizer Token pattern?
Defense to CSRF.
Generates a challenge token, which is a random value associated with the current session/user. That token is submitted with every request. (Hidden field for POSTS or the URL for GETS) The server then checks to make sure that token is current for each session/user.
Can do it per request or per session.