Friday, June 22, 2012
Tuesday, June 19, 2012
xxs stopper
Code download available at:
WickedCode0408.exe
(118 KB)
Browse the Code Online
Figure 1 SecureSessionModule.cs
Figure 3 Error Showing Generated Key
Browse the Code Online
Let's face it: every
minute of every day, someone, somewhere, is patrolling the Web looking
for sites to hack. ASP.NET developers must constantly be on their guard
to ensure attempted hacks can't be successful. That means constraining
and validating user input, accessing databases securely, storing
sensitive data securely, and generally writing secure code that repels
rather than accommodates these malevolent hackers.
A
classic form of hack attack that ASP.NET sites must defend against is
session hijacking. Simply put, session hijacking entails connecting to a
Web site and accessing someone else's session state. The severity of
the damage incurred depends on what's stored in session state. If
sessions hold shopping cart information and users are required to verify
their identities before checking out, session hijacking might not be
very damaging. If sessions contain credit card numbers or similarly
sensitive data that can be presented back to the user, you really have
to watch out.
Session hijacking
attacks are typically perpetrated in one of two ways: session ID
guessing and stolen session ID cookies. Session ID guessing involves
gathering a sample of session IDs and "guessing" a valid session ID
assigned to someone else. ASP.NET apps tend to be much less susceptible
to this form of session hijacking because ASP.NET uses highly random
120-bit numbers for its session IDs. Unless you replace ASP.NET session
IDs with IDs of your own (last summer I met one developer who had done
just that and used sequential session IDs, which are an open door to
hackers), you have nothing to fear from session ID guessing.
Stolen
session cookies are another matter. Secure Sockets Layer (SSL) can be
used to protect session ID cookies on the wire, but few sites restrict
session ID cookies to encrypted connections. Even if you use SSL,
session ID cookies can be stolen in other ways, notably through
cross-site scripting attacks, man-in-the-middle attacks, and gaining
physical access to the cookie stores on victims' PCs. Furthermore,
executing a successful session hijacking attack with a stolen session ID
cookie requires little skill on the part of the attacker. The reason is
simple: ASP.NET encodes no information in a session ID cookie other
than the session ID. If it receives a cookie containing a valid session
ID, ASP.NET connects to the corresponding session, no questions asked.
It's
virtually impossible to build a foolproof defense against attacks that
rely on stolen session ID cookies, but you can take steps to make it
harder. Some Web sites, for example, encode heuristic information such
as IP addresses in their session IDs. That doesn't prevent session
hijacking altogether—after all, some hackers possess the means to spoof
IP addresses, and IP addresses are not a reliable means for identifying
callers anyway—but it does raise the bar. Security is all about raising
the bar. The harder you make it for a hacker to execute a successful
attack, the less likely it is that successful attacks will occur.
Introducing SecureSessionModule
[
Editor's Update - 7/20/2004:
Figure 1 has been updated so as not to provide too much information to an attacker.]
using System;
using System.Web;
using System.Web.Security;
using System.Configuration;
using System.Security.Cryptography;
using System.Runtime.Serialization;
using System.Globalization;
using System.Text;
public class SecureSessionModule : IHttpModule
{
private static string _ValidationKey = null;
public void Init (HttpApplication app)
{
// Initialize validation key if not already initialized
if (_ValidationKey == null)
_ValidationKey = GetValidationKey ();
// Register handlers for BeginRequest and EndRequest events
app.BeginRequest += new EventHandler (OnBeginRequest);
app.EndRequest += new EventHandler (OnEndRequest);
}
public void Dispose () {}
void OnBeginRequest (Object sender, EventArgs e)
{
// Look for an incoming cookie named "ASP.NET_SessionID"
HttpRequest request = ((HttpApplication) sender).Request;
HttpCookie cookie = GetCookie (request, "ASP.NET_SessionId");
if (cookie != null) {
// Throw an exception if the cookie lacks a MAC
if (cookie.Value.Length <= 24)
throw new InvalidSessionException
("Access Denied"); // don't tell bad guys too much
// Separate the session ID and the MAC
string id = cookie.Value.Substring (0, 24);
string mac1 = cookie.Value.Substring (24);
// Generate a new MAC from the session ID and requestor info
string mac2 = GetSessionIDMac (id, request.UserHostAddress,
request.UserAgent, _ValidationKey);
// Throw an exception if the MACs don't match
if (String.CompareOrdinal (mac1, mac2) != 0)
throw new InvalidSessionException
("Access Denied"); // don't tell bad guys too much
// Strip the MAC from the cookie before ASP.NET sees it
cookie.Value = id;
}
}
void OnEndRequest (Object sender, EventArgs e)
{
// Look for an outgoing cookie named "ASP.NET_SessionID"
HttpRequest request = ((HttpApplication) sender).Request;
HttpCookie cookie = GetCookie (
((HttpApplication) sender).Response, "ASP.NET_SessionId");
if (cookie != null) {
// Add a MAC
cookie.Value += GetSessionIDMac (cookie.Value,
request.UserHostAddress, request.UserAgent,
_ValidationKey);
}
}
private string GetValidationKey ()
{
string key = ConfigurationSettings.AppSettings
["SessionValidationKey"];
if (key == null || key == String.Empty)
throw new InvalidSessionException
("SessionValidationKey missing");
return key;
}
private HttpCookie GetCookie (HttpRequest request, string name)
{
HttpCookieCollection cookies = request.Cookies;
return FindCookie (cookies, name);
}
private HttpCookie GetCookie (HttpResponse response, string name)
{
HttpCookieCollection cookies = response.Cookies;
return FindCookie (cookies, name);
}
private HttpCookie FindCookie (HttpCookieCollection cookies,
string name)
{
int count = cookies.Count;
for (int i=0; i<count; i++) {
if (String.Compare (cookies[i].Name, name, true,
CultureInfo.InvariantCulture) == 0)
return cookies[i];
}
return null;
}
private string GetSessionIDMac (string id, string ip,
string agent, string key)
{
StringBuilder builder = new StringBuilder (id, 512);
builder.Append (ip.Substring (0, ip.IndexOf ('.',
ip.IndexOf ('.') + 1)));
builder.Append (agent);
using (HMACSHA1 hmac = new HMACSHA1
(Encoding.UTF8.GetBytes (key))) {
return Convert.ToBase64String (hmac.ComputeHash
(Encoding.UTF8.GetBytes (builder.ToString ())));
}
}
}
[Serializable]
public class InvalidSessionException : Exception
{
public InvalidSessionException () :
base ("Session cookie is invalid") {}
public InvalidSessionException (string message) :
base (message) {}
public InvalidSessionException (string message,
Exception inner) : base (message, inner) {}
protected InvalidSessionException (SerializationInfo info,
StreamingContext context) : base (info, context) {}
}
Figure 2 shows
how SecureSessionModule works. First, it checks every outgoing response
for a session ID cookie issued by ASP.NET's SessionStateModule. When it
sees such a cookie, SecureSessionModule modifies it by appending a
hashed message authentication code (MAC) to the session ID. The MAC is
generated from the session ID, the network address portion of the
requestor's IP address (for example, the 192.16 in 192.16.0.14), the
User-Agent header received in the request, and a secret key stored on
the server. The Framework's System.Security.Cryptography.HMACSHA1 class
makes the task of generating the MAC really quite easy.Why use the
network address instead of the full IP address? The node address of
users that access the Internet through public proxy servers such as
AOL's can change in every request, but the network address should not.
Figure 2 SecureSessionModule
Second,
SecureSessionModule examines every incoming request for an ASP.NET
session ID cookie. Before allowing a request containing a session ID
cookie to continue through the pipeline, SecureSessionModule validates
the cookie by regenerating the MAC from the requestor's IP address, the
User-Agent header, and the secret key. If the freshly computed MAC
matches the one in the cookie, the MAC is stripped from the cookie and
the request is allowed to proceed. If the MACs don't match,
SecureSessionModule throws an InvalidSessionException, as shown in Figure 3.
The net result is that once a
session ID cookie is issued, it's only considered valid if it's
submitted from the same network address and with the same User-Agent
header. An attacker who steals a session ID cookie can only use it if
she can spoof IP addresses and HTTP headers. Both are certainly
possible, but spoofing of this sort requires a higher skill level on the
part of the attacker. In addition, getting a response back from a
request with a spoofed IP address is much harder than simply submitting
the request in the first place and can be defeated with proper egress
filtering. It's impossible for the attacker to simply replace the hash
in the cookie with one generated from her own IP address and User-Agent
header without the secret key used to generate the MAC. To the extent
that the key can be secured, casual hackers will find it difficult
indeed to use stolen session IDs for nefarious purposes.
Deploying SecureSessionModule
Deploying
SecureSessionModule is as simple as copying SecureSessionModule.dll
into the application root's bin subdirectory and registering it in
Web.config, like so:
<configuration>
<appSettings>
<add key="SessionValidationKey"
value="DAD4D476F80E0148BCD134D7AA5C61D7" />
</appSettings>
<system.web>
<httpModules>
<add name="SecureSession"
type="SecureSessionModule,
SecureSessionModule" />
</httpModules>
</system.web>
</configuration>
The SessionValidationKey value in the <appSettings> section of
Web.config is required. This is the "secret key" used to generate the
MAC; SecureSessionModule looks for it at load time and throws an
exception if it's not there. The key should be unique for every
application, and it should be long and random. I used a simple tool
built around the .NET Framework RNGCryptoServiceProvider class to
generate the one in Figure 3. You should use a similar
tool to maximize randomness. In addition, if deployed on a Web farm,
SessionValidationKey should be the same on every server. Of course,
storing plaintext security keys in configuration files poses risks of
its own. For an added measure of security, consider encrypting the
secret key. The article at Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication describes how to use the Windows®
Data Protection API (DPAPI) from ASP.NET. DPAPI is ideal for encrypting
secrets in configuration files because it offloads the problem of key
management—specifically, storing decryption keys—to the operating system
itself.
Ideally,
SecureSessionModule would use the same secret key that ASP.NET uses for
hashing: the value of the validationKey attribute in Machine.config's
<machineKey> element. However, there is no public API for
retrieving this key, and after inspecting what the Framework does to
retrieve validationKey, I elected not to duplicate the logic in the
Framework to avoid potential incompatibilities with future versions of
.NET. The new configuration API coming in version 2.0 of the .NET
Framework will correct this omission and provide a documented means for
reading the ASP.NET validation key.
Once
deployed, SecureSessionModule works passively—no intervention is
required. If you'd like, include an Application_Error method in
Global.asax to log InvalidSessionExceptions in the Windows event log or
elsewhere. That way you can check the log every morning over your first
cup of coffee and find out if someone has been trying to spoof your
server with stolen session IDs. Such a method might look like this:
<%@ Import Namespace="System.Diagnostics" %>
<script language="C#" runat="server">
void Application_Error(Object sender, EventArgs e)
{
// Write an entry to the event log
EventLog log = new EventLog ();
log.Source = "My ASP.NET Application";
log.WriteEntry (Server.GetLastError().ToString(),
EventLogEntryType.Error);
}
</script>
Caveats
Before deploying SecureSessionModule on a production Web server, you should consider several potential issues.
First,
SecureSessionModule is not 100 percent effective in detecting illicit
session ID cookies. If the attacker has the same network address as the
victim (if both, for example, use the same proxy server) or can spoof
the victim's network address, then User-Agent headers are the last line
of defense. And User-Agent headers are easily spoofed by someone aware
that User-Agent headers are being used to validate session IDs.
Second,
if for some reason a user's network address or User-Agent headers vary
from request to request, that user will lose access to her session
state. Third, SecureSessionModule doesn't work with cookieless session
state. It assumes session IDs are passed in cookies, not URLs.
Finally,
SecureSessionModule hasn't been tested in a production environment. If
you use it, I'd love to hear from you—especially about any glitches that
arise. Note that Microsoft has considered building similar protections
into ASP.NET, but has always shied away from it for backward
compatibility concerns.
Conclusion
Session
hijacking remains a serious threat to security. SecureSessionModule
raises the bar for hackers who hijack sessions using stolen session IDs
by factoring evidence about the session owner into the session ID
cookie. That evidence isn't conclusive because neither network addresses
nor User-Agent headers can be used reliably to distinguish one user
from another, but it nonetheless places an additional hurdle in the path
of hackers who are actively seeking to compromise your Web servers by
connecting to other users' sessions and grabbing their data.
@@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT
SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record
March 25, 2007 by pinaldave
SELECT @@IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(‘tablename’)
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
To avoid the potential problems
associated with adding a trigger later on, always use SCOPE_IDENTITY()
to return the identity of the recently added row in your T SQL Statement
or Stored Procedure.
best practice for trigger
Table of Contents
- Overview
- What is a Trigger?
- Why Use Triggers?
- Creating and Using a Trigger
- Types of Trigger
- Good Practice
- Conclusion
- History
Overview
Implementing business rules as well as performing validation or data modifications, triggers are the best use for this purpose when other methods are not sufficient. Triggers are normally used in two areas: creating audit records and reflecting changes to crucial business tables, and validating changes against a set of business rules coded in T-SQL.In this article, I would like to demonstrate how to create triggers, use of triggers, different types of triggers and performance considerations.
What is a Trigger?
A database trigger is a stored procedure that is invoked automatically when a predefined event occurs. Database triggers enable DBAs (Data Base Administrators) to create additional relationships between separate databases. In other ways, a trigger can be defined to execute before or after anINSERT, UPDATE, or DELETE operation,
either once per modified row, or once per SQL statement. If a trigger
event occurs, the trigger's function is called at the appropriate time
to handle the event. Triggers can be assigned to tables or views. However, although there are two types of triggers,
INSTEAD OF and AFTER, only one type of trigger can be assigned to views. An INSTEAD OF trigger is the one that is usually associated with a view, and runs on an UPDATE action placed on that view. An AFTER trigger fires after a modification action has occurred.From a performance viewpoint, the fewer the triggers, the better, as we will invoke less processes. Therefore, do not think that having one trigger per action to make things modular will not incur performance degradation. A trigger's main overhead is referencing either two specialist tables that exist in triggers – deleted and inserted or other tables for business rules. Modularizing triggers to make the whole process easier to understand will incur multiple references to these tables, and hence a greater overhead.
Note: It is not possible to create a trigger to fire when a data modification occurs in two or more tables. A trigger can be associated only with a single table.
Why Use Triggers?
To improve data integrity, trigger can be used. When an action is performed on data, it is possible to check if the manipulation of the data concurs with the underlying business rules, and thus avoids erroneous entries in a table. For example:- We might want to ship a free item to a client with the order, if it totals more than $1000. A trigger will be built to check the order total upon completion of the order, to see if an extra order line needs to be inserted.
- In a banking scenario, when a request is made to withdraw cash from a cash point, the stored procedure will create a record on the client's statement table for the withdrawal, and the trigger will automatically reduce the balance as required. The trigger may also be the point at which a check is made on the client's balance to verify that there is enough balance to allow the withdrawal. By having a trigger on the statement table, we are secure in the knowledge that any statement entry made, whether withdrawal or deposit, will be validated and processed in one central place.
Another use of triggers can be to carry out an action when a specific criterion has been met. One example of this is a case where an e-mail requesting more items to be delivered is sent, or an order for processing could be placed, when stock levels reach a preset level. However, if we
insert data into another table from within a trigger,
we have to be careful that the table we insert into doesn't have a
trigger that will cause this first trigger to fire. It is possible to
code triggers that result in an endless loop, as we can define a trigger on TableA, which inserts into TableB, and a trigger for TableB, which updates TableA. This scenario will ultimately end in an error being generated by the SQL Server. The following diagram will demonstrate this:
Figure 1
- A stored procedure,
A, updatesTableA. - This fires a trigger from
TableA. - The defined trigger on
TableAupdatesTableB. TableBhas a trigger which fires.- This trigger from
TableBupdatesTableA.
Creating and Using a Trigger
A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events areINSERT, UPDATE, or DELETE statements on a table or view. More details can be found at this link.CREATE TRIGGER Statement
TheCREATE TRIGGER statement defines a trigger in the database. Invocation
This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared only if DYNAMICRULES run behavior is in effect for the package (SQLSTATE 42509).Authorization
The privileges held by the authorization ID of the statement must include at least one of the following:ALTERprivilege on the table on which theBEFOREorAFTERtrigger is definedCONTROLprivilege on the view on which theINSTEAD OFTRIGGER is defined- Definer of the view on which the
INSTEAD OFtrigger is defined ALTERINprivilege on the schema of the table or view on which the trigger is definedSYSADMorDBADMauthority and one of:IMPLICIT_SCHEMAauthority on the database, if the implicit or explicit schema name of the trigger does not existCREATEINprivilege on the schema, if the schema name of the trigger refers to an existing schema
SYSADM authority, the definer is granted explicit DBADM authority for the purpose of creating the trigger. Syntax of a Trigger
CREATE TRIGGER name ON table
[WITH ENCRYPTION]
[FOR/AFTER/INSTEAD OF]
[INSERT, UPDATE, DELETE]
[NOT FOR REPLICATION]
AS
BEGIN
--SQL statements
...
END
Sample Example
Let’s take an example. We have a table with some columns. Our goal is to create aTRIGGER which
will be fired on every modification of data in each column and track
the number of modifications of that column. The sample example is given
below:-- ==========================================================
-- Author: Md. Marufuzzaman
-- Create date:
-- Description: Alter count for any modification
-- ===========================================================
CREATE TRIGGER [TRIGGER_ALTER_COUNT] ON [dbo].[tblTriggerExample]
FOR INSERT, UPDATE
AS
BEGIN
DECLARE @TransID VARCHAR(36)
SELECT @TransID = TransactionID FROM INSERTED
UPDATE [dbo].[tblTriggerExample] SET AlterCount = AlterCount + 1
,LastUpdate = GETDATE()
WHERE TransactionID = @TransID
END
Figure 2 (SQL table)
Types of Triggers
There are three main types of triggers that fire onINSERT, DELETE, or UPDATE actions. Like stored procedures, these can also be encrypted for extra security. More details can be found at this link.Good Practice
The most important point is to keep the trigger as short as possible to execute quickly, just like stored procedures. The longer a trigger takes to fire, the longer the locks will be held on the underlying tables. To this end, we could place cursors within a trigger, but good practice dictates that we don't. Cursors are not the fastest of objects within a database, and we should try and revisit the problem with a different solution, if we feel the need for cursors. One way around the problem may be to run two, or perhaps, three updates, or even use a temporary table instead.Use triggers to enforce business rules, or to complete actions that have either a positive effect on the organization, or if an action will stop problems with the system. An example of this is creation of a trigger that will e-mail a client when an order is about to be shipped, giving details of the order, and so on.
Note: Use an
@@ROWCOUNT, where required, to check the number of rows that have been affected.
Saturday, June 16, 2012
best practice for stored procedure
SQL SERVER – Stored Procedure Optimization Tips – Best Practices
- Include SET NOCOUNT ON statement: With every SELECT and DML statement, the SQL server returns a message that indicates the number of affected rows by that statement. This information is mostly helpful in debugging the code, but it is useless after that. By setting SET NOCOUNT ON, we can disable the feature of returning this extra information. For stored procedures that contain several statements or contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost because network traffic is greatly reduced.
CREATE PROC dbo.ProcName
AS
SET NOCOUNT ON;
--Procedure code here
SELECT column1 FROM dbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO - Use schema name with object name: The object name is qualified if used with schema name. Schema name should be used with the stored procedure name and with all objects referenced inside the stored procedure. This helps in directly finding the complied plan instead of searching the objects in other possible schema before finally deciding to use a cached plan, if available. This process of searching and deciding a schema for an object leads to COMPILE lock on stored procedure and decreases the stored procedure’s performance. Therefore, always refer the objects with qualified name in the stored procedure like
SELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method- Do not use the prefix “sp_” in the stored procedure name: If a stored procedure name begins with “SP_,” then SQL server first searches in the master database and then in the current session database. Searching in the master database causes extra overhead and even a wrong result if another stored procedure with the same name is found in master database.
- Use IF EXISTS (SELECT 1) instead of (SELECT *): To check the existence of a record in another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any value is returned from an internal statement, either a single value “1” or all columns of a record or complete recordset. The output of the internal statement is not used. Hence, to minimize the data for processing and network transferring, we should use “1” in the SELECT clause of an internal statement, as shown below:
IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type = 'U') - Use the sp_executesql stored procedure instead of the EXECUTE statement.
The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve the re-usability of your code. The execution plan of a dynamic statement can be reused only if each and every character, including case, space, comments and parameter, is same for two statements. For example, if we execute the below batch:
DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET @Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' + CONVERT(VARCHAR(3),@Age)
EXEC (@Query)
If we again execute the above batch using
different @Age value, then the execution plan for SELECT statement
created for @Age =25 would not be reused. However, if we write the above
batch as given below,
DECLARE @Query NVARCHAR(100)
SET @Query = N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25
the compiled plan of this SELECT
statement will be reused for different value of @Age parameter. The
reuse of the existing complied plan will result in improved performance.
- Try to avoid using SQL Server cursors whenever possible: Cursor uses a lot of resources for overhead processing to maintain current record position in a recordset and this decreases the performance. If we need to process records one-by-one in a loop, then we should use the WHILE clause. Wherever possible, we should replace the cursor-based approach with SET-based approach. Because the SQL Server engine is designed and optimized to perform SET-based operation very fast. Again, please note cursor is also a kind of WHILE Loop.
- Keep the Transaction as short as possible: The length of transaction affects blocking and deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation level, the shared locks are also aged with transaction. Therefore, lengthy transaction means locks for longer time and locks for longer time turns into blocking. In some cases, blocking also converts into deadlocks. So, for faster execution and less blocking, the transaction should be kept as short as possible.
- Use TRY-Catch for error handling: Prior to SQL server 2005 version code for error handling, there was a big portion of actual code because an error check statement was written after every t-sql statement. More code always consumes more resources and time. In SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as follows:
BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH - Disable parameter sniffing: U
se local variable instead of parameter directly.
Friday, May 25, 2012
Create a Self Signed Certificate in IIS 7
How to Create a Self Signed Certificate in IIS 7
SSL is an essential part of securing your IIS 7.0 site and creating a self-signed certificate in IIS 7 is much easier to do than in previous versions of IIS. SSL certificates enable the encryption of all traffic sent to and from your IIS web site, preventing others from viewing sensitive information. It uses public key cryptography to establish a secure connection. This means that anything encrypted with a public key (the SSL certificate) can only be decrypted with the private key and vice versa.When to Use an IIS Self Signed Certificate
Never use a self signed certificate on an e-commerce site or any site that transfers valuable personal information like credit cards, social security numbers, etc.An SSL certificate has multiple purposes: distributing the public key and, when signed by a trusted third-party, verifying the identity of the server so clients know they aren’t sending their information (encrypted or not) to the wrong person. A self signed certificate is a certificate that is signed by itself rather than a trusted third party. This means you can't verify that you are connecting to the right server because any attacker can create a self signed certificate and launch a man-in-the-middle attack. Because of this, you should almost never use a self signed certificate on a public IIS server that requires anonymous visitors to connect to your site. However, self signed certificates can be appropriate in certain situations:
- Self signed certificates can be used on an intranet. When clients only have to go through a local intranet to get to the server, there is virtually no chance of a man-in-the-middle attack.
- Self signed certificates can be used on an IIS development server. There is no need to spend extra cash buying a trusted certificate when you are just developing or testing an application.
- Self signed certificates can be used on personal sites with few visitors. If you have a small personal site that transfers non-critical information, there is very little incentive for someone to attack the connection.
Generate Your IIS Self Signed Certificate
Now you know when to use an IIS self signed certificate and when not to. Now let’s create one: (Click here to hide or show the images)- Click on the Start menu, go to Administrative Tools, and click on Internet Information Services (IIS) Manager.
- Click on the name of the server in the Connections column on the left. Double-click on Server Certificates.
- In the Actions column on the right, click on Create Self-Signed Certificate...
- Enter any friendly name and then click OK.
- You will now have an IIS Self Signed Certificate valid for 1
year listed under Server Certificates. The certificate common name
(Issued To) is the server name. Now we just need to bind the Self signed
certificate to the IIS site.
Bind the Self Signed Certificate
- In the Connections column on the left, expand the sites folder
and click on the website that you want to bind the certificate to. Click
on Bindings... in the right column.
- Click on the Add... button.
- Change the Type to https and then select the SSL certificate that you just installed. Click OK.
- You will now see the binding for port 443 listed. Click Close.
- Now let's test the IIS self signed certificate by going to the
site with https in our browser (e.g. https://site1.mydomain.com). When
you do, you should see the following warning stating that "The security
certificate presented by this website was issued for a different
website's address" (a name mismatch error).
This is displayed because IIS always uses the server's name (in this case WIN-PABODPHV6W3) as the common name when it creates a self signed certificate. This typically doesn't match the hostname that you use to access the site in your browser (site1.mydomain.com). For many situations where IIS self signed certificates are used, this isn't a problem. Just click "Continue to this web site" each time. However, if you want to completely get rid of the error messages, you'll need to follow the next two steps below.
Generate a Self Signed Certificate with the Correct Common Name
This step is only required if you want to get rid of the warning message displayed because the common name on the self signed certificate doesn't match the website's hostname. In order to resolve this problem, we'll need to create the self signed certificate using the same method that is used to create a self signed certificate in IIS 6.0 (with SelfSSL instead of through IIS).- Download the Internet Information Services (IIS) 6.0 Resource Kit Tools
and install SelfSSL 1.0 (if you do a Custom install you can uncheck
everything except for SelfSSL). Once it is installed, click on the Start
menu, go to IIS Resources, then SelfSSL, and run SelfSSL.
- Paste in the following command and replace site1.mydomain.com
with the hostname of your IIS site. If you receive the erorr "Error
opening metabase: 0x80040154", just ignore it. We will be manually
binding the certificate to the website.
SelfSSL /N:CN=site1.mydomain.com /V:1000 - After the command is finished, you will have an IIS self signed
certificate with the correct common name listed in the Server
Certificates section of IIS. Now follow the instructions above to bind the certificate to your IIS website.
- After you have bound the new certificate to your IIS site, visit
it with https in your web browser and you will encounter another error:
"The security certificate presented by this website was not issued by a
trusted certificate authority." (the SSL Certificate Not Trusted error)
Don't worry; this is the last error we will need to fix. This is a normal error for self signed certificates because the certificate is signed by itself instead of a trusted SSL provider. All visitors to the site will see that error unless they import the self-signed certificate into their Trusted Root Certification Authorities store (or the appropriate SSL certificate store for the browser they are using). You can easily add the IIS self signed certificate to the store on the server by following the the instructions below. If you need to import the certificate on another Windows machine, just follow the instructions on how to Move or copy an SSL certificate from a Windows server.
Add the Self Signed Certificate to Trusted Root Certificate Authorities
- Click on the Start menu and click Run.
- Type in mmc and click OK.
- Click on the File menu and click Add/Remove Snap-in...
- Double-click on Certificates.
- Click on Computer Account and click Next.
- Leave Local Computer selected and click Finish.
- Expand the Certificates item on the left and expand the Personal
folder. Click on the Certificates folder and right-click on the self
signed certificate that you just created and select Copy.
- Expand the Trusted Root Certification Authorities folder and
click the Certificates folder underneath it. Right-click in the white
area below the certificates and click Paste.
- Now you can visit your site with https in your web browser and
you shouldn't receive any errors because Windows will now automatically
trust your IIS self signed certificate.
- Installing an SSL Certificate in Windows Server 2008 (IIS 7.0)
- Tip/Trick: Enabling SSL on IIS 7.0 Using Self-Signed Certificates
- IIS Self Signed Certificates on IIS 7 – the Easy Way and the Most Effective Way
Bryan Bowers
Posts: 15
Posts: 15
Reply #16 on : Mon April 30, 2012, 15:35:16
Hi all, I followed the process (even ran as
administrator) but the cert does not show up in the IIS MMC. Any
ideas? I get a failed to build the subject name blob: 0x80092023.
Would appreciate any help as client is antsy for the fix.
Robert
Posts: 2
Posts: 2
Reply #15 on : Fri April 27, 2012, 07:25:20
Hi Rix,
Unfortunately, that is the nature of self-signed certificates. Because they are signed by themselves, they can't be trusted until the user actively sets them to be trusted (this is fairly easy in Firefox but more difficult in other browsers). To completely avoid warnings and manual trust process, you'll need to get a certificate from a trusted authority.
Unfortunately, that is the nature of self-signed certificates. Because they are signed by themselves, they can't be trusted until the user actively sets them to be trusted (this is fairly easy in Firefox but more difficult in other browsers). To completely avoid warnings and manual trust process, you'll need to get a certificate from a trusted authority.
Rix
Posts: 15
Posts: 15
Reply #14 on : Fri April 27, 2012, 00:49:29
I have followed all the steps but clients still get
"The security certificate presented by this website was not issued by a trusted certificate authority."
Clients DID NOT import the self signed certificate, yet because I would like to avoid this. I don't want to force people to follow the bulky certification import steps, I just want them to navigate easily! So my question is: is there a way to allow the self signed certificate to be recognized as valid WITHOUT importing in in the client trusted root store?
"The security certificate presented by this website was not issued by a trusted certificate authority."
Clients DID NOT import the self signed certificate, yet because I would like to avoid this. I don't want to force people to follow the bulky certification import steps, I just want them to navigate easily! So my question is: is there a way to allow the self signed certificate to be recognized as valid WITHOUT importing in in the client trusted root store?
Ted
Posts: 15
Posts: 15
Reply #13 on : Fri January 20, 2012, 16:07:51
Thank you!!!
Mithun Kanji
Posts: 15
Posts: 15
Reply #12 on : Mon January 16, 2012, 04:32:11
Thx mate...The instructions were clear and well written...
Jeff
Posts: 15
Posts: 15
Reply #11 on : Mon December 12, 2011, 17:45:38
Remember to open cmd with administrator
rights, if it's doing nothing more than likely it's because you are not
running as administrator. remember even if you're logged in as
administrator, you still have to run as administrator.
Robert
Posts: 2
Posts: 2
Reply #10 on : Fri December 09, 2011, 06:39:09
Thanks, Mo. I fixed the email address validation issue.
Mo
Posts: 15
Posts: 15
Reply #9 on : Mon November 28, 2011, 09:29:32
Also, this comment form is refusing to
accept valid email addresses. My standard email address has a "+" in the
mailbox name component, so I had to use an alternate.
Mo
Posts: 15
Posts: 15
Reply #8 on : Mon November 28, 2011, 09:24:31
As far as I can tell, I followed the
instructions above to the letter, but when I run the SelfSSL command,
nothing changes in my Server Certificates screen. I still have the old
certificate with the wrong hostname, and I don't have a certificate with
the correct hostname. Also, SelfSSL doesn't give me the "Error opening
metabase" warning, but it doesn't complain about anything else, either.
After asking me Y/N, it just goes back to the command prompt.
DPK
Posts: 15
Posts: 15
Reply #7 on : Fri November 18, 2011, 00:56:32
Very comprehensive. Just what I was looking for!
Amy Hsu
Posts: 15
Posts: 15
Reply #6 on : Thu September 29, 2011, 15:14:51
Spend lots time on it. Really helps. Thanks.
Anthony Garrett
Posts: 15
Posts: 15
Reply #5 on : Mon June 20, 2011, 12:46:52
Thanks for putting this together... all the
information I needed. I did have to modify it a tiny bit to cope with
my site not having the default ID but that's very simple with SelfSSL.
All nicely working with IE, FF, Opera & Chrome (after various approval processes) but still having problems with Safari(Win) failing to recognise the presence of the certificate.
Thanks again.
All nicely working with IE, FF, Opera & Chrome (after various approval processes) but still having problems with Safari(Win) failing to recognise the presence of the certificate.
Thanks again.
Nicogis
Posts: 15
Posts: 15
Reply #4 on : Tue April 12, 2011, 11:01:02
you can use in selfssl.exe the argument /T for add the self-signed certificate to trusted certificates
Nelson
Posts: 15
Posts: 15
Reply #3 on : Thu April 07, 2011, 09:49:21
Just what I was looking for. Thanks!
Eugene Honor
Posts: 15
Posts: 15
Reply #2 on : Fri April 01, 2011, 08:30:27
simple and direct approach has been provided with this tips.. thanks...
Clive Nicholson
Posts: 15
Posts: 15
Reply #1 on : Mon February 14, 2011, 06:10:57
Well written , accurate and fixed my local issue
Thanks very much!
Thanks very much!
Subscribe to:
Posts (Atom)
Reply #17 on : Fri May 04, 2012, 01:33:18