Applying for Master Program in Sweden

by Admin 6. August 2008 17:59
1)     Visit www.studera.nu and browse its English version website.2)     On the left menu you have to browse YOUR PAGES link in order to get registered on the website https://www.studera.nu/aw/toAccount.do?lang=en3)     Make sure you read each and every instruction written on the website specially at or under https://www.studera.nu/studera/897.html4)     After creating your account and understanding the general and documentation requirements browse search for courses https://www.studera.nu/aw/courseGuide.do?lang=en5)     It’s better if you search your relevant course using free text search utility provided at the top right on the page.  6)     You can apply for at most 8 courses. 7)     For general requirements at KTH you can refer this URL http://www.kth.se/studies/master/admission?l=en8)     Following documents must be submitted to www.studera.nu before the deadline mentioned on the website. These documents are general. You must check the actual requirements of your selected courses.a.      Cover sheet (generated from the web-based application)b.      Certificates and diplomas from previous education at an internationally recognized university (must be attested from HEC).c.      Transcripts of records (including course list). Sort them in reversed chronological order; i.e put the last received document on top.d.      A copy of your passport or some other document of identification.e.      Proof of English skills.f.        Autobiographical statement (Letter of motivation)g.      Curriculum Vitaeh.      2 Letters of Recommendationi.        Certificate showing relevant work experience, if applicablej.         Thesis proposal (if required)k.      Proof of finance (if required) 9)     You are done in selecting the courses and your application should be submitted successfully.10) After successful application submission you have to send your documents to Sweden for your application evaluation before the deadline on the mentioned address. Don’t forget to enclose singed cover sheet.11) After receiving your documents you will receive an acknowledgement email from studera.nu12) Keep on checking your studera.nu account regularly specially near the date of announcement. Visit http://www.paksirzameen.net/ for detailed discussion and procedures.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

general

Tools

by Admin 13. June 2008 23:06

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

general

Take Advantage of ASP.NET Built-in Features to Fend Off Web Attacks

by Admin 12. June 2008 07:53
Dino Esposito
Wintellect

Summary: Dino summarizes the most common types of Web attacks and describes how Web developers can use built-in features of ASP.NET to increase security. (13 printed pages)

What ASP.NET Developers Should Always Do

If you're reading this article, you probably don't need to be lectured about the growing importance of security in Web applications. You're likely looking for some practical advice on how to implement security in ASP.NET applications. The bad news is that no development platform—including ASP.NET—can guarantee you'll be writing 100-percent secure code once you adopt it—who tells that, just lies. The good news, as far as ASP.NET is concerned, is that ASP.NET, especially version 1.1 and the coming version 2.0, integrates a number of built-in defensive barriers, ready to use.

The application of all these features alone is not sufficient to protect a Web application against all possible and foreseeable attacks. However, combined with other defensive techniques and security strategies, the built-in ASP.NET features form a powerful toolkit to help ensure that applications operate in a secure environment.

Web security is the sum of various factors and the result of a strategy that goes well beyond the boundaries of the individual application to involve database administration, network configuration, and also social engineering and phishing.

The goal of this article is to illustrate what ASP.NET developers should always do in order to keep the security bar reasonably high. That's what security is mostly about—keep the guard up, never feel entirely secure, and make it harder and harder for the bad guys to hack.

Let's see what ASP.NET has to offer to simplify the job.

Where the Threats Come From

In Table 1, I've summarized the most common types of Web attacks and flaws in the application that can make them succeed.

AttackMade possible by . . .
Cross-site scripting (XSS) Untrusted user input echoed to the page
SQL injection Concatenation of user input to form SQL commands
Session hijacking Session ID guessing and stolen session ID cookies
One-click Unaware HTTP posts sent via script
Hidden field tampering Unchecked (and trusted) hidden field stuffed with sensitive data

Table 1. Common Web attacks

What are the key facts that emerge from the list? At least the following three, I'd say:

  • Whenever you insert any sort of user input into the browser's markup, you potentially expose yourself to a code injection attack (any variations of SQL injection and XSS).
  • Database access must be accomplished securely, that is, using the least set of permissions ever possible for accounts and delimiting the individual user's responsibility through roles.
  • Sensitive data should never be sent across the wire (let alone as clear text) and must be stored safely on the server.

It is interesting to note that the three points above address three distinct aspects of Web security, the combination of which is the only reasonable way to build a bulletproof and tamper-resistant application. The facets of Web security can be summarized as follows:

  • Coding practices: data validation, type and buffer length checking, anti-tampering measures
  • Data access strategies: use roles to ensure the weakest possible account, use stored procedures or at least parameterized commands
  • Effective storage and administration: do not send critical data down to the client, use hash codes to detect manipulation, authenticate users and protect identities, apply rigorous policies for passwords

As you can see, a secure application can result only from the combined efforts of developers, architects, and administrators. Don't assume you can get it right otherwise.

When writing ASP.NET applications you're not left on your own to fight against the army of hackers, armed only with your brains, skills, and fingers to type lines of code. ASP.NET 1.1 and later helps with a few specific features that raise automatic barriers against some of the threats listed above. Let's review them in detail.

ViewStateUserKey

Introduced with ASP.NET 1.1, ViewStateUserKey is a string property on the Page class that only few developers admit to be familiar with. Why? Let's read what the documentation has to say about it.

Assigns an identifier to an individual user in the view state variable associated with the current page

