• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/100

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

100 Cards in this Set

  • Front
  • Back
Performance Wizard
performance profiler within VS, which means it analyzes a running app. Generates a report after testing app.



CPU Sampling: lightweight profiling method that gathers info every couple CPU cycles.




Instrumentation: profiling method that injects code into assembly to collect timing info of all methods.




.NET memory allocation: profiling method that has 2 modes. Sampling or code injection to track when objects are created or freed




Resource contention data: profiling method that reports on thread contention with each other and system, CPU utilization, and overlapped I/O

Visual Studio Profiler
performs a trace of all called methods and memory used. Generates a large amount of data which can be hard to parse through.
Performance Monitor
separate app that monitors multiple applications in a production environment. Can schedule when it runs, like nightly batch jobs or when new functionality is released
System performance counters
focuses when apps/processes start, stop, and run
Application performance counters
watch details going on within app like HTTP requests, caches, and errors
Troubleshooting authentication
if all users affected, could be a bad connection string to a DB or bad authentication scheme in IIS.



if only some users affected, most likely issue with base authentication system.

Troubleshooting authorization
if all users affected, system may not be able to get appropriate info.



If some, could be role names don’t match those from providing authority or users may have wrong role assignments.

TraceListeners
writes logging info from a running app. Setup in Web.config. Could write to text file, event log, XML, CSV, etc.



Can manually write info by using the Trace object can calling static methods like Write, WriteIf, WriteLine, and WriteLineIf

Setting up error logging
1. Can add [HandleError] to a method or controller.

2. Can override OnException() method on a controller.


3. Can log in the Application_Error() method in Global.asax, which is app-wide but can be hard to get details about specific users.


4. Can create a custom error filter by overriding HandleErrorAttribute class.


5. Can use 3rd party tools like NLog and log4net.

Code Contracts
an extension in Visual Studio added with .NET 4.0 that allows you to define conditions for methods in an app. Define preconditions (Contract.Requires), invariants (Contract.Invariant), and postconditions (Contract.Ensures). Throw exceptions if rules are violated. Can manage contract failures by registering a handler to the Contract.ContractFailed event
[ContractInvariant]
attribute to define a method as a code contract for invariants. Method lists the rules that can’t be broken at anytime within a class. Example, System.Diagnostics.Contract.Invariant(this.Id < 0);
Health Monitoring
built into ASP.NET to handle logging of web events. Setup in the web.config file



App lifetime events; when app/processes starts/stops or at scheduled times.




Security events; login failures or unauthorized attempts to access secure URLs.




Errors; all, unhandled, infrastructure, processing, etc.

Exceptions across layers
exceptions should only travel to layers that communicate with it. Errors in data layer should be caught by business layer. Business layer should decide how to handle it and if it is necessary to show in the UI layer.
Custom error pages
Usually one for 404-Page Not Found and a generic error page. Can create more specific ones with views and controllers and redirecting manually in the Application_Error() method in Global.asax. Could also redirect based on error codes in the Web.config file.
First chance exceptions
can get notifications of exceptions before they have been handled by an error handler. However just notifications, does not handle it. If setup, debugger breaks at the catch statement before it enters the block.
Can also create an event delegate by subscribing to FirstChanceException in Application_Start() in Global.asax; however an error here will lead to a StackOverflow due to recursive calls.



Need to check the Thrown box under CLR Exceptions. (User-unhandled already checked by default)

Test-Driven Development (TDD)
requirements are translated into runnable unit tests after design, but before development.
Assert
verifies conditions in unit tests using Boolean conditions. Example Assert.IsTrue(unitTest.Add(2, 2).Equals(4)).
Unit Test
tests smallest possible unit of functionality in a replicable, automated manner. Should not need any dependencies, should be granular and test only one behavior. Should test for positive, negative, edge, and “impossible” cases. Should create a test file for each controller and several tests for each method in it. Methods should be decorated with [TestMethod]
Integration tests
test dependencies between integration points and across layers like creating, editing, deleting a database object through the UI
Shim
small piece of code that intercepts a call to an assembly and returns an object you created or mocked. Generally used to provide mocks from assemblies outside your solution. Example, intercept call to DateTime.Now with ShimDateTime.NowGet and replace it with something else hard-coded for testing.



Must wrap code with a using(ShimsContext) statement or else all code will use the shim!

