Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET Hosting - ASPHostPortal.com :: How to Bind Data to a Label From a SqlDataSource

clock April 25, 2016 21:24 by author Dan

Label controls in ASP.NET don't have a smart tag that allows you to select a data source, so at first glance, it is not easy to see how to bind a value returned from a SqlDataSource or AccessDataSource control to the label. Here's how to programmatically access the data returned by such a DataSource and apply it to a non-databound control.

To programmatically access the contents of a SqlDataSource or AccessDataSource control you need to explicitly call its Select() method. This method accepts a single input parameter of type DataSourceSelectArguments. This parameter can contain information regarding the filters to apply or the column to Order By. For example, when working with a sortable GridView, sorting a column calls the Select() method, and passes in a DataSourceSelectArguments instance with its SortExpression property set to the column name the user chose to sort by. If you don't want the DataSource to sort or filter, you pass in DataSourceSelectArguments.Empty.

Depending on the DataSourceMode of the DataSource control, one of two objects are returned when the Select() method is called. If the DataSourceMode is set to DataReader, a DataReader object is returned. The type of DataReader (SqlDataReader, OleDbDataReader, OdbcDataReader etc) that is returned depends entirely on the provider type used - in other words, whether you are using the OleDb provider, SqlClient provider etc. It has nothing to do with the type of DataSource control. The examples below both query an Access database, but one uses the AccessDataSource control, and the other uses the SqlDataSource control. Both return OleDbDataReaders, because it is the OleDbProvider library that is used for the connection.

If the DataSourceMode is set to Dataset, or not set at all (which means that the default setting of Dataset is used) the object that is returned is a DataView. A DataView is like a DataTable on steroids. It exposes methods that allow you to filter and sort data, for example, and bind it. A DataView contains a collection of DataRowView objects, which represent each row in the returned results.

So, with a DataReader, you would access the values during the DataReader.Read() operation, in very much the same way as if you are using plain ADO.NET code, whereas with the DataSet, you would need to create an object of the appropriate type - DataView, then iterate the DataRowView collection to access the values. In this, the code is remarkably similar to accessing values directly from a DataSet's table collection using plain ADO.NET.

The code below shows the contents of an aspx file, which contains two label controls, and two SqlDataSource controls. Each SqlDataSource control has its DataSource mode set to alternative values - DataSet and DataReader, and both of them have an OnSelecting event defined in which the value of the EmployeeID parameter is assigned:

<asp:Label ID="Label1" runat="server" /> <asp:Label ID="Label2" runat="server" />

<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataSet"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource
    ID="SqlDataSource2"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataReader"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource2_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>


The following code snippet shows the aspx.cs file contents, where the parameter values are set in the Selecting event handler. In the Page_Load method, the data returned by each of the Sql DataSource controls is accessed and a value consigned to a label. The method of access depends on the DataSource mode, but is identical for both SqlDataSource and AccessDataSource:

[C#]
protected void Page_Load(object sender, EventArgs e)
{

    DataView dvSql = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    foreach (DataRowView drvSql in dvSql)
    {
        Label1.Text = drvSql["FirstName"].ToString();
    }

    OleDbDataReader rdrSql = (OleDbDataReader)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
    while (rdrSql.Read())
    {
        Label2.Text = rdrSql["LastName"].ToString();

    }
    rdrSql.Close();
}



protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

[VB]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim dvSql As DataView =
    DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    For Each drvSql As DataRowView In dvSql
        Label1.Text = drvSql("FirstName").ToString()
    Next

Dim rdrSql As OleDbDataReader =
    DirectCast(SqlDataSource2.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
    While rdrSql.Read()

        Label2.Text = rdrSql("LastName").ToString()
    End While
    rdrSql.Close()
End Sub

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub

Protected Sub SqlDataSource2_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub


When using this technique with Sql Server - or more specifically the SqlClient provider, change OleDbDataReader to SqlDataReader in the above code. Happy Coding.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to solve page html getting wrongly appended to file being downloaded

clock April 18, 2016 21:24 by author Dan

Today while writing a small web application where I needed to download a datatable as csv file. I faced issue of page html getting wrongly appended to file being downloaded. I was using Response.Write to download file on client machine.

Solution to my problem was easy, I just needed to add an extra line telling content-length. Below is method that I finally ended up using.

        private void DownloadDataAsCsv(DataTable dt)
        {
            string tab = "";
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append(tab + dc.ColumnName);
                tab = ",";
            }
            sb.Append("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(tab + dr[i].ToString());
                    tab = ",";
                }
                sb.Append("\n");
            }
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.AddHeader("Content-Length", sb.ToString().Length.ToString());
            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com : Paging with ASP.NET Web API OData

clock October 20, 2015 08:58 by author Kenny

Paging with ASP.NET Web API OData

What is OData?

OData, short for Open Data Protocol, defines a protocol for the querying and updating of data utilizing existing Web protocols. OData is a REST-based protocol for querying and updating data and is built on standardized technologies such as HTTP, Atom/XML, and JSON. It is different from other REST-based web services in that it provides a uniform way to describe both the data and the data model. It is considered to be a flexible technology for enabling interoperability between disparate data sources, applications, services and clients.

Step by Step

When the API call returns the list of repositories in the body of the response as a JSON array:

[
  {
    "id": 1234,
    "name": "domain.com",
    "full_name": "user/domain.com",
    ...
  },
  {
    "id": 1111,
    "name": "test",
    "full_name": "user/test",
    ...
  }
]

It does not state the total number of records anywhere in the resulting JSON, not does it return the current page or the number of records per page which you requested. What it does however is to return the pagination information in the Link header of the request. So in the case of my API call above it returns the following Link header:

Link: <https://api.github.com/user/repos?page=5&per_page=2>; rel="next",
      <https://api.github.com/user/repos?page=8&per_page=2>; rel="last",
      <https://api.github.com/user/repos?page=1&per_page=2>; rel="first",
      <https://api.github.com/user/repos?page=3&per_page=2>; rel="prev"

So it allows you to request subsequent pages by requesting the URL in the Link header with the relation type (rel parameter value) of “next”. Also to get the total number of pages you will need to extract the page query parameter from the link with the relation type of last.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET MVC 4 Hosting - ASPHostPortal.com :: A Best Practice for Authenticating Users in ASP.NET MVC 4

clock December 20, 2013 06:16 by author Robert

If your site has even one or two actions where access is restricted to particular users, the smart thing to do is to restrict access to all the actions on your site and then selectively permit access to those actions that all users are allowed to request. That way, an error of omission (forgetting to make a method available) simply prevents users from accessing some action.

Unfortunately, by default ASP.NET MVC works exactly the opposite way: all actions are accessible to all users unless you specifically restrict access by applying the Authorization action filter to the method. Under this scenario, an error of omission (forgetting to put an Authorize attribute on a method) allows all users access to the action. It's literally the worst thing that can happen in a secure environment: unauthenticated and unauthorized access to a resource that should have been secured.

Global Filters provided a solution to this by allowing you to apply the Authorize attribute to all of your action methods, locking non-authenticated users out of your actions by default. You can then selectively override that setting by applying the Authorize attribute to individual methods, specifying specific roles and users authorized to use that action. That works, unless you have some action methods that don't require authentication, methods intended to be accessible to the general public. In that scenario, you can't use Global Filters to secure all of your action methods -- until ASP.NET MVC 4.

Implementing the best practice is possible in ASP.NET MVC 4 with the new AllowAnonymous action filter. The first step is to use the Global Filters in the FilterConfig class in the App_Start folder to apply the Authorize attribute to every action method:

public class FilterConfig
{
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
    filters.Add(new AuthorizeAttribute);
  }
}


The next step is to selectively allow access to actions that don't require authentication by decorating them with the AllowAnonymous attribute:

[AllowAnonymous]
Public ActionResult Get()
{

 



ASP.NET Hosting - IIS 7.5 Hosting - ASPHostPortal.com :: Configure Costum Error in IIS 7.5 With ASP.NET

clock September 21, 2013 09:17 by author Ben

Now, I will explain how to configure custom error pages in IIS (Internet Information Service). For this example we will be using IIS 7.5 which shipped with Windows Server 2008 R2.

First Step, Open Internet Information Services (IIS) Manager.  Select your website. Note: This could also be set at the server level and applied to all sites on the server. DoubleClick on the “.NET Error Pages” icon.


The .NET Error Pages features view will be displayed.


Click the “Edit Feature Settings” link to enable this feature. The “Edit Error Page Settings” dialog box will appear.


How to determine the error code 404 explicitly..

First, On the .NET Error Pages Actions menu click the Add link.


The “Add Custom Error Page” dialog will appear. This is where we define individual error pages per status code. For our example we will add a custom page for the HTTP 404 Error.




Now that we have turned on the feature and added a custom page for the 404 status code we can verify it is working. Please reload your website.

As mentioned above this can also be managed from the site’s web.config file. Consider the following configuration section from our site’s web.config file.



ASP.NET MVC 4 Hosting - ASPHostPortal :: Build Mobile Applications With ASP.NET MVC 4.5

clock August 20, 2013 05:56 by author Ben

The MVC 4 release is building on a pretty mature base and is able to focus on some more advanced scenarios. Some top features include:

  • ASP.NET Web API
  • Enhancements to default project templates
  • Mobile project template using jQuery Mobile
  • Display Modes
  • Task support for Asynchronous Controllers
  • Bundling and minification

The following sections provide an overview of these features. We’ll be going into them in more detail throughout the book.
Developing MVC 4 applications with Visual Studio 2011 Developers Preview is quite jump-start for developers as it has inbuilt support for JQuery Mobile css & javascripts, nice intellisense for HTML 5 , CSS 3 media queries. MVC 4 developers preview was built keeping in mind the Mobile Web Developers who wants keen support of rich MVC in Mobile Web.

  • Lets start to develop MVC 4 mobile application with JQuery Mobile, HTML5, CSS3 in VS 2011 developers preview.

  • Select your MVC 4 application domain either Internet/Intranet/Mobile Web application  with default Razor or ASPX syntaxes. For my demo , selected Mobile Web application in VS 2011 Developer Preview.

  • Next, write some JQuery Mobile application code to check th UI view in SmartPhones while Model & Controller logic remains same & could change according to business requirements.
  • Database -> Entity Framework (EF) -> Model in MVC 4(Entities) (DAL)-> Controllers (Business Logic Layer)(BLL) -> View(s) -> Master(_Layout.cshtml) is the default development path in MVC 4 Web & mobile application.

  • Next , Check the nice intellisense support for HTML5 , JQuery Mobile in Visual Studio 2011 Developer Preview.

  • Check out the MVC 4 Mobile Web applications with JQuery Mobile , HTML5 , CSS 3 media queries in Smart Devices.
  • JQuery Mobile View in iPhone of MVC 4 Mobile application:

 



ASPHostPortal.com Proudly Announces ASP.NET MVC 5 Hosting

clock July 12, 2013 08:19 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based hosting, proudly announces the new Microsoft product, ASP.NET MVC 5 hosting to all new and existing customers.

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5 hosting services, we hope that developers and our existing clients can try this new features.”

ASPHostPortal.com is one of the Microsoft recommended hosting partner that provide most stable and reliable web hosting platform. With the new launch of ASP.NET MVC 5 into its feature, it will continue to keep ASPHostPortal as one of the front runners in the web hosting market. For more information about new ASP.NET MVC 5, please visit http://www.asphostportal.com.

About ASPHostPortal.com:
ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



IIS 7.5 Hosting - ASPHostPortal :: IIS 7.5 AppPool Identities

clock May 27, 2013 10:16 by author Ben

Windows 7 and Windows Server 2008 R2 ship with IIS 7.5. It's called Application Pool Identities. Application Pool Identities allows you to run Application Pools under an unique account without having to create and manage domain or local accounts. The name of the Application Pool account corresponds to the name of the Application Pool. The image below shows an IIS worker process (w3wp.exe) running as the DefaultAppPool identity.

Application Pool Identity Accounts
Worker processes in IIS 6 and 7 run as NETWORKSERVICE by default. NETWORKSERVICE is a built-in Windows identity. It doesn't require a password and it has only user privileges, i.e. it is relatively low-privileged. Running as a low-privileged account is a good security practice because then a software bug can't be used by a malicious user to take over the whole system. The problem is however that over time more and more Windows system services started to run as NETWORKSERVICE and services running as NETWORKSERVICE can tamper with other services running under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code) it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities. The Windows operating system provides a feature called "Virtual Accounts" that allows IIS to create unique identities for each of its Application Pools. Click here for more information about Virtual Accounts.