In spite of the convoluted style, the sentence is fairly clear; but can you honestly say it explains the intended purpose of the property? To understand the role of ViewStateUserKey, you need to read a little further, until you arrive at the Remarks section.

The property helps you prevent one-click attacks by providing additional input to create the hash value that defends the view state against tampering. In other words, ViewStateUserKey makes it much harder for hackers to use the content of the client-side view state to prepare malicious posts against the site. The property can be assigned any non-empty string, preferably the session ID or the user's ID. To better understand the importance of this property, let's briefly review the basics of the one-click attack.

A one-click attack consists in posting a malicious HTTP form to a known, vulnerable Web site. It is called "one-click" because it usually begins with an unaware victim clicking on an alluring link received through e-mail or found when navigating a crowded forum. By following the link, the user inadvertently triggers a remote process that ends up submitting the malicious <form> to a site. Be honest: can you say you never followed a link like Click here to win $1,000,000 just to see what happens? Apparently, nothing bad happened to you. Let's assume this is correct; can you say the same for all the rest of the Web community? Who knows.

To be successful, a one-click attack requires certain background conditions:

  • The attacker must know a lot about the vulnerable site. This can happen because the attacker "diligently" studied the file, or because he/she is an angry internal (for example, a fired and dishonest employee). For this reason, the attack might potentially be devastating.
  • The site must be using cookies (better if persistent cookies) to implement single sign-on, and the attacker should have received a valid authentication cookie.
  • Certain users of the site are involved in sensitive transactions.
  • The attacker must have access to the target page.

As mentioned, the attack consists in submitting a malicious HTTP form to a page that expects a form. Reasonably, this page will be consuming posted data to perform some sensitive operation. Reasonably, the attacker knows exactly how each field will be used and can come up with some spoofed values to reach his goal. It's usually a targeted attack, and it is also hard to track back because of the triangular trade that it establishes—the hacker induces a victim to click a link on the hacker's site, which in turn will post the bad code to a third site. (See Figure 1.)

Why an unsuspecting victim? Because, in this way server logs show that the IP address where the bad request originated is the victim's IP address! As mentioned, this attack is not as common (and easy to arrange) as a "classic" XSS; however, its nature makes it potentially devastating. What's the cure for it? Let's review the mechanics of the attack in the ASP.NET context.

Unless the action is coded in the Page_Load event, there's no way an ASP.NET page can execute sensitive code outside a postback event. For a postback event to take place, the view state field is mandatory. Bear in mind that ASP.NET checks the postback state of a request and sets IsPostBack accordingly, based on the presence of the _VIEWSTATE input field. So whoever wants to send a bogus request to an ASP.NET page must necessarily provide a valid view state field.

For the one-click attack to work, the hacker must have had access to the page. When this happened, the far-sighted hacker saved the page locally. So now he/she can access the _VIEWSTATE field and use that to create a request with the old view state and malicious values in other fields. The question is, will this work?

Why not? If the attacker can provide a valid authentication cookie, the hacker gets in and the request is regularly processed. The view state contents is not checked at all on the server (when EnableViewStataMac is off), or is only checked against tampering. By default, there's nothing in the view state that ties that content to a particular user. The attacker can easily reuse the view state obtained making legal access to the page to build a bogus request on behalf of another user. That's where ViewStateUserKey fits in.

If accurately chosen, the property adds user-specific information to the view state. When the request is processed, ASP.NET extracts the key from the view state and compares it against the ViewStateUserKey of the running page. If the two match, the request is considered legitimate; otherwise an exception is thrown. What's a valid value for the property?

Setting ViewStateUserKey to a constant string—the same for all users—is like leaving it blank. You must set it to something that varies for each user—user ID or, better yet, session ID. For a number of technical and social reasons, session ID is a much better fit because a session ID is unpredictable, times out, and varies on a per-user basis.

Here's the code you need to have in all of your pages:

To avoid writing this over and over again, you can bolt it in the OnInit virtual method of the Page-derived class. (Note that you must set this property in the Page.Init event.)

Overall, using a base page class is always a good thing, as I explain in my article, Build Your ASP.NET Pages on a Richer Bedrock. An excellent article to learn more about the tactics of one-click attackers can be found on aspnetpro.com.

Cookies and Authentication

Cookies exist because they can help developers to achieve results. Cookies operate as a sort of persistent link between browser and server. Especially for applications using single sign-on, a stolen cookie is just what makes the attack possible. This is certainly the case with one-click attacks.

To use cookies, you don't have to explicitly create and read them programmatically. You implicitly use cookies if you use session state and if you implement forms authentication. Sure, ASP.NET supports cookieless session state and ASP.NET 2.0 also introduces cookieless forms authentication. So you could in theory use those functionalities without using cookies. I'm not saying you don't have to, but this is just one of the cases in which the remedy can be even worse than the disease. Cookieless sessions, in fact, embed the session ID in the URL making it visible to everybody.

What are the potential problems connected to the use of cookies? Cookies can be stolen (that is, copied to the hacker's machine) and poisoned (that is, filled with malicious data). These actions are often the prelude to an incoming attack. If stolen, authentication cookies "authorize" external users to connect to the application (and use protected pages) on behalf of you, potentially enabling hackers to happily bypass authorization and themselves do whatever roles and security settings allow the victim to do. For this reason, authentication cookies are normally given a relatively short lifetime—30 minutes. (Note that the cookie expires even if the browser's session takes longer to complete.) In case of theft, hackers have a 30-minute window to try the attack.