Stub
mocked up code that replaces a working class with a limited subset of features. Automatically provide an implementation of the interface you can work with as if it were a real object. Thus should never new the base class; only create instances using the interface. Naming convention is to put Fakes.Stub in front of interface name.
Fakes Assembly
used to create a shim or stub for an assembly referenced in your solution
Web Tests
can simulate many simultaneous visitors running app through a designated workflow. Available with VS2012-Ultimate
Constant load web test
Web Test that uses a constant number of users throughout entire test run. May be too unrealistic
Step load web test
Web Test that steadily increases number of users throughout a test run
Goal-based load web test
Web Test that increases number of users in a test run until it reaches a goal like a certain percent of CPU or memory usage.
Browser Link
feature in VS 2013 that allows you to debug with multiple web browsers at once. Uses a HTTP module behind the scenes to inject JS code for SignalR.
Mobile Browser Emulators
Can set up in IE 11 with F12 Developer Tools or GoogleChrome DevTools. Has preset sizes and orientations for Windows Phones, iPhones, iPads, etc.
Diagnostics in Azure
must use diagnostic tools in Azure SDK as any saved logs will be lost after app stops and restarts due to virtual nature of roles. Need to import the WindowsAzure.Diagnostics API in ServiceConfiguration.csdef then setup app, DBs, etc in ServiceConfiguration.Local.cscfg and ServiceConfiguration.Cloud.cscfg. Examples: IIS logs, diagnostic infrastructure logs.
Transferring diagnostic info in Azure
Can save logs to an Azure storage account directly, manually, in a batch schedule, or when role shuts down. Can transfer on-demand by requesting through code, from an external app, or schedule a transfer through config files
Custom diagnostic tools in Azure
Any tools like performance counters need to be added to Diagnostics.wadcfg. Not recommended to setup programmatically as diagnostics can start before the OnStart() method, config changes don’t need role to restart, custom code doesn’t need to run.
Azure emulators
can run project on local machine as if it was running in cloud. Can also emulate storage and compute accounts. Can configure settings like maximum endpoints and cores.
IntelliTrace
can run through a snapshot of a debugging trace from Azure as if you were debugging them locally. Can log events only or with call information which could impact performance.
Remote Desktop
can remotely access a Windows Azure instance directly to review IIS logs, event logs, and do other tasks instead of having to do locally
Remote Debugging
how to debug an app on another computer in Visual Studio. Must download Remote Tools for VS 2013+
Server Explorer
server mgmt console for VS. How to create, manage, and browse data connections to other database servers. Can view, edit SQL tables and columns
Authentication
process of determining whether users are who they say they are. 2 parts in ASP.NET MVC, IIS and the .NET app framework. 2 types of authentication.

Challenge-based: client must respond to server’s demand for credentials like login/password




Login redirection-based: credentials sent to server without being required