Configuring IIS Application Pool Identities
If you are running IIS 7.5 on Windows Server 2008 R2 you don't have to do anything. For every Application Pool you create the IIS Admin Process (WAS) will create a virtual account with the name of the new Application Pool and run the Application Pool's worker processes under this account. If you are running Windows Server 2008 you have to change the IdentityType property of the Application Pool you created to "AppPoolIdentity". Here is how:

  • Open the IIS Management Console (INETMGR.MSC).
  • Open the Application Pools node underneath the machine node. Select the Application Pool you want to change to run under an automatically generated Application Pool Identity.
  • Right click the Application Pool and select "Advanced Settings..."

Configure AppPool Identity

  • Select the "Identity" list item and click the button with the three dots.
  • The following dialog appears.

Select the Identity Type "ApplicationPoolIdentity" from the combo box

  • select the Identity Type "ApplicationPoolIdentity" from the combo box

Securing Resources
Whenever a new Application Pool is created the IIS management process creates a security identifier (SID) representing the name of the Application Pool itself, i.e. if you create an Application Pool with the name "MyNewAppPool" a security identifier with the name "MyNewAppPool" is created in the Windows Security system. From this point on resources can be secured using this identity. The identity is not a real user account however, i.e. it will not show up as a user in the Windows User Management Console. You can try this by selecting a file in Windows Explorer and adding the "DefaultAppPool" identity to its Access Control List (ACL).

  1. Open Windows Explorer
  2. Select a file or directory
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select your machine.
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box
  8. Click the "Check Names" button and click "OK".

By doing this the file or directory you selected will now also allow the "DefaultAppPool" identity access. You can do this via the command-line using the ICACLS tool. The following example gives full access to the DefaultAppPool identity.

On Windows 7 and Windows Server 2008 R2 the default is to run Application Pools as this security identifier, i.e. as the Application Pool Identity. To make this happen a new identity type with the name "AppPoolIdentity" was introduced. If the "AppPoolIdentity" identity type is selected (default on Windows 7 and Windows Server 2008 R2) IIS will run worker processes as the Application Pool identity. With every other identity type the security identifier will only be injected into the access token of the process. If the identifier is injected content can still be ACLed for the AppPool identity but the owner of the token is probably not unique. Here is an article that explains this concept.

Accessing the Network
Using the NETWORKSERVICE account in a domain environment has a great benefit. Worker process running as NETWORKSERVICE access the network as the machine account. Machine accounts are generated when a machine is joined to a domain. They look like this: <domainname>\<machinename>$, for example: mydomain\machine1$ The nice thing about this is that network resources like file shares or SQL Server databases can be ACLed to allow access for this machine account.

What about AppPool identities?
The good news is that Application Pool identities also use the machine account to access network resources. No changes are required.



IIS 7.5 Hosting - ASPHostPortal :: GZIP compression in IIS 7.5 for JSON response

clock May 15, 2013 12:20 by author Ben

Recently we need to build some RESTful services that responded with JSON and to my surprise these responses are not compressed when I fired up Fiddler and check the Transformer tab.

After enabling Failed Request Tracing in IIS by going to IIS Manager > Web Site > Right Panel > Actions Configure > Failed Request Tracing.

On the same page with the Right Panel of "Actions", under the IIS area, click into Failed Request Tracing Rules.

From there, at the Right Panel, click "Add..." > Specify Content to Trace > All content(*) > Status code(s): type in "200" > Finish.

You should make sure no other request is hitting on the same server at the same time to minimize the logging file creation, which is based on request, if you only have one request when you turn this on, there should only be one fr000001.xml file created in %windir%\inetpub\logs\FailedReqLogFiles\W3SVC1, open that in Internat Explorer and click on Request Details > Search for Compression, expand the corresponding node > Mine says in the node dynamic compression > not success > no_matching_content_type.

So it seems that even though by default HTTP Compression is enabled in IIS 7.5, there are only 3 content types that IIS recognizes and will actually perform the compression.

You can check this in IIS Manager > YOUR_SERVER > Under Management section > Configuration Editor > Expand the system.webServer > httpCompression > dynamicTypes

When you have a RESTful service that serve JSON based response and you would like that to be gzip/compressed whenever client's request includes in the header "Accept-Encoding: gzip", you must update this list to include both mime types

application/json
application/json;
charset=utf-8


in the list, you can either start adding these 2 type in the editor itself or you can run a command line tool AppCmd.exe from %windir%\system32\inetsrv directory, the full command is