This window can be enlarged to save users from having to log on too frequently; be aware that you do this at your own peril. In any case, avoid using ASP.NET persistent cookies. That would make the lifetime of the cookie virtually perennial, as long as 50 years! The following code snippet shows how to modify the expiration of the cookie at leisure.

You might want to use this code in your own login forms to fine-tune the lifetime of authentication cookies.

Session Hijacking

Cookies are also used to retrieve the session state for a particular user. The ID of the session is stored to a cookie that travels back and forth with the request and is stored on the browser's machine. Again, if stolen the session cookie can be used to get a hacker into the system and access someone else's session state. Needless to say, this can happen as long as the specified session is active—usually, no more than 20 minutes. An attack conducted through a spoofed session state is known as session hijacking. For more details on session hijacking, read Theft On The Web: Prevent Session Hijacking.

How dangerous can this attack be? Hard to say. It depends on what the Web site does and, more importantly, how its pages are designed. For example, imagine you've been able to get someone else's session cookie and attach it to a request to a page on the site. You load the page and work through its ordinary user interface. There's no code you can inject in the page and nothing in the page that you can alter, except that the page now works using the session state of another user. This is not bad per se, but may lead hackers straight to a successful exploit as long as the information in the session is sensitive and critical. Look, the hacker can't snoop into the content of the session store, but what's stored in it is used as if the hacker legitimately entered it. For example, imagine an e-commerce application where users add items to a shopping cart as they navigate through the site.

  • Scenario #1. The content of the shopping cart is stored in the session state. However, upon check-out, the user is requested to confirm and enter payment details over a secure SSL connection. In this case, plugging into another user's session state only allows the hacker to learn some details about the shopping preferences of the victim. No sort of damage really results from hijacking in this context. Only confidentiality is at risk.
  • Scenario #2. The application handles a profile for each registered user and stores the profile in the session state. Alas, the profile (as might be the case) includes credit card information. Why store user profile details into the session? Perhaps one of the application's goals is ultimately to save users from typing their credit card and bank information over and over again. So upon checkout, the application navigates the user to a page with pre-filled fields. Improvidently, one of these fields is the credit card number taken from the session state. Can you now guess the end of the story?

The design of the application's page is key to preventing session hijacking attacks. Two points remains open, though. The first is, what can you do to prevent cookie theft? The second is, what can ASP.NET do to detect and block hijacking?

The ASP.NET session cookie is extremely simple and is limited to contain the sole session ID string. The ASP.NET runtime extracts the session ID from the cookie and checks it against the active sessions. If the ID is valid, ASP.NET connects to the corresponding session and continues. This behavior greatly simplifies life for hackers who have stolen, or can guess, a valid session ID.

XSS and man-in-the-middle attacks, as well as brute access to a client PC, are all ways to get a valid cookie. To prevent thefts, you should implement security best practices to prevent XSS, and all of its variations, from succeeding.

To prevent session ID guessing, instead, you should simply avoid overrating your skills. Guessing a session ID means that you know a way to predict a valid session ID string. Given the algorithm used by ASP.NET (15 random numbers mapped to URL-enabled characters), your chance to guess a valid ID by chance approaches zero. There's no reason I can think of to replace the default session ID generator with your own. In many cases, you only make life easier for attackers.

What's worse about session hijacking is that once a cookie has been stolen or guessed there's not much ASP.NET can do to detect the fraudulent use of the cookie. Again, the reason is that ASP.NET limits itself to checking the validity of the ID and questions the place of origin of the cookie.

My Wintellect pal Jeff Prosise wrote an excellent article on session hijacking for MSDN Magazine. His conclusions offer little comfort—it's virtually impossible to build a foolproof defense against attacks that rely on stolen session ID cookies—but the code he developed offers a smart tip to raise the security bar even higher. Jeff created a HTTP module that monitors incoming requests and outgoing responses for session ID cookies. The module appends a hash code to outgoing session IDs that would make it harder for the attacker to reuse that cookie. You can read details here.

EnableViewStateMac

The view state is used to persist the state of controls across two successive requests for the same page. By default, the view state is Base64-encoded and signed with a hash value to prevent tampering. Unless you change default page settings, the view state is not at risk of tampering. If an attacker modifies the view state, or even if he/she rebuilds the view state using the right algorithm, ASP.NET catches the attempt and throws an exception. A tampered view state is not necessarily harmful—it modifies the state of server controls, though—but can become the vehicle of serious infections. For this reason, it is of extreme importance that you do not remove the machine authentication code (MAC) cross-checking that takes place by default. See Figure 2.

 

When MAC checking is enabled (which is the default), the serialized view state is appended a hash value that results from some server-side values and the view state user key, if any. When the view state is posted back, the hash value is computed again using fresh server-side values and compared to the stored value. If the two match, the request is allowed; otherwise, an exception is thrown. Even assuming the hacker has the skills to crack and rebuild the view state, he/she needs to know server-stored values to come up with a valid hash. Specifically, the hacker needs to know the machine key referenced in the <machineKey> entry of machine.config.

By default, the <machineKey> entry is autogenerated and physically stored in the Windows Local Security Authority (LSA). Only in case of Web farms—when the view state's machine keys must be the same on all machines—should you specify it as clear text in the machine.config file.

View state MAC checking is controlled through a @Page directive attribute named EnableViewStateMac. As mentioned, it is set to true by default. Never ever disable it; it would make view state tampering one-click attacks possible and with great chances of success.