Authenticated User Information
HttpModule verifies User object and adds it to System.Web.HttpContext.Current.User. Also added to System.Threading.Thread.CurrentPrincipal, but doesn’t always stay in sync, so set it equal to each other manually. If User info is on Thread.CurrentPrincipal, can be used by all controllers, models and assemblies on that thread.
User security interfaces
IPrincipal has info about the current user like their roles. IIdentity has info about all users like name and if they are authenticated.
Anonymous authentication
only form of authentication installed in IIS7 and above; need to install all the others. Does not attempt to identify who the client is. Requires you to select a user or service account that anonymous users will impersonate to access files. Can assign to an individual website or to the app pool that runs the website. Can setup in IIS Manager, config files, or by using AppCmd.exe
Basic authentication
simple way to send a username/password between a client and server. Base64 encoded but not encrypted. Wrapper around traditional Windows security, so users need to have accounts in Active Directory or on the server. Checks the default domain, and if none, the local server, and if that fails, request is rejected. Can setup in IIS Manager, config files, or by using AppCmd.exe
Digest authentication
same as basic authentication but uses a challenge-response mechanism to ensure credentials sent are encrypted. Both client and server create hashes of challenge and challenge value to make sure that both are sending items that haven’t changed.
Forms authentication
a way to allow authentication and authorization without using the built-in Windows security system. When trying to access a URL that requires an authenticated user, a rendered HTML page appears to input username/password. These credentials are matched in a DB and if successful, user’s authentication token is set and can be saved in a cookie for the rest of the session. Token and roles are sent on every request to the server.
Windows authentication
single sign-on experience from already logging into Windows domain. Doesn’t ask for login credentials, and instead server retrieves user’s login info from browser’s credentials cache. Only works with Microsoft browsers.
ASP.NET Impersonation authentication
add-in on top of Windows authentication. Allows you to use Windows identity to also allow access to items like network or file resources. Sets System.Security.Principal.WindowsIdentity object. Must first turn on in Web.config file. (This is independent of the authentication mode that fills in HttpContext.User property.)
(IIS) Client Certificate authentication
most complex and secure form of authentication. Requires a SSL certificate installed on the server and all clients must have a corresponding client cert installed. Requires that IIS server, client computer, and user accounts are members of an Active Directory domain. IIS Client Cert supports ability to map a client cert also to the local server so is more flexible.
Interfaces for Custom Authentication
if custom class implements IPrincipal and IIdentity can use the [Authorize] attribute and other features in framework. If not, have to recreate the whole authentication process and framework
IsAuthenticated()
Call on Thread.CurrentPrincipal.Identity or HttpContext.Current.User.Identity if you don’t want to use the [Authorize] or [AllowAnonymous] attribute.
Accepted/Blocked-Lists
If you apply the [Authorize] attribute globally in RegisterGlobalFilters(), must have an accepted list of actions that don’t need authorization or else you can access site at all. Blocked-list not recommended as you would have to maintain a long blacklist of actions that need authorization.
FormsAuthenticationTicket
encrypted version of authenticated user name that is stored in the cookie. Can be accessed around site by accessing FormIdentity.Ticket. Ticket is encrypted by using FormsAuthentication.Encrypt(). Ticket is sent with all requests/responses. Thus tradeoff in performance
Stateless authentication
instead of having to send encrypted cookie with authentication ticket/user roles, use a SessionId on the cookie to lookup info on the server/DB. Thus user info is not sent to client.
Saving in network performance by not sending ticket with all requests, but now have to call a DB for lookup
Classic membership framework
Stores name, password, and some profile info. Designed mainly around users, roles, and profiles as opposed to ASP.NET Identity which is claims-based
SimpleMembership class
umbrella term for both SimpleMembership and SimpleRoles. Can use any table that has a column with unique user names and a column for the Id.
SimpleMembershipProvider class
requires additional tables for roles and membership like passwords. Implemented by WebSecurity class
Overriding FormsAuthentication membership provider
1. Handle FormsAuthentication class which sets the ticket into the cookie with SetAuthCookie().

2. Encryption is done using the machineKey element in Machine.config. If in a webfarm, this must be the same on all servers.


3. Handle FormsAuthenticationModule which is an HTTP module that decrypts the cookie/ticket and adds it to the HttpContext for each request

Custom Membership Providers
need to inherit the MembershipProvider abstract class which inherits the ProviderBase abstract class. 25 methods and properties total so consider requirements. Using WebSecurity helpers will not work.
ApplicationName value
allows you to have multiple identical user names in the same DB as only as they are for different apps. Allows you to use the same credentials DB for multiple apps.
ASP.NET Identity
new framework for membership that addresses limitations from Simple Membership and Forms Authentication. Can now use OWIN, Organizational accounts like Azure Active Directory, or NoSQL databases. Can’t use Windows authentication. Claims-based instead of role-based. Introduces 2-factor authentication, account reset, account lockout.



Managers: how to do CRUD operations for users, roles, email, SMS, sign-in. Talks to corresponding data store. Stores: talks to underlying data source. Stores info about a user like an email

OWIN
Security middleware that uses a simple dictionary collection to lookup info from whatever external identity provider like Facebook or Google. Microsoft’s implementation is Katana now integrated into ASP.NET 5. (implemented as extension methods on the IAppBuilder interface)
Authorization
process of giving a user permission to take action on something like a CRUD action in a DB. process of comparing a user’s capability to interact with items against the user’s request
Roles
best way to manage permissions instead of handling authorization for each user. Role’s title should describe privilege like CanEditOrder instead of OrderPicker. No template for creating roles, must create a UI and use the Roles API or insert directly into the DB with scripting. Typically has a related membership provider like SqlRoleProvider and SqlMembershipProvider.
Configuring Roles
defining providers is setup in Web.config file. Just change config file rather than having to redeploy app. If using SimpleMembershipProvider/SimpleRole have to specify where the user table is in InitializeDatabaseConnection()
Programmatically authorizing roles
in controller/action use [Authorize(Roles=”a,b,..”)]; upon failure sends user to login screen.