appcmd.exe set config -section:system.webServer/httpCompression /+"dynamicTypes.[mimeType='application/json; charset=utf-8',enabled='True']" /commit:apphost

Remember to apply your settings if you are using the GUI editor, I used the command line tool because this is the only one that will add the type along with the "Entry Path", adding through the GUI editor for some reason doesn't add any Entry Type, it still works but I just don't like missing anything.

Now, restart IIS and you can check again in Fiddler and Viola! Now it says GZIP Encoding. You can "Click here to transform" to see the data :)



IIS 7.0 Hosting - ASPHostPortal :: Securing IIS 7.0 Web Server on Windows 2007

clock May 8, 2013 08:51 by author Ben

Hacking a Web Server
With the advent of Windows 2007 and IIS 7.0 there was a sharp turn in the way hosting services were being provided on Windows platform few years back. Today, web servers running on Internet Information Services 7.0 (IIS 7.0) are highly popular worldwide - thanks to the .NET and AJAX revolution for designing web applications. Unfortunately, this also makes IIS web servers a popular target amongst hacking groups and almost every day we read about the new exploits being traced out and patched. That does not mean that Windows is not as secured as Linux. In fact, it's good that we see so many patches being released for Windows platform as it clearly shows that the vulnerabilities have been identified and blocked.

Many server administrators have a hard time coping up with patch management on multiple servers thus making it easy for hackers to find a vulnerable web server on the Internet. One good way I have found to ensure servers are patched is to use Nagios to run an external script on a remote host, in turn alerting on the big screen which servers need patches and a reboot after the patch has been applied. In other words, it is not a difficult task for an intruder to gain access to a vulnerable server if the web server is not secured and then compromise it further to an extent that there is no option left for the administrator but to do a fresh OS install and restore from backups.
Many tools are available on the Internet which allows an experienced or a beginner hacker to identify an exploit and gain access to a web server. The most common of them are:

1. IPP (Internet Printing Protocol) - which makes use of the IPP buffer overflow. The hacking application sends out an actual string that overflows the stack and opens up a window to execute custom shell code. It connects the CMD.EXE file to a specified port on the attacker's side and the hacker is provided with a command shell and system access.

2. UNICODE and CGI-Decode - where the hacker uses the browser on his or her computer to run malicious scripts on the targeted server. The script is executed using the IUSR_ account also called the "anonymous account" in IIS. Using this type of scripts a directory transversal attack can be performed to gain further access to the system.

Over these years, I've seen that most of the time, attacks on a IIS web server result due to poor server administration, lack of patch management, bad configuration of security, etc. It is not the OS or the application to blame but the basic configuration of the server is the main culprit. I've outlined below a checklist with an explanation to each item. These if followed correctly would help prevent lot of web attacks on an IIS web server.

Secure the Operating System
The first step is to secure the operating system which runs the web server. Ensure that the Windows 2007 Server is running the latest service pack which includes a number of key security enhancements.

Always use NTFS File System
NTFS file system provides granular control over user permissions and lets you give users only access to what they absolutely need on a file or inside a folder.

Remove Unwanted Applications and Services
The more applications and services that you run on a server, the larger the attack surface for a potential intruder. For example, if you do not need File and Printer sharing capabilities on your shared hosting platform, disable that service.

Use Least Privileged Accounts for Service
Always use the local system account for starting services. By default Windows Server 2007 has reduced the need for service accounts in many instances, but they are still necessary for some third-party applications. Use local system accounts in this case rather than using a domain account. Using a local system account means you are containing a breach to a single server.

Rename Administrator and Disable Guest
Ensure that the default account called Guest is disabled even though this is a less privileged account. Moreover, the Administrator account is the favorite targets for hackers and most of the malicious scripts out there use this to exploit and vulnerable server. Rename the administrator account to something else so that the scripts or programs that have a check for these accounts hard-coded fail.

Disable NetBIOS over TCP/IP and SMB
NetBIOS is a broadcast-based, non-routable and insecure protocol, and it scales poorly mostly because it was designed with a flat namespace. Web servers and Domain Name System (DNS) servers do not require NetBIOS and Server Message Block (SMB). This protocol should be disabled to reduce the threat of user enumeration.

To disable NetBIOS over TCP/IP, right click the network connection facing the Internet and select Properties. Open the Advanced TCP/IP settings and go to the WINS tab. The option for disabling NetBIOS TCP/IP should be visible now.