ValidateRequest

Cross-site scripting (XSS) is an old-acquaintance for many seasoned Web developers—it's around since 1999 or so. Simply put, XSS exploits holes in the code to introduce a hacker's executable code into another user's browser session. Executed, the injected code can perform a variety of actions—grab cookies and upload a copy to a hacker's controlled Web site, monitor the user's Web session and forward data, modify the behavior and appearance of the hacked page giving incorrect information, even make itself persistent, so that the next time the user returns to the page, the fraudulent code runs again. Read in more detail about the basics of a XSS attack in the TechNet article Cross-site Scripting Overview.

What loopholes in the code make XSS attacks possible?

XSS exploits Web applications that dynamically generate HTML pages and don't validate the input echoed to the page. Input here means the contents of query strings, cookies, and form fields. If this content goes online without proper sanity checks, there's the risk that hackers can manipulate it to execute malicious script in client browsers. (After all, the aforementioned one-click attack is a recent variation of XSS.) A typical XSS attack entails that the unsuspecting user follows a luring link that embeds escaped script code. The fraudulent code is sent to a vulnerable page that trustfully outputs it. Here's an example of what can happen:

The user clicks on an apparently safe link and ends up passing to a vulnerable page a piece of script code that first gets all the cookies on the user's machine and then sends them to a page on the hacker's Web site.

It is important to note that XSS is not a vendor-specific issue and doesn't necessarily exploit holes in Internet Explorer. It affects every Web server and browser currently on the market. Even more important, note that there's no single patch to fix it. You can surely protect your pages from XSS, you do so by applying specific measures and sane coding practices. In addition, be aware that the attacker doesn't need the user to click a link in order to start the attack.

To defend against XSS, you must primarily determine which input is valid and reject all the rest. A detailed checklist for foiling XSS attacks can be found in the book that is a required reading at Microsoft—Writing Secure Code by Michael Howard and David LeBlanc. In particular, I suggest you take a careful look at Chapter 13.

The primary way to thwart insidious XSS attacks is to add a well-done and solid validation layer to your input—any type of input data. For example, there are circumstances in which even an otherwise innocuous color—a RGB triplet—can bring uncontrolled script straight to the page.

In ASP.NET 1.1, when turned on, the ValidateRequest attribute on the @Page directive checks that users are not sending potentially dangerous HTML markup in query strings, cookies, or form fields. If that is detected, an exception is thrown and the request aborts. The attribute is on by default; you don't have to do anything to be protected. If you want to allow HTML markup to pass, then you must actively disable it.

<%@ Page ValidateRequest="false" %>

ValidateRequest is not the silver bullet and can't replace an effective validation layer. Read here to get a lot of valuable information on how the feature really works under the hood. It basically applies a regular expression to catch a few potentially harmful sequences.

Note   The ValidateRequest feature was originally flawed; you need to apply a patch for it to work as expected. This is valuable information that has often passed unnoticed. Strangely enough, I myself found one of my machines still affected by the flaw. Check it out!

There's no reason for not keeping ValidateRequest on. You can disable it, but you must have a very good reason; one of which could be the user requirement of being able to post some HTML to the site for gaining better formatting options. In this case, you should limit the number of allowed HTML tags (<pre>, <b>, <i>, <p>, <br>, <hr>) and write a regular expression that ensures that nothing else is allowed or accepted.

Here are a few more tips that help protect ASP.NET applications from XSS:

  • Use HttpUtility.HtmlEncode to convert dangerous symbols to their HTML representation.
  • Use double quotes instead of single quotes, as HTML encoding only escapes double quotes.
  • Force a codepage to limit the number of characters that can be used.

In summary, use, but do not fully trust, the ValidateRequest attribute and don't be too lazy. Spend some time to understand security threats like XSS at their roots and plan a defensive strategy centered on one key point—consider all user input evil.

Database Perspective

SQL injection is another well-known type of attack that exploits applications that use unfiltered user input to form database commands. If the application blissfully uses what the user types in a form field to create a SQL command string, it exposes you to the risk that a malicious user may simply access the page and enter fraudulent parameters to modify the nature of the query. You can learn more about SQL injection here.

There are many ways in which you can thwart a SQL injection attack. Here are the most common techniques.

  • Ensure that any user input is of the proper type and follows the expected pattern (zip code, SSN, e-mail address). If you expect a number from a textbox, block the request if the user enters something that cannot be converted to a number.
  • Use parameterized queries or, better yet, stored procedures.
  • Use SQL Server permissions to limit the things each user can do on the database. For example, you might want to disable xp_cmdshell or limit it to administrators.

If you use stored procedure you significantly reduce the attack surface. With stored procedures, in fact, you don't need to compose SQL strings dynamically. In addition, any parameters are validated in SQL Server against the specified types. While this alone isn't a 100-percent secure technique, combined with validation it will make you more secure.

It is even more important to ensure that only authorized users perform potentially devastating operations like dropping tables. This requires a careful design of the middle-tier of the application. A good technique, and not just because of security, is to focus on roles. You group users in roles and define an account for each role with the least set of permissions.

A few weeks ago, the Wintellect Web site was under attack through a sophisticated form of SQL injection. The hacker attempted to create and launch an FTP script to download a (malicious?) executable. It was our good luck that the attack failed. Or was it rather strong input validation, use of stored procedures, and use of SQL Server permissions that prevented the attack from working?

