Strong responses html. Crazy shapes. Email addresses

Cross-site script injection attacks

In a cross-site scripting (XSS) attack, an attacker injects malicious code into a legitimate Web page, which then runs a malicious script on the client side. When a user visits an infected page, the script is downloaded to the user's browser and executed there. This scheme has many varieties. A malicious script could access browser cookies, session tokens, or other sensitive information stored in the browser. However, all attacks operate according to the scheme shown in Figure 1.

Figure 1. Figure 1. Typical XSS attack
XSS vulnerabilities

In a typical XSS attack, the attacker finds a way to inject a string into the server's Web page. Let's say an attacker injected the following line into a Web page: alert("you are under attack") . Every time a user visits this page, their browser downloads this script and runs it along with the rest of the page's content. In this case, as a result of running the script, the user will see a pop-up window with the text “you are under attack.”

Consequences of XSS

If an attacker was able to exploit an XSS vulnerability in a Web application, he could inject script into the page that would provide access to data account user. In this case, the attacker can perform many malicious actions, for example:

  • steal an account;
  • spread viruses;
  • access your browsing history and clipboard contents;
  • Get an opportunity remote control browser;
  • scan and use hardware and software resources and applications on the internal network.
Preventing XSS attacks

To prevent XSS attacks, the application must encrypt the page output before delivering it to the end user. When encrypting output data HTML markup replaced by alternative representations - objects. The browser displays these objects but does not launch them. For example, converted to .

Table 1 shows the object names for some common HTML characters.

Table 1. Object names for HTML characters Result Description Object name Object number
Non-breaking space
< Less than<
> More than> >
& Ampersand& &
¢ Cent¢ ¢
£ Lb£ £
¥ Jena¥ ¥
Euro
§ Paragraph§ §
© Copyright ©
® ® ®
Trademark

When the browser encounters the objects, they are converted back to HTML and printed, but they are not fired. For example, if an attacker inserts the string alert("you are under attack") into a variable field on the server's Web page, then when using the described strategy, the server will return the string alert("you are under attack") .

When the browser downloads the encrypted script, it will convert it to alert("you are under attack") and display the script as part of the Web page, but will not run it.

Adding HTML Code to a Server-Side Java Application

To prevent malicious script code from being rendered along with the page, your application must encrypt all string variables before they are rendered on the page. Encryption consists of simple transformation each character to the corresponding HTML object name, as shown in Java code shown in Listing 1.