To disable SMB, simply uncheck the File and Print Sharing for Microsoft Networks and Client for Microsoft Networks. A word of caution though - if you are using network shares to store content skip this. Only perform this if you are sure that your Web Server is a stand-alone server.

Schedule Patch Management
Make a plan for patch management and stick to it. Subscribe to Microsoft Security Notification Service (http://www.microsoft.com/technet/security/bulletin/notify.asp) to stay updated on the latest release of patches and updates from Microsoft. Configure your server's Automatic Update to notify you on availability of new patches if you would like to review them before installation.

Run MBSA Scan
This is one of the best way to identify security issues on your servers. Download the Microsoft Base Line Security tool and run it on the server. It will give you details of security issues with user accounts, permissions, missing patches and updates and much more.

That's it to the basic of securing the operating system. There are more fixes which can be performed for further securing the server but they are beyond the scope of this article. Let's now move on to securing the IIS web server.

IIS 7.0 when setup is secured by default. When we say this, it means that when a fresh installation of IIS is done, it prevents scripts from running on the web server unless specified. When IIS is first installed, it serves only HTML pages and all dynamic content is blocked by default. This means that the web server will not serve or parse dynamic pages like ASP, ASP.NET, etc. Since that is not what a web server is meant to do, the default configuration is changed to allow these extensions. Listed below are some basic points that guide you to securing the web server further:

Latest Patches and Updates
Ensure that the latest patches, updates and service packs have been installed for .NET Framework. These patches and updates fix lot of issues which enhances the security of the web server.

Isolate Operating System
Do not run your web server from the default InetPub folder. If you have the option to partition your hard disks then use the C: drive for Operating System files and store all your client web sites on another partition. Relocate web root directories and virtual directories to a non-system partition to help protect against directory traversal attacks.

IISLockDown Tool
There are some benefits to this tool and there are some drawbacks, however, so use it cautiously. If your web server interacts with other servers, test the lockdown tool to make sure it is configured so that connectivity to backend services is not lost.

Permissions for Web Content
Ensure that Script Source Access is never enabled under a web site's property. If this option is enabled, users can access source files. If Read is selected, source can be read; if Write is selected, source can be written to. To ensure that it is disabled, open IIS, right click the Websites folder and select Properties. Clear the check box if it is enabled and propagate it to all child websites.

Enable Only Required Web Server Extensions
IIS 7.0 by default does not allow any dynamic content to be parsed. To allow a dynamic page to be executed, you need to enable the relevant extension from the Web Service Extensions property page. Always ensure that "All Unknown CGI Extensions" and "All Unknown ISAPI Extensions" are disabled all the time. If WebDAV and Internet Data Connector are not required, disable that too.

Disable Parent Paths
This is the worst of all and thanks to Microsoft, it is disabled in IIS 7.0 by default. The Parent Paths option permits programmers to use ".." in calls to functions by allowing paths that are relative to the current directory using the ..notation. Setting this property to True may constitute a security risk because an include path can access critical or confidential files outside the root directory of the application. Since most of the programmers and third-party readymade applications use this notation, I leave it up to you to decide if this needs to be enabled or disabled. The workaround to Parent Paths is to use the Server.MapPath option in your dynamic scripts.

Disable Default Web Site
If not required, stop the Default Web Site which is created when IIS 7.0 is installed or change the property of Default Web Site to run on a specific IP address along with a Host Header. Never keep it running on All Unassigned as most of the ready-made hacking packages identify a vulnerable web server from IP address rather than a domain name. If your Default Web Site is running on All Unassigned, it means that it can serve content over an IP address in the URL rather than the domain name.

Use Application Isolation
I like this feature in IIS 7.0 which allows you to isolate applications in application pools. By creating new application pools and assigning web sites and applications to them, you can make your server more efficient and reliable as it ensures that other applications or sites do not get affected due to a faulty application running under that pool.

Summary
All of the aforementioned IIS tips and tools are natively available in Windows. Don't forget to try just one at a time before you test your Web accessibility. It could be disastrous if all of these were implemented at the same time making you wonder what is causing a problem in case you start having issues.

Final tip: Go to your Web server and Run "netstat -an" (without quotes) at the command line. Observe how many different IP addresses are trying to gain connectivity to your machine, mostly via port 80. If you see that you have IP addresses established at a number of higher ports, then you've already got a bit of investigating to do.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in