To summarize, follow these guidelines to avoid unwanted injections of SQL code:

  • Run with least privileges and never execute code as "sa".
  • Restrict access to built-in stored procedures.
  • Favor SQL parameterized queries.
  • Do not build statements via string concatenation and do not echo database errors.

Hidden Fields

In classic ASP, hidden fields are the only way to persist data between requests. Any data you need to retrieve on the next request is packed into a hidden <input> field and round-tripped. What if on the client someone modifies the values stored in the field? The server-side environment has no way to figure it out so long as the text is clear. The ASP.NET ViewState property for pages and individual controls serves two purposes. On the one hand, the ViewState is the means to persist state across requests; on the other hand, the ViewState allows you to store custom values in a protected, tamper-resistant hidden field.

As shown in Figure 2, the view state is appended a hash value that gets checked on each and every request to detect tampering. There's no reason for using hidden fields in ASP.NET except in a few cases. The view state does the same in a much more secure way. Said upfront that storing sensitive values such as prices or credit card details in a clear hidden field is like leaving the door open to hackers, the view state would even make this bad practice less dangerous than before because of its data protection mechanism. However, bear in mind that the view state prevents tampering with but doesn't guarantee confidentiality unless you encrypt it—so credit card details stored in the view state are anyway at risk.

When is it acceptable to use hidden fields in ASP.NET? When you're building custom controls that need to send data back to the server. For example, imagine you create a new DataGrid control that supports column reordering. You need to pass the new order back to the server on postbacks. Where else can you store this information, if not into a hidden field?

If the hidden field is a read/write field—that is, the client is expected to write to it—there's not much you can do that is hacker-proof. You can try to hash or cipher the text, but this wouldn't give you any reasonable certainty of not being hacked. The best defense here is to make the hidden field contain inert and harmless information.

This said, it is worthwhile to note that ASP.NET exposes a little known class that can be used to encode and hash any serialized object. The class is LosFormatter and is the same class used by the ViewState implementation to create the encoded text round-tripped to the client.

private string EncodeText(string text) {  
StringWriter writer = new StringWriter();  LosFormatter formatter = new LosFormatter();  
formatter.Serialize(writer, text);  return writer.ToString();}

The preceding code snippet shows how to use LosFormatter to create view state-like content, encoded and hashed.

E-mails and Spam

To end this article, let me point out that at least two of the most common attacks—classic XSS and one-click—are often conducted by inducing unsuspecting victims to click on alluring and spoofed links. Many times we find such links directly in our inbox, anti-spam filters notwithstanding. Volumes of e-mail addresses can be bought for a few dollars. One of the main techniques used to build such lists is scanning public pages on Web sites looking for, and grabbing, anything that looks like an e-mail address.

If a page displays an e-mail address, the chances are good that sooner or later it will be caught by Web robots. Really? Well, it much depends on how you display the e-mail address. If you hardcode it, you're lost. If you resort to alternative representations such as dino-at-microsoft-dot-com, it's not clear if you really fool a Web robot; for sure, you will irritate any human reading your page who wants to establish a legitimate contact.

Overall, you should figure out a way to dynamically generate the email address as a mailto link. This is exactly what a free component written by Marco Bellinaso does. You can get it with full source code from the DotNet2TheMax Web site.

Summary

Does anyone doubt that the Web is probably the most hostile of all runtime environments? It comes from the fact that everybody can access a Web site and try to pass it good and bad data. However, would it really make sense to create a Web application that doesn't accept user input?

So let's face it: no matter how strong your firewall is, and how frequently you apply available patches, if you're running an inherently vulnerable Web application, sooner or later attackers will walk straight to the heart of your systems through the main entrance, namely port 80.

ASP.NET applications are neither more vulnerable nor more secure than other Web applications. Security and vulnerability both derive from coding practices, experience from the field, and teamwork. No application is secure if the network isn't; likewise, no matter how secure and well administered the network is, attackers will always find their way if the application is broken.

The beauty of ASP.NET is that it provides you with a few good tools to raise the security bar to a passable level with a few clicks. It is not a sufficient level, though. Do not rely on ASP.NET built-in solutions alone—but neither should you ignore them. And learn as much as possible about most common attacks.

This article provides an annotated list of built-in features and some background about attacks and defenses. Techniques for detecting ongoing attacks are another story, and perhaps require another article.

Related Resources

Writing Secure Code by Michael Howard and David LeBlanc

TechNet Magazine, Theft On The Web: Prevent Session Hijacking

 

About the Author

Dino Esposito is a Wintellect instructor and consultant based in Italy. Author of Programming Microsoft ASP.NET and the more recent Introducing Microsoft ASP.NET 2.0 (both from Microsoft Press), he spends most of his time teaching classes on ASP.NET and ADO.NET and speaking at conferences. Tour Dino's blog at http://weblogs.asp.net/despos.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

general

C# Interview Questions

by Admin 28. April 2008 05:55