If roles not predetermined, use RoleProvider.GetRolesForUser(), HttpContext.User.IsInRole(), or RoleProvider.IsUserInRole().


If using the WebSecurity helper class can use WebSecurity.RequireRoles(), but on failure will stop processing and will return a HttpResponse with an error status of 401-Unauthorized

Custom Role Providers
if you have different needs or roles not stored in Active Directory or roles stored in SQL Server tables.

1. Inherit the abstract base class RoleProvider which inherits the ProviderBase class.


2. Add locks to ensure that provider is thread-safe.


3. Encrypt the cookie which stores the roles; done in each server’s Machine.config file.




(More common than creating custom membership providers or tokens)

WCF Service authorization
1. Can transfer user credentials from app to WCF; service is responsible for auth.

2. Can transfer a set of credentials for app; app is responsible for auth and must create proxy to WCF service by first using the Add Service Reference command. WCF’s client is the app not the user.


3. Can make the WCF call directly from client with AJAX or call from server.

Federated security
relies on another application to authenticate users using claims, bits of information about the user the provider is willing to share. Authorization is based on claims not user roles. Claims are passed between apps using security tokens.
Azure Access Control Service (ACS)
a centralized place to authenticate users through 3rd parties like Facebook Google, ADFS, OAuth, SAML. etc. Example of a security token service (STS). Does not necessarily reduce number of users to be managed in app; still need to maintain info for personalization or roles. Should also provide users an ID for your app (can be same as the Identity provider or new)
ACS Workflow
Client->App->ACS->Identity Provider->token to user->token to ACS->ACS creates new token with claims from Identity provider->new token to app->app sends back original request to client.



This is all handled by OAuth.VerifyAuthentication(). Can also choose to save token in a cookie. After receiving the token from ACS use OAuth.Login()

Windows Identity Foundation (WIF)
framework for building identity-aware apps. Part of the .NET framework. Abstracts away the WS-Trust and WS-Federation protocols with APIs
Security Token Service (STS)
builds, signs, and issues security tokens according to WS-Trust and WS-Federation protocols. Windows Azure ACS is an example.
Custom Tokens
created in XML and must also be managed in a class that derives from the SecurityToken class. Will need to create a custom token handler, but do not need to rewrite the WS-Federation protocol’s token transfer mechanism
Custom Token Handlers
every token needs a token handler to validate it. Needs to derive from SecurityTokenHandler and override methods to read, write, and validate the token. In Web.config or App.config, also need to add the handler in the system.identityModel tag. Uncommon compared to creating new membership or role providers except if using SWT or JWT as they don’t have handlers built-into WIF
SAML Tokens
XML-based protocol that uses tokens (claims) along with assertions, or packets of info, about a principal/end-user between the SAML authority and a service provider. Can be used with SSO, federated identity, and web-services security. Built into .NET Framework so don’t need to create a custom token handler. Tokens are signed with asymmetric certs; thus clients can’t create their own tokens. This means you can support key rollover, revocation, and client access verification. Tokens can also be encrypted.
Simple Web Token (SWT)
simpler than a SAML token (claim) and is signed with a symmetric key. Because user has all the key info, rollover is complicated and does not support key revocation. Does not have a token handler built-into WIF
JSON Web Token (JWT)
security token/claims to be transferred between 2 parties. Encoded as a JSON object signed with a JSON Web Signature (JWS) and/or encrypted with JSON Web Encryption (JWE). Expected to replace SWT. Does not have a token handler built-into WIF
Symmetric encryption
uses the same key to encrypt and decrypt and suitable if system is doing both steps. Reading/Writing performed on streams (CryptoStream class) and useful for large amounts of data. DES is an old symmetric algorithm, superseded by the AES (Advanced Encryption Standard) and Rijndael algorithms
Asymmetric encryption
uses a public key for encryption which is shared and a private key for decryption which is not distributed. Used with SSL so browsers can encrypt info with a public key that is sent to web servers which decrypt it with the private key. Only useful for small amounts of data like a single webpage.
Hashing
process of applying a formula to a string of text that produces a value of fixed length that cannot be decrypted back to the original value. Hashing same text with same algorithm gets the same result which indicates that data has not been modified or that entered password matches hashed value stored in a DB. MD5 has a major flaw. SHA is most common in ASP.NET but SHA-0-SHA-3 represent improvements.
Salting
makes encryption and hashing harder to break by adding random strings to beginning and/or end of text before algorithm is applied. If salt is different, then even if 2 passwords are identical, the hashed value will be different. Should be as long as hash value. Can store salt in same DB as password hash, or use the first or last characters of the hash as the salt.
Encryption best-practices
1. Use different keys for different business functions instead of one key for whole app.