Listing 1. Converting characters to HTML object names public class EscapeUtils ( public static final HashMap m = new HashMap(); static ( m.put(34, """); //< - меньше чем m.put(60, ""); // >- greater than //User must match all html objects with the corresponding decimal values. //Object mappings to decimal values ​​are shown in the table below) public static String escapeHtml() ( String str = "alert(\"abc\")"; try ( StringWriter writer = new StringWriter((int) (str.length() * 1.5)); escape(writer, str); System.out.println("encoded string is " + writer.toString()); return writer.toString(); ) catch (IOException ioe) ( ioe.printStackTrace() ; return null; ) ) public static void escape(Writer writer, String str) throws IOException ( int len ​​= str.length(); for (int i = 0; i< len; i++) { char c = str.charAt(i); int ascii = (int) c; String entityName = (String) m.get(ascii); if (entityName == null) { if (c >0x7F) ( writer.write(""); writer.write(Integer.toString(c, 10)); writer.write(";"); ) else ( writer.write(c); ) ) else ( writer. write(entityName); ) ) ) )

The Java code in Listing 1 encodes the HTML string String String "alert(\"abc\)" . Use the following procedure:

As a result, the following line will appear in the output: alert("abc") .

Table 2 shows the mapping of HTML objects to their decimal values.

Table 2. HTML Object Decimal Values Decimal value Object Description
160 Non-breaking space
60 < Less than
62 > More than
38 & Ampersand
162 ¢ Cent
163 £ Lb
165 ¥ Jena
8364 Euro
167 § Paragraph
169 Copyright
174 ® Registered Trademark
8482 Trademark
Conclusion

Cross-site script injection is one of the most common methods of attacking a user's computer. However, you can significantly reduce an attacker's ability to infect your Web application with malicious code. When building your application, be careful to encrypt all page output values ​​before sending them to the end user's browser.

Generating a response from controllers

After the controller has finished processing the request, it usually needs to generate a response. When we create a low-level controller by directly implementing the IController interface, we must take responsibility for every aspect of request processing, including generating a response to the client.

For example, to send an HTML response, you would need to create and compose the HTML data and then send it to the client using the Response.Write() method. Similarly, to redirect the user's browser to another URL, you will need to call the Response.Redirect() method and pass it the required URL. Both approaches are demonstrated in the code below, which shows extensions of the BasicController class that we created in an earlier article by implementing the IController interface:

Using System.Web.Mvc; using System.Web.Routing; namespace ControllersAndActions.Controllers ( public class BasicController: IController ( public void Execute(RequestContext requestContext) ( string controller = (string)requestContext.RouteData.Values["controller"]; string action = (string)requestContext.RouteData.Values["action "]; if (action.ToLower() == "redirect") ( requestContext.HttpContext.Response.Redirect("/Derived/Index"); ) else ( requestContext.HttpContext.Response.Write(string.Format("Controller : (0), Action method: (1)", controller, action)); ) ) ) )

The same approach can be applied in the case of inheriting a controller from the Controller class. The HttpResponseBase class, which is returned when the requestContext.HttpContext.Response property is read in the Execute() method, is accessible through the Controller.Response property, as shown in the example below, which extends the DerivedController class, also created earlier by inheriting from the Controller class:

Using System; using System.Web; using System.Web.Mvc; namespace ControllersAndActions.Controllers ( public class DerivedController: Controller ( public ActionResult Index() ( // ... ) public void ProduceOutput() ( if (Server.MachineName == "ProfessorWeb") Response.Redirect("/Basic/Index" ); else Response.Write("Controller: Derived, Action Method: ProduceOutput"); ) ) )

The ProduceOutput() method uses the value of the Server.MachineName property to decide what response to send to the client. ("ProfessorWeb" is the name of my development machine.)

Although this approach of generating a response to the user works, there are several problems with it:

    Controller classes must contain information about HTML structure or URL, which makes classes difficult to read and maintain.

    A controller that generates a response directly to output is difficult to unit test. You'll need to create mock implementations of the Response object and then be able to process the output from the controller to determine what it is. This may mean, for example, the need to parse HTML markup into keywords, which is a long and tedious process.

    Processing the small details of each response in this way is complex and error-prone. Some programmers like the absolute control provided by building a low-level controller, but this usually gets complicated very quickly.

Fortunately, the MVC Framework has a handy tool that solves all of these problems - the results of actions. The following sections explain the concept of action results and show various ways its use for generating responses from controllers.

Results of actions

Action results in the MVC Framework are used to separate statements of intent from execution of intent (sorry for the tautology). The concept will seem simple once you get the hang of it, but it takes some time to understand due to some indirectness.

Instead of dealing directly with a Response object, action methods return an ActionResult-derived class object that describes what the response from the controller should be—for example, rendering a view or redirecting to another URL or action method. However (this is the very indirectness) the answer is not directly generated. Instead, an ActionResult object is created, which the MVC Framework processes to produce the result after the action method has been called.

An action results system is an example of the Command design pattern. This pattern represents scenarios in which you store and pass objects that describe the operations being performed.

When the MVC Framework receives an ActionResult object from an action method, it calls ExecuteResult() method, defined in the class of this object. The action results implementation then operates on the Response object, generating output that matches your intent. To demonstrate this in action, let's create an Infrastructure folder and add a new class file to it called CustomRedirectResult.cs with a custom ActionResult implementation shown in the example below:

Using System.Web.Mvc; namespace ControllersAndActions.Infrastructure ( public class CustomRedirectResult: ActionResult ( public string Url ( get; set; ) public override void ExecuteResult(ControllerContext context) ( string fullUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext); context.HttpContext.Response.Redirect (fullUrl); ) ) )

This class is based on the way the System.Web.Mvc.RedirectResult class works. One of the benefits of the open source MVC Framework is the ability to explore the inner workings of anything. The CustomRedirectResult class is much simpler than its MVC equivalent, but is sufficient for the purposes of this article.

When instantiating the RedirectResult class, we pass in the URL to which the user should be redirected. The ExecuteResult() method, which will be executed by the MVC Framework when the action method completes, receives Response object to make a request through the ControllerContext object provided by the framework and calls either the RedirectPermanent() method or the Redirect() method (this exactly mirrors what was done inside the low-level IController implementation in the example earlier in the article).

The use of the CustomRedirectResult class is illustrated in the example below, which shows the changes that were made to the Derived controller:

// ... using ControllersAndActions.Infrastructure; namespace ControllersAndActions.Controllers ( public class DerivedController: Controller ( public ActionResult Index() ( // ... ) public ActionResult ProduceOutput() ( if (Server.MachineName == "MyMachineName") return new CustomRedirectResult ( Url = "/Basic/ Index" ); else ( Response.Write("Controller: Derived, Action Method: ProduceOutput"); return null; ) ) ) )

Note that we were forced to change the result of the action method to return ActionResult. We return null if we don't want the MVC Framework to do anything when our action method is executed, which is what we did if the CustomRedirectResult instance was not returned.

Unit Testing Controllers and Actions

Many parts of the MVC Framework are designed to make unit testing easier, and this is especially true for actions and controllers. There are several reasons for this support:

You can test actions and controllers outside of the web server. Context objects are accessed through their base classes (such as HttpRequestBase), which is easy to mock.

To test the results of an action method, you don't need to parse the HTML markup. To ensure that you are getting the expected results, you can inspect the returned ActionResult object.

Emulation of client requests is not needed. The MVC Framework's model binding system allows you to write action methods that receive input in their parameters. To test an action method, you simply call it directly and provide the appropriate parameter values.

Future articles on generating data from controllers will show you how to create unit tests for different types of action results.

Don't forget that unit testing is only part of the picture. Complex behavior in an application occurs when action methods are called sequentially. Unit testing works best when combined with other testing approaches.

Now that you know how the special result of a redirect action works, you can switch to its equivalent offered by the MVC framework, which is more powerful and has been thoroughly tested by Microsoft. The required change to the Derived controller is given below:

// ... public ActionResult ProduceOutput() ( return new RedirectResult("/Basic/Index"); ) // ...

The conditional statement has been removed from the action method, which means that after launching the application and navigating to a URL like /Derived/ProduceOutput, the browser will be redirected to a URL like /Basic/Index. To simplify action method code, the Controller class includes convenience methods for generating various kinds of ActionResult objects. So, for example, we can achieve the same effect as in the example above by returning the result of the Redirect() method:

// ... public ActionResult ProduceOutput() ( return Redirect("/Basic/Index"); ) // ...

There's nothing particularly complex about the action results system, but it ultimately helps produce simpler, cleaner, more consistent code that's easy to read and unit test. For example, in the case of redirection, you can simply check that the action method returns a RedirectResult instance whose Url property contains the expected target.

The MVC Framework defines many built-in action result types, which are described in the table below:

Built-in ActionResult types Type Description Helper methods of the Controller class
ViewResult

Renders the specified or standard view template

View()
PartialViewResult

Renders the specified or standard partial view template

PartialView()
RedirectToRouteResult

Issues HTTP redirect 301 or 302 to an action method or specified route entry, generating a URL according to the routing configuration

RedirectToAction()
RedirectToActionPermanent()
RedirectToRoute()
RedirectToRoutePermanent()
RedirectResult

Issues an HTTP 301 or 302 redirect to the given URL

Redirect()
RedirectPermanent()
ContentResult

Returns unformatted text data to the browser, additionally setting the content-type header

Content()
FileResult

Transfers binary data (such as a file on disk or a byte array in memory) directly to the browser

File()
JsonResult

Serializes a .NET object to JSON format and sends it as a response. Responses of this type are more often generated when using Web API and AJAX tools

Json()
JavaScriptResult

Sends a fragment source code JavaScript that must be executed by the browser

JavaScript()
HttpUnauthorizedResult

Sets the HTTP response status code to 401 (meaning "not authorized"), which causes the authentication mechanism in place (forms authentication or Windows authentication) to prompt the visitor to sign in

No
HttpNotFoundResult

Returns HTTP error with code 404 - Not found (not found)

HttpNotFound()
HttpStatusCodeResult

Returns the specified HTTP code

No
EmptyResult

Doing nothing

No

All of these types derive from the ActionResult class, and many of them have convenient helper methods in the Controller class. We will demonstrate the use of these types of results in subsequent articles.

After receiving and interpreting a request message, a server responds with an HTTP response message:

  • A Status-line
  • Zero or more header (General|Response|Entity) fields followed by CRLF
  • An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
  • Optionally a message-body
  • The following sections each explain of the entities used in an HTTP response message.

    Message Status-Line

    A Status-Line consists of the protocol version followed by a numeric status code and its associated textual phrase. The elements are separated by space SP characters.

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF HTTP Version

A server supporting HTTP version 1.1 will return the following version information:

HTTP-Version = HTTP/1.1

Status Code

The Status-Code element is a 3-digit integer where the first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values ​​for the first digit:

S.N. Code and Description
1 1xx: Informational

It means the request was received and the process is continuing.

2 2xx: Success

It means the action was successfully received, understood, and accepted.

3 3xx: Redirection

It means further action must be taken in order to complete the request.

4 4xx: Client Error

It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error

It means the server failed to fulfill an apparently valid request.

HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all registered status codes. A list of all the status codes has been given in a separate chapter for your reference.

Response Header Fields

We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For now, let's check what Response header fields are.

The response-header fields allow the server to pass additional information about the response which cannot be placed in the Status- Line. These header fields give information about the server and about further access to the resource identified by the Request-URI.

  • Proxy-Authenticate

  • WWW-Authenticate

You can introduce your custom fields in case you are going to write your own custom Web Client and Server.

Examples of Response Message

Now let"s put it all together to form an HTTP response for a request to fetch the hello.htm page from the web server running on site

HTTP/1.1 200 OK Date: Mon, 27 Jul 2009 12:28:53 GMT Server: Apache/2.2.14 (Win32) Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT Content-Length: 88 Content- Type: text/html Connection: Closed Hello, World!

The following example shows an HTTP response message displaying error condition when the web server could not find the requested page:

HTTP/1.1 404 Not Found Date: Sun, 18 Oct 2012 10:36:20 GMT Server: Apache/2.2.14 (Win32) Content-Length: 230 Connection: Closed Content-Type: text/html; charset=iso-8859-1 404 Not Found Not Found

The requested URL /t.html was not found on this server.

The following is an example of HTTP response message showing error condition when the web server encountered a wrong HTTP version in the given HTTP request:

HTTP/1.1 400 Bad Request Date: Sun, 18 Oct 2012 10:36:20 GMT Server: Apache/2.2.14 (Win32) Content-Length: 230 Content-Type: text/html; charset=iso-8859-1 Connection: Closed 400 Bad Request Bad Request

Your browser sent a request that this server could not understand.

The request line contained invalid characters following the protocol string.