General Questions

  1. Does C# support multiple-inheritance?
    No.
     
  2. Who is a protected class-level variable available to?
    It is available to any sub-class (a class inheriting this class).
     
  3. Are private class-level variables inherited?
    Yes, but they are not accessible.  Although they are not visible or accessible via the class interface, they are inherited. 
     
  4. Describe the accessibility modifier “protected internal”.
    It is available to classes that are within the same assembly and derived from the specified base class. 
     
  5. What’s the top .NET class that everything is derived from?
    System.Object. 
     
  6. What does the term immutable mean?
    The data value may not be changed.  Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
     
     
  7. What’s the difference between System.String and System.Text.StringBuilder classes?
    System.String is immutable.  System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. 
     
  8. What’s the advantage of using System.Text.StringBuilder over System.String?
    StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time a string is changed, a new instance in memory is created.
     
  9. Can you store multiple data types in System.Array?
    No. 
     
  10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array.  The CopyTo() method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
     
  11. How can you sort the elements of the array in descending order?
    By calling Sort() and then Reverse() methods. 
     
  12. What’s the .NET collection class that allows an element to be accessed using a unique key?
    HashTable. 
     
  13. What class is underneath the SortedList class?
    A sorted HashTable. 
     
  14. Will the finally block get executed if an exception has not occurred?­
    Yes.
     
  15. What’s the C# syntax to catch any possible exception?
    A catch block that catches the exception of type System.Exception.  You can also omit the parameter data type in this case and just write catch {}. 
     
  16. Can multiple catch blocks be executed for a single try statement?
    No.  Once the proper catch block processed, control is transferred to the finally block (if there are any). 
     
  17. Explain the three services model commonly know as a three-tier application.
    Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). 
     

Class Questions

  1. What is the syntax to inherit from a class in C#?
    Place a colon and then the name of the base class.
    Example: class MyNewClass : MyBaseClass 
     
  2. Can you prevent your class from being inherited by another class?
    Yes.  The keyword “sealed” will prevent the class from being inherited. 
     
  3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
    Yes.  Just leave the class public and make the method sealed. 
     
  4. What’s an abstract class?
    A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation. 
     
  5. When do you absolutely have to declare a class as abstract?
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2. 
    When at least one of the methods in the class is abstract. 
     
  6. What is an interface class?
    Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. 
     
  7. Why can’t you specify the accessibility modifier for methods inside the interface?
    They all must be public, and are therefore public by default. 
     
  8. Can you inherit multiple interfaces?
    Yes.  .NET does support multiple interfaces. 
     
  9. What happens if you inherit multiple interfaces and they have conflicting method names?
    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
    To Do: Investigate 
     
  10. What’s the difference between an interface and abstract class?
    In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers. 
     
  11. What is the difference between a Struct and a Class?
    Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval.  Another difference is that structs cannot inherit. 
     

Method and Property Questions

  1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
    Value.  The data type of the value parameter is defined by whatever data type the property is declared as. 
     
  2. What does the keyword “virtual” declare for a method or property?
    The method or property can be overridden. 
     
  3. How is method overriding different from method overloading?
    When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same name within the class. 
     
  4. Can you declare an override method to be static if the original method is not static?
    No.  The signature of the virtual method must remain the same.  (Note: Only the keyword virtual is changed to keyword override) 
     
  5. What are the different ways a method can be overloaded?
    Different parameter data types, different number of parameters, different order of parameters. 
     
  6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
    Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
     

Events and Delegates

  1. What’s a delegate?
    A delegate object encapsulates a reference to a method. 
     
  2. What’s a multicast delegate?
    A delegate that has multiple handlers assigned to it.  Each assigned handler (method) is called.
     

XML Documentation Questions

  1. Is XML case-sensitive?
    Yes. 
     
  2. What’s the difference between // comments, /* */ comments and /// comments?
    Single-line comments, multi-line comments, and XML documentation comments. 
     
  3. How do you generate documentation from the C# file commented properly with a command-line compiler?
    Compile it with the /doc switch.
     

Debugging and Testing Questions

  1. What debugging tools come with the .NET SDK?
    1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch.
    2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR. 
     
  2. What does assert() method do?
    In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true. 
     
  3. What’s the difference between the Debug class and Trace class?
    Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds. 
     
  4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    The tracing dumps can be quite verbose.  For applications that are constantly running you run the risk of overloading the machine and the hard drive.  Five levels range from None to Verbose, allowing you to fine-tune the tracing activities. 
     
  5. Where is the output of TextWriterTraceListener redirected?
    To the Console or a text file depending on the parameter passed to the constructor. 
     
  6. How do you debug an ASP.NET Web application?
    Attach the aspnet_wp.exe process to the DbgClr debugger. 
     
  7. What are three test cases you should go through in unit testing?
    1.       Positive test cases (correct data, correct output).
    2.       Negative test cases (broken or missing data, proper handling).
    3.       Exception test cases (exceptions are thrown and caught properly). 
     
  8. Can you change the value of a variable while debugging a C# application?
    Yes.  If you are debugging via Visual Studio.NET, just go to Immediate window. 
     

ADO.NET and Database Questions

  1. What is the role of the DataReader class in ADO.NET connections?
    It returns a read-only, forward-only rowset from the data source.  A DataReader provides fast access when a forward-only sequential read is needed.
  2.  
     
  3. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix.  OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET. 
     
  4. What is the wildcard character in SQL?
    Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’. 
     
  5. Explain ACID rule of thumb for transactions.
    A transaction must be:
    1.       Atomic - it is one unit of work and does not dependent on previous and following transactions.
    2.       Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
    3.       Isolated - no transaction sees the intermediate results of the current transaction).
    4.       Durable - the values persist if the data had been committed even if the system crashes right after. 
     
  6. What connections does Microsoft SQL Server support?
    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). 
     
  7. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
    Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction. 
     
  8. What does the Initial Catalog parameter define in the connection string?
    The database name to connect to. 
     
     
  9. What does the Dispose method do with the connection object?
    Deletes it from the memory.
    To Do: answer better.  The current answer is not entirely correct. 
     
  10. What is a pre-requisite for connection pooling?
    Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.  The connection string must be identical.
     