2. Protect symmetric key and private asymmetric key.


3. Don’t store keys where data is stored.


4. Set keys to expire.

Encrypting config files
should protect as it could include passwords, connection strings, and other private info. DpApiProtectedConfigurationProvider uses Windows Data Protection. If you need to use config files on multiple servers use RsaProtectedConfigurationProvider as it allows for import/export of keys for encryption/decryption. Need to add machine key so that ASP.NET can decrypt it, which then happens automatically.
Aspnet_regiis.exe
encrypts config files.

-pe: element to encrypt


-app: virtual path to app


-prov: type of encryption provider


-pd: element to decrypt

Nonrepudiation
ability to prove that an authenticated party is the same party that took a particular action
Digital signatures
hash text with an algorithm like SHA-1, then encrypt the hash with an asymmetric algorithm like DSA. Provides authentication, authorization, and nonrepudiation
SSL
Secure sockets layer. Creates an encrypted link over HTTPS between servers and browsers. Server requires a SSL certificate/public key cert/digital cert/identity cert. Cert links an identity to a public key. Identity info includes name of company, contact info, expiration date, issuing date, etc. Browser checks its own list of trusted CAs
PKI
Public key infrastructure. Signed signature comes from a trusted 3rd party, a certificate authority (CA).



In less formal schemes, signature comes from another user (an endorsement), or from the user themselves (a self-signed certificate)

How to turn on SSL on a web server
Request a cert with IIS Manager. Server creates public/private key. Public key is saved into a Certificate Signing Request (CSR) which is submitted to the CA. CA validates the CSR then issues a SSL cert to load into your server. If public key from SSL cert matches private one on server, you can now turn on HTTPS binding.
Dictionary attack
large file of strings, common passwords, numbers, and their hashes which are compared to stolen hashed passwords
Brute-force attack
simply uses random characters to guess and eventually find matches. The longer the password, the more time required
Rainbow table
instead of using random values like in a brute-force attack, it uses a dictionary of values and hashes them on-the-fly. More can be stored since the unhashed values are smaller
CSPRNG
Cryptographically Secure Pseudo-Random Number Generator.

Example: RNGCryptoServiceProvider.GetBytes()

Key-Stretching
repeatedly hashing each password, along with a salt and pseudorandom function, generally a minimum of 1000 times so that hacking it would take exponentially more time. Example is the PBKDF2 iterative hasher. Users can’t see old password, but nobody can either.
Email loop
used when user needs to reset a password if only hashed passwords are stored since original password can never be retrieved by hash. Generate a single-use random password that is now tied to their account and will expire when used and after a certain amount of time.
<%Html.Encode(text)%> and Server.HtmlEncode(text)
encodes string into literal text rather than runnable code in case of attack either before display or before saving to DB. preference is before display. Only blocks a set list of characters (less secure). Available in the .NET library
AntiXSS
Microsoft library for anti-cross site scripting attacks. Protects against attacks in dozens of languages. Does not affect UI. Takes an accepted-list of characters that will be encoded; opposite of standard .NET library thus is more secure
Lazy request validation
postpone data validation until you are going to access and use it. Minimizes the work done on the server. Turn on by setting in Web.config file for ASP.NET 4.5
Preventing SQL Injection
1. check for data type and length.

2. Use SQL parameters even if you already performed validation.


3. Use a restricted SQL account like access only for stored procedures and not underlying tables.


4. Don’t show details about data in error messages.


(Linq-to-Entities does not have this problem since it uses the object model, not free-text input.)

SQLParameter class
use to prevent SQL injection attacks. Parameters are treated as literal values and checked for type and length. If it fails, an exception is thrown.
XSRF/CSRF
Cross-site reference/request forgery. Exploits trust a site has for the user. Example, secretly injecting a URL to cancel an order within JS, HTML, email, a form.
Antiforgery tokens
use the [ValidateAntiForgeryToken] attribute on actions and call @Html.AntiForgeryToken() from Razor. Makes sure page sent from server is the same as one received. If token value saved in cookie and from HTML form do not match, the action will error out. 128-bit token created using RNG cryptography. End-users have to turn cookies on or else they will error out inappropriately.