11.07.2015 Views

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: Code Access <strong>Security</strong> in Practice 213Sockets <strong>and</strong> DNSCode that uses sockets directly by using the System.Net.Sockets.Socket class mustbe granted the SocketPermission by code access security policy. In addition, if yourcode uses DNS to map host names to IP addresses, it requires the DnsPermission.You can use SocketPermission to constrain access to specific ports on specific hosts.You can also restrict whether the socket can be used to accept connections or initiateoutbound connections, <strong>and</strong> you can restrict the transport protocol, for example,Transmission Control Protocol (TCP) or User Datagram Protocol (UDP).Constraining Socket AccessTo constrain code so that it can only use sockets in a restricted way, you can use theSocketPermissionAttribute together with <strong>Security</strong>Action.PermitOnly. Thefollowing attributes ensure that the code can connect only to a specific port on aspecific host using the TCP protocol. Because the code also calls Dns.Resolve toresolve a host name, the code also requires the DnsPermission.[SocketPermissionAttribute(<strong>Security</strong>Action.PermitOnly,Access="Connect",Host="hostname",Port="80",Transport="Tcp")][DnsPermissionAttribute(<strong>Security</strong>Action.PermitOnly, Unrestricted=true)]public string MakeRequest(string hostname, string message){Socket socket = null;IPAddress serverAddress = null;IPEndPoint serverEndPoint = null;byte[] sendBytes = null, bytesReceived = null;int bytesReceivedSize = -1, readSize = 4096;}serverAddress = Dns.Resolve(hostname).AddressList[0];serverEndPoint = new IPEndPoint(serverAddress, 80);socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);bytesReceived = new byte[readSize];sendBytes = Encoding.ASCII.GetBytes(message);socket.Connect(serverEndPoint);socket.Send(sendBytes);bytesReceivedSize = socket.Receive(bytesReceived, readSize, 0);socket.Close();if(-1 != bytesReceivedSize){return Encoding.ASCII.GetString(bytesReceived, 0, bytesReceivedSize);}return "";

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!