Assembly Questions

  1. How is the DLL Hell problem solved in .NET?
    Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. 
     
  2. What are the ways to deploy an assembly?
    An MSI installer, a CAB archive, and XCOPY command. 
     
  3. What is a satellite assembly?
    When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. 
     
  4. What namespaces are necessary to create a localized application?
    System.Globalization and System.Resources.
     
  5. What is the smallest unit of execution in .NET?
    an Assembly.
     
  6. When should you call the garbage collector in .NET?
    As a good rule, you should not call the garbage collector.  However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory.  However, this is usually not a good practice.
     
  7. How do you convert a value-type to a reference-type?
    Use Boxing.
     
  8. What happens in memory when you Box and Unbox a value-type?
    Boxing converts a value-type to a reference-type, thus storing the object on the heap.  Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

general

Visual Studio 2005 Shortcuts

by Admin 4. April 2008 15:31

Its not necessary that you should know everything about Visual Studio IDE. but if you know few basics shortcuts within your IDE you can save much of your time. If you are a power user, you will certainly enjoy using keyboard shortcuts to perform various operations more quickly.most of you are already familiar with some of them:

  • F5 for Debug.Start,
  • F10 for Debug.StepOver
  • F4 for View.Properties

I have included some of my favorite ones below.

Basics:

F7 Toggles between design and code views.
F9 Toggles breakpoint.
F12 Go to definition of a variable, object, or function.
Ctrl+Shift+7

Ctrl+Shift+8

Quickly navigate forward and backwards in the go to definition stack.
Shift+F12 Find all references of a function or a variable.
Ctrl+M, Ctrl+M Expand and collapse code outlining in the editor.
Ctrl+K, Ctrl+C

Ctrl+K, Ctrl+U

Comment and uncomment line(s) of code, respectively.
Shift+Alt+Enter Toggles between full screen mode and normal mode.
Ctrl+I

Incremental Search.

Navigation:

  • Goto Line: Ctrl+G Brings up Go To Line allowing you to automatically jump to a line position
  • Toggle Bookmark: Ctrl+K, Ctrl+K Set a bookmark to allow you to easily jump back to that position later.
  • Next Bookmark/Previous Bookmark: Ctrl+K, Ctrl+N (Next); Ctrl+K, Ctrl+P (Previous) Moves between your set bookmarks.

Debugging/Running/Compiling:

  • Insert/Remove (Simple) Breakpoint: F9 Create a default breakpoint which always fires when debugging.
  • Insert (Complex) Breakpoint: Ctrl+B Brings up breakpoint dialogue allowing for conditional breakpoints, etc.
  • Start (with Debugging if in Debug build): F5 Run without Debugging: Ctrl+F5 If you are in a release build, both F5 and Ctrl+F5 behave the same.
  • Iterate Through Build Errors: F8 If your build fails, you can press F8 to move between the various errors in the task list.

Writing Code:

  • Comment and Uncomment Code: Ctrl+K,Ctrl+C (Comment), Ctrl+K, Ctrl+U (Uncomment) Works on current line or multiple selected lines.
  • Intellisense Autocomplete: Alt+RArrow or Ctrl+Space Start typing a keyword, then press Alt + Right Arrow or Ctrl + Space and Intellisense will complete the word (if what you’ve typed is identifiable) or bring up Intellisense with the nearest match. You can also do this before typing and Intellisense will come up.
  • Dynamic Help: F1 Get in center of a method, type, class, etc in editor, press F1. Help comes up on that topic if it exists.
  • View Code-Behind: F7 View the code-behind file from the .ASPX or .ASCX file
  • Switch between Design and HTML View: Ctrl + PgUp or Ctrl + PgDown Move between HTML and Design view on .ASPX and .ASCX files.
  • Switch between Tabs: Ctrl+Tab (Back), Ctrl+Shift+Tab (Forward) Useful for moving between open files in Visual Studio. Keeps track of the order in which you last visited the tabs and cycles through that.
  • Go To Definition: F12 Click, Select or have cursor on text you wish to go to the definition of.
  • Last cursor position: Ctrl + - (Back), Ctrl+Shift+- (Forward) Useful for moving between files you have been editing. Especially useful if you have done a Go To Definition or if you are stepping though code in the debugger.
  • Toggle Wordwrap:Ctrl + R, Ctrl + R While you should make it a practice to limit the width of your lines so they don’t require wrapping, sometime you do have lines that scroll off the Screen. This wraps them for you so you can see the entire text without scrolling.
  • CTRL+ALT+L: View Solution Explorer.
  • SHIFT+F12: Find all references of a function or variable.
  • F7: Toggle between Designer and Source views.
  • CTRL+D or CTRL+/: Find combo (see section on Find Combo below).
  • CTRL+M, O: Collapse to Definitions. This is usually the first thing I do when opening up a new class.
  • CTRL+K, CTRL+C: Comment block. CTRL+K, CTRL-U (uncomment selected block).
  • CTRL+-: Go back to the previous location in the navigation history.
  • ALT+B, B: Build Solution. Related shortcuts: ALT+B, U (build selected Project), ALT+B, R (rebuild Solution).
  • CTRL+ALT+Down Arrow: Show dropdown of currently open files. Type the first few letters of the file you want to select.
  • CTRL+K, CTRL+D: Format code.
  • CTRL+L: Delete entire line.
  • SHIFT+ALT+Enter: Toggle full screen mode. This is especially useful if you have a small monitor.
  • CTRL+K, X: Insert "surrounds with" code snippet.
  • CTRL+B, T: Toggle bookmark. Related: CTRL+B, N (next bookmark), CTRL+B, P (prev bookmark).

 

even i dont use all of them but we should.. Happy Coding  Wink

see also http://www.imiscommunity.com/visual_studio_2005_tips_and_tricks

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

general

Disable Button on Postback in ASP.NET

by Admin 7. March 2008 07:06

Starting with a new, blank ASP.NET WebForm, add a single button control to the page:

Listing 1: ASP.NET markup for the Save button

<asp:button id="btnSave" text="Save"runat="server" />

Code Behind

On the server, you must add to the attributes of the server control to hook into the client-side click event.  When the user clicks on the button, the custom JavaScript executes before the ASP.NET __doPostBack function.  The addition to the control is all done in the page load event and is only necessary upon the first request of the page.

Listing 2: Add a client-side OnClick event to an ASP.NET button

Private Sub Page_Load(ByVal sender As System.Object,_        
ByVal e As System.EventArgs) HandlesMyBase.Load   
If Not Me.Page.IsPostBack Then   
Me.btnSave.Attributes.Add("onclick",_"btnSave_Click(this);")  
End If
End Sub

In a real-world scenario when the user clicks on the button, the page will make the appropriate calls to a business layer in order to perform some kind of task (apply for a loan, order pizza, etc.).    For the sake of this example, the page will send a command to the server to tell it to hesitate for five seconds by calling the Sleep method of the current Thread.  This will simulate a long server process.  The following code will demonstrate this technique in action.

Listing 3: Add a five second delay to simulate real-world performance issues

Private Sub btnSave_Click(ByVal sender As _        System.Object
ByVal e As System.EventArgs)_ 
Handles btnSave.Click  System.Threading.Thread.Sleep(5000)End Sub

JavaScript

The JavaScript for this solution is built to be generic and reusable.  In order to achieve the desired effect, the browser must wait before disabling the button, but not hinder the server from processing.

The flow of execution for this process:

1. Run the custom function when the user clicks the button.

2. Initiate a delay on the client which will eventually disable the calling button.

3. Return control to ASP.NET which will contact the server for the postback.

Add the following JavaScript in the <head> section of your page.  The following is the implementation of this logic.

Listing 4: Generic JavaScript functions that disables a control after a short interval

<script type="text/javascript">function DisableControl(controlId){  
document.getElementById(controlId).disabled =true;} 
function DisableControl_SetTimeout(controlId,interval)
{  setTimeout("DisableControl('" +controlId + "')",interval);} 
function btnSave_Click(control){  DisableControl_SetTimeout(control.id,100);}
</script>

The DisableControl function contains a reference to the calling control’s ID as its only argument.  When the function executes then the control is located on the page, its state is updated and it becomes disabled.

JavaScript’s built-in setTimeout function executes a function after waiting a specified amount of time.  The DisableControl_Timeout function calls DisableControl using the setTimeout feature.

The btnSave_Click function will run when the user clicks on the button.  Since you wired up this function in your code-behind passing by this as an argument, you may access the control’s properties directly.

You might be wondering why you would not just pass a reference to the control to each of the functions, rather than the control ID.  The JavaScript setTimeout function requires that you pass in a string of the function name and arguments along with delay interval.  If you pass in an object reference as an argument, the page will encounter a JavaScript error.

Run this page in your browser to test its behavior.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

general

Send Email Through ASP.NET 2.0

by Admin 4. March 2008 19:28

today i was wondering for some well written SMTP mail sender code in ASP.NET 2.0. i found so many but then i liked to write one for myself. here it goes...

public void SendMailNow()

{

// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0

// System.Net.Mail.SmtpClient is the alternate class for this in 2.0

SmtpClient smtpClient = new SmtpClient(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

try

{

MailAddress fromAddress = new MailAddress(FromEmail, FromDisplayName);

// You can specify the host name or ipaddress of your server

// Default in IIS will be localhost

smtpClient.Host = SmtpServer;

//Default port will be 25

int prt=0;Int32.TryParse(Port, out prt);

smtpClient.Port = prt ;

//From address will be given as a MailAddress Object

message.From = fromAddress;

// To address collection of MailAddress

foreach(string t in To)

{

message.To.Add(t);

}

message.Subject = Subject;

// CC and BCC optional

foreach (string c in Cc)

{

message.CC.Add(c);

}

foreach (string b in Bcc)

{

message.Bcc.Add(b);

}

// MailAddressCollection class is used to send the email to various users

// You can specify Address as new MailAddress("admin1@yoursite.com")

message.CC.Add(new MailAddress("sajid.nazeer@gmail.com", "Sajid"));

// You can specify Address directly as string

//message.Bcc.Add(new MailAddress("admin3@yoursite.com"));

//message.Bcc.Add(new MailAddress("admin4@yoursite.com"));

//Body can be Html or text format

//Specify true if it is html message

message.IsBodyHtml = IsHtml;

// Message body content

message.Body = Message.Trim();

// Send SMTP mail

smtpClient.Send(message);

}

catch (Exception)

{

throw;

}

}

 

Download the Code in C#

EmailSender.cs (6.09 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

general

Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen

S@jid

there is no secret ingredient - Kung fu Panda

Recent posts

Recent comments