Network Security Access Restrictions in Silverlight

Microsoft Silverlight will reach end of support after October 2021. Learn more.

The Silverlight runtime supports several primary means for networking applications to connect with remote hosts:

  • WebClient and HTTP classes in the System.Net namespace - these classes use the HTTP or HTTPS protocol for network communication. These classes use the security policy system and policy files described below.

  • Sockets classes in the System.Net.Sockets namespace - these classes provide a low-level sockets interface that can be used for more general network communication using TCP (unicast IP packets). These classes use the security policy system and policy files described below.

  • The UdpAnySourceMulticastClient and UdpSingleSourceMulticastClient class in the System.Net.Sockets namespace -- these classes provide support for UDP multicast clients. These classes were added in Silverlight 4. These classes use a different mechanism for security (multicast security policy protocol) rather than the security policy system and policy files described below. For more information, see Working with Multicast.

In all cases, there is a need to provide security and prevent Silverlight applications from initiating unauthorized connections. Potential networking threats to be mitigated include:

  • Denial of Service (DoS) attacks – A large number of remote hosts are used to attack a target site so that the target is unable to service valid requests.

  • DNS Rebinding attacks – Use DNS to force a remote host to rebind a trusted host name (site of origin) to a victim’s IP address, thus allowing access to a host other than site of origin.

  • Reverse tunnel attack – Use a remote client’s outgoing connection as a back tunnel to the client’s private network.

The security policy system incorporated in Silverlight 2 and later is designed to prevent these networking threats. In addition, the policy system also aims to give administrators more control over which resources a remote client is allowed to connect to.

Past designs for network-capable plugins limited connectivity to the host or site of origin. This meant that a web application could only communicate back to its deploying server, so network applications were allowed to connect to the host from which they were downloaded.

Silverlight 2 and later includes support for cross-domain connectivity which allows an application to access resources from locations other than the site of origin. This is an important feature for enabling Silverlight applications to consume existing services on the web. The security policy system in the Silverlight runtime requires that a policy file be downloaded from a target domain before a network connection is allowed access to a network resource under that target domain. This security policy system affects cross-domain network access for the WebClient and HTTP classes in the System.Net namespace. Network connections for the WebClient and HTTP classes in the System.Net namespace to the site or host of origin do not require a security policy.

Note that cross-domain access to network resources from Silverlight applications may also be limited by other security and firewall policies in place on a domain, local Intranet, and local computer. For example other security and firewall policies may restrict access to URIs of the form http://contoso, while access to a similar URI with a fully-qualified domain name of https://www.contoso.com may be allowed. It is also possible for other security and firewall policies to restrict all cross-domain and local Intranet access from Silverlight  applications even when a client access policy is in place.

For network connections using System.Net.Sockets, the security policy system in Silverlight affects both site-of-origin and cross-domain network access. A security policy is required for any connections using sockets, even when the connection is back to the site of origin.

While the security policy system in Silverlight prevents initiating unauthorized connections and potential networking threats from attacking a local computer or other devices on the local network, these policy checks also pose a barrier to deploying legitimate Silverlight applications. In order to make it easier to write and deploy Silverlight applications which communicate using System.Net.Sockets, Silverlight 4 introduces relaxed restrictions for out-of-browser trusted applications. Using this feature, an out-of-browser Silverlight application with permission from the user is run within an expanded sandbox without the security policy checks for System.Net.Sockets. For general information on out-of-browser support and trusted applications, see the Out-of-Browser Support and Trusted Applications topics.

Caution noteCaution:

In Silverlight 5 and later, system administrators can enable trusted applications to run inside the browser. For more information, see Trusted Applications.

The content in this section provides detailed information on how to use the security policy system in Silverlight 4 and describes the policy file formats that are supported.

Basics of the Security Policy System

Silverlight supports two types of security policy files:

  • Flash policy file - the existing crossdomain.xml policy file used by Adobe Flash. This policy file can only be used by the WebClient and HTTP classes in the System.Net namespace. A Flash policy file must allow access to all domains to be used by the Silverlight runtime.

  • Silverlight policy file - the Silverlight policy file that can be used by the WebClient and HTTP classes in the System.Net namespace and also by the sockets classes in the System.Net.Sockets namespace. This policy file has a different format than the Flash policy file.

Before allowing a connection to a network resource, the Silverlight runtime will try to download a security policy file from the domain that hosts the network resource. There are two different methods used to download the security policy that depend on whether the connection request was from a WebClient or HTTP class or whether the connection request was from sockets.

If the connection request was from a WebClient or an HTTP class to a cross-domain site, the Silverlight runtime tries to download the security policy file using the HTTP protocol. The Silverlight runtime first tries to download a Silverlight policy file with a name of "clientaccesspolicy.xml" at the root of the requested target domain using the HTTP protocol.

If the "clientaccesspolicy.xml" is either not found (the web request returns a 404 status code), returned with an unexpected mime-type, is not valid XML, or has an invalid root node, then the Silverlight runtime will issue a request for the Flash policy file with a name of "crossdomain.xml" at the root of the requested target domain, using the HTTP protocol.

HTTP redirects for the policy file are not allowed. A redirect for a policy file will result in a SecurityException of access denied.

If a "clientaccesspolicy.xml" file is returned, but contains an error other than the ones listed above, then no further cross domain requests to that domain will be allowed.

If a valid "clientaccesspolicy.xml" file is returned, that file will be used as the policy file for that cross-domain request for the remainder of the client session of the Silverlight application, and will be used to determine the validity of all subsequent cross-domain requests to that domain. 

The Flash policy file must allow connections to all domains for it to be used by the Silverlight WebClient and HTTP classes in the System.Net namespace.

If a Silverlight policy file is returned (even if there is an error in parsing the file), it is used as the policy file for that cross-domain request and all subsequent requests to that server for the entire session of the Silverlight application. If a Silverlight policy file is not found, the Silverlight runtime then tries to download a Flash policy named "crossdomain.xml" at the root of the requested target domain using the HTTP protocol. The Flash policy file must allow connections to all domains for it to be used by the Silverlight WebClient and HTTP classes in the System.Net namespace.

In Silverlight 3 for a connection request using System.Net.Sockets to the site (cross-domain or site of origin), the Silverlight runtime tries to open a connection using TCP to a well-known port (port 943) on the target site. If a TCP connection can be established, the Silverlight runtime sends the special string <policy-file-request/> to the server to request a Silverlight socket policy file. The Silverlight runtime then waits to receive a reply from the target site that contains a Silverlight policy file. If this Silverlight socket policy file is returned (even if there is an error in parsing the file), it is used as the policy file for that socket request and all subsequent requests to that target site for the entire session of the Silverlight application.

If the policy file retrieved is successfully parsed and grants permission, a connection is finally opened to the target host. If the policy file retrieved is invalid and cannot be correctly parsed, then connections to the network resource are denied by the Silverlight runtime and any connection requests will fail. If no policy file is found, then connections to the network resource are denied by the Silverlight runtime and any connection requests will fail.

In Silverlight 4 for a connection request using System.Net.Sockets, an application can choose instead to retrieve the policy file via the HTTP protocol on TCP port 80 instead of the custom TCP protocol on port 943. This allows HTTP servers that are already running HTTP services to authorize socket connections from Silverlight applications without having to deploy a new TCP service on the machine and open a port through a firewall for port 943. The socket policy file is retrieved via HTTP using as the Host the resolved IP address where the socket connection is targeted. Changes to the network configuration may be needed to allow access to this resolved IP address. Once the policy file is retrieved and successfully parsed, this results in an authoritative machine-wide policy for machine resources such as sockets to connect to the target host. In contrast, the policy file for use by the WebClient and HTTP classes in the System.Net namespace is retrieved from the host domain that is targeted by the HTTP request. The HTTP protocol allows for isolation of resources on a per domain basis through the Host header.

To use HTTP to retrieve the socket policy file, an application should set the SocketAsyncEventArgs.SocketClientAccessPolicyProtocol property to Http on the System.Net.Sockets.SocketAsyncEventArgs instance passed to the Socket.ConnectAsync method.

To use TCP and port 943 to retrieve the socket policy file, an application should set the SocketAsyncEventArgs.SocketClientAccessPolicyProtocol property to Tcp on the System.Net.Sockets.SocketAsyncEventArgs instance passed to the Socket.ConnectAsync method.

One additional restriction on using the sockets classes is that the destination port range that a network application is allowed to connect to must be within the range of 4502-4534. These are the only destination ports allowed by a connection from a Silverlight application using sockets. If the target port is not within this port range, the attempt to connect will fail. It is possible for a target server to receive connections on a port from this restricted range and redirect it to a different port (a well-known port, for example) if this is needed to support a specific existing application protocol.

To deploy a policy file for use by connections from the WebClient and HTTP classes, system administrators need to configure a web service for each IP address that is to provide the policy file definition and make the Silverlight or Flash policy file available over HTTP.

To deploy a socket policy file on a server for sockets in Silverlight 3, system administrators need to configure a separate authentication service on port 943 for each IP address that is to provide the policy file definition. 

To deploy a policy file on a server for sockets in Silverlight 4, system administrators can choose to use the above method on port 943 or use HTTP port 80. For use with HTTP, system administrators need to configure a web service for each IP address that is to provide the policy file definition and make the Silverlight policy file available over HTTP. The policy file for sockets must be stored in the "clientaccesspolicy.xml" file at the root of a web server that responds for the resolved IP address of the target connection request. In contrast, the policy file for use by the WebClient and HTTP classes in the System.Net namespace is retrieved from a web server that responds for the domain that is targeted by the HTTP request. If a web server is configured to host only a single domain and to also respond to requests to the server IP address for the socket connection, then the policy sections for sockets can be combined with the Silverlight policy file used for the WebClient and HTTP classes, if one is used.

Trusted Applications and Elevated Trust

In Silverlight 4 and later, the Silverlight runtime offers relaxed security policy checks for network applications that run as out-of browser applications with elevated trust. Using this feature, an out-of-browser Silverlight application can be configured in its manifest as a trusted application that needs to run with elevated trust. The user is warned when trying to install a trusted application and must provide consent. If the user gives consent, the Silverlight trusted application is run within an expanded sandbox which allows it to access network and local resources that a normal Silverlight application is explicitly denied the ability to access for security reasons.

In Silverlight 4 and later, trusted applications have been given permission to use the WebClient and HTTP classes in the System.Net namespace without policy checks. For example, an application installed from one domain using the HTTP protocol can access media files from a cross-domain site using the HTTPS protocol.

In Silverlight 4 and later, trusted applications have also been given permission to use the networking classes in the System.Net.Sockets namespace including the new UdpAnySourceMulticastClient and UdpSingleSourceMulticastClient classes without policy checks. A trusted application is able to create a TCP connection to any port on any host without the need for a cross-domain policy file. The destination port is no longer required to be within the range of 4502-4534. Similarly, a trusted application using the UdpAnySourceMulticastClient and UdpSingleSourceMulticastClient classes is able to join any multicast group on any port greater than or equal to 1024 without the need for a policy responder to authorize the connection. No extra method calls are needed in order to take advantage of these changes. The existing methods do not require the policy checks when an out-of-browser application is running with elevated trust as a trusted application.

On Silverlight 4, an in-browser Silverlight application or a non-elevated out-of-browser Silverlight application has to meet all of the security policy check requirements. A non-elevated Silverlight application will continue to throw a System.Net.Sockets.SocketException with the SocketException.SocketErrorCode property set to SocketError.AccessDenied if the security policy check fails.

For more information on out-of-browser support and trusted applications, see the Out-of-Browser Support and Trusted Applications topics.

Caution noteCaution:

In Silverlight 5 and later, system administrators can enable trusted applications to run inside the browser. For more information, see Trusted Applications.

Silverlight Policy File Format

The Silverlight policy file format is described below using a DTD.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- A DTD for the Silverlight Policy File -->

<!ELEMENT access-policy (cross-domain-access)>

<!ELEMENT cross-domain-access (policy+)>

<!ELEMENT policy (allow-from)>

<!ELEMENT policy (grant-to)>

<!ELEMENT allow-from (domain+)>

<!ATTLIST allow-from http-request-headers CDATA>

<!ELEMENT domain EMPTY >

<!ATTLIST domain uri CDATA #REQUIRED>

<!ELEMENT allow-from http-methods CDATA>

<!ELEMENT grant-to (resource+)>

<!ELEMENT grant-to (socket-resource+)>

<!ELEMENT grant-to EMPTY>

<!ATTLIST resource path CDATA #REQUIRED>

<!ATTLIST resource include-subpaths (true|false) "false">

<!ATTLIST socket-resource port CDATA #REQUIRED protocol #REQUIRED>

<!-- End of file. --><!-- End of file. -->

The following table describes the possible ELEMENT entries.

Element

Child of

Required

Allow Multiple

Description

access-policy

N/A (root)

Yes

No

The root element of a Silverlight policy file.

cross-domain-access

access-policy

Yes

No

Defines all of the cross domain policies for a site.

policy

cross-domain-access

Yes

Yes

Defines a cross domain policy for requests coming from a certain domain or set of domains.

Multiple policies can be defined in the same file.

allow-from

policy

Yes

No

Defines all the domains that are affected by this policy. Defines the sites that are allowed to access resources in a certain policy.

By using the allow-from element for a particular policy, you implicitly deny access for all non-listed domains.

If allow-from is empty, then the policy file grants access to no sites.

domain

allow-from- or -

allow-from http-methods

Yes

Yes

Defines a domain (or a specific Silverlight application) that is affected by this policy.

grant-to

policy

Yes

No

Defines all the server’s resources that are affected by this policy.

resource

grant-to

Yes (for WebClient and HTTP classes)

Yes

Defines the resources that can be accessed in a certain policy.

This element applies only to connection requests that use WebClient and HTTP classes.

socket-resource

grant-to

Yes (for sockets)

Yes

Defines the socket resources that can be accessed in a certain policy.

This element applies only to connection requests that use sockets.

The following table describes the possible ATTRIBUTE entries allowed on an ELEMENT.

Element

Attribute

Required

Default

Description

allow-from

http-request-headers

No

No headers are allowed, except for the Content-Type header, which is always permitted.

A case-insensitive, comma-separated list of allowed headers for the domain specified in the domain attribute. Valid characters, per RFC822, are ASCII 33-41, 42-57, and 59-126. This includes all printable non-space ASCII characters except colons (which end a header name), and asterisks (which are used as wildcards).

Wildcards can be used to specify all headers, or can be used with a single header name as a suffix allowing for all headers that start with the string value preceding the wildcard character. The '*' character used alone is interpreted as all request headers can be sent that are normally allowed with the HttpWebRequest class.

Some common headers are considered restricted and are either exposed directly (Content-Type, for example) or are protected by the system and cannot be set or changed. For more information on restricted headers, see WebHeaderCollection.

If this attribute is missing, no headers are allowed to be sent except the Content-Type header.

allow from

http-methods

No

Only the GET and POST method are allowed by the client HTTP handler.

Defines whether the client HTTP handler allows custom request methods other than GET and POST to be used. This policy only applies if the HTTP handler for a URI is changed to use the client HTTP handler.The default browser HTTP handler allows only the GET and POST request methods to be used.The only possible value for the request methods allowed by this policy element is the wildcard of "*".

domain

uri

Yes

N/A

Lists the allowed domains and specific Silverlight applications that can access the granted paths in this policy. The uri specifies a scheme and a domain that connections are allowed from. The scheme and port may be specified.

Three types of wildcards are accepted:

1. The standalone '*' wildcard character used alone is interpreted as accept all connections from the same schemed applications hosted on any domain.

2. The "http://*" literal wildcard option is interpreted as accept all connections from HTTP schemed applications on any domain.

3. A subdomain wildcard option is represented as a scheme allowed followed by a '*' character and a '.' character followed by the rest of hostname. The wildcard is used as the first segment of the hostname. This is considered a subdomain wildcard. An attribute value of "http://*.contoso.com" allows only HTTP for the scheme and accepts connections from Silverlight applications hosted on any subdomain of "contoso.com".

resource

path

Yes (for WebClient and HTTP classes)

N/A

The attribute is the URI relative to root of the domain. It refers to a specific path that can represent a web service or a file.

The path cannot contain wildcard characters or characters not recognized by Uniform Resource Identifier (URI): Generic Syntax, http://ietf.org/rfc/rfc3986

This element and attribute are used solely for requests from WebClient and HTTP classes.

resource

include-subpaths

No

False

Specifies whether subpaths of the associated path should be included.

A true value will allow a path to match the exact path designated by the path attribute or the path designated by the path attribute and any appended subpaths.

A false value will only allow a match to the exact path designated by the path attribute. The default value is false if this attribute is omitted.

This element and attribute are used solely for requests from WebClient and HTTP classes.

socket-resource

port

Yes

N/A

Specifies the port or port range that an application using sockets is allowed to connect to.

This element and attribute are used solely for requests from socket classes.

socket-resource

protocol

Yes

N/A

Specifies the protocol that an application using sockets is allowed to connect with.

The only protocol currently supported is tcp.

This element and attribute are used solely for requests from socket classes.

The uri attribute of the domain element refers to the domains and specific Silverlight applications that are granted access to the paths specified by the <grant-to> element tags within the policy file. The included domain must exactly match the requesting domain. For example, a domain uri="https://contoso.com" only allows access from https://contoso.com, not from http://web.contoso.com.

There are three types of wildcards allowed:

  1. A standalone '*' wildcard. This option is used to allow access to all domains of the same scheme. An HTTP service will allow all HTTP callers. An HTTPS service will allow all HTTPS callers.

  2. An "http://*" literal wildcard. This option explicitly allows all HTTP callers, even if this is an HTTPS service. It is almost always a security error for an HTTPS service to allow HTTP callers since this allows the possibility for untrusted code to be injected into a legitimate service (a man in the middle attack) and access data that is supposed to be secured via the HTTPS protocol.

  3. A subdomain wildcard. This option uses a wildcard at the first segment of the path ("http://*.contoso.com", for example) that allows all subdomains of the domain specified. So for the example. http://web.contoso.com and http://mail.contoso.com would be allowed. Note that a uri path where the wildcard does not occur as a prefix (http://web.*.com, for example) is disallowed.

The Silverlight policy file allows connections to an HTTPS service using a cross- domain policy file. When an explicit allow-from attribute on a domain element is provided in the policy, that domain includes the scheme information. An example would be the following:

<allow-from>

<domain uri="https://contoso.com">

</allow-from>).

This above policy would allow only connection from https://contoso.com using the HTTPS scheme.

The wildcard behavior of a Silverlight policy file for a standalone '*' wildcard depends on the type of service being accessed:

HTTP Service

<domain uri="*"/>

HTTPS Service

<domain uri="*"/>

HTTP-hosted Silverlight application

Allowed by Silverlight.

Some browsers may prohibit or discourage HTTP access from HTTPS-hosted sites.

Denied

HTTPS-hosted Silverlight application

Allowed

Allowed

This wildcard behavior allows all Silverlight applications hosted on HTTP and HTTPS to connect to an HTTP service. This allows only Silverlight applications hosted on HTTPS to connect to an HTTPS service.

The wildcard behavior of a Silverlight policy file for an "http://*" literal wildcard depends on the type of service being accessed:

HTTP Service

<domain uri="http://*"/>

HTTPS Service

<domain uri="http://*"/>

HTTP-hosted Silverlight application

Allowed

Allowed

HTTPS-hosted Silverlight application

Denied

Denied

This behavior for "http://*" literal wildcard allows all Silverlight applications hosted on HTTP to connect to an HTTP or HTTPS service. It is almost always a security error for an HTTPS service to allow HTTP callers since this allows the possibility for untrusted code to be injected into a legitimate service (a man in the middle attack) and access data that is supposed to be secured via the HTTPS protocol.

The wildcard behavior of a Silverlight policy file for an "https://*" literal wildcard depends on the type of service being accessed:

HTTP Service

<domain Uri="https://*"/>

HTTPS Service

<domain uri="https://*"/>

HTTP-hosted Silverlight application

Denied

Denied

HTTPS-hosted Silverlight application

Allowed by Silverlight

Some browsers may prohibit or discourage HTTP access from HTTPS-hosted sites.

Allowed

This behavior for "http://*" literal wildcard allows all Silverlight applications hosted on HTTP to connect to an HTTP or HTTPS service.

Caution noteCaution:

It is almost always a security error for an HTTPS service to allow HTTP callers since this allows the possibility for untrusted code to be injected into a legitimate service (a man in the middle attack) and access data that is supposed to be secured via the HTTPS protocol.

If an HTTPS service wants to allow all connections from both HTTP and HTTPS, then there are two methods to accomplish this on Silverlight .

One method is that the policy file must include domain uri entries for both the standalone '*' wildcard and the "http://*" literal wildcard. An example would be the following:

<allow-from>

<domain uri=*">

<domain uri="http://*">

</allow-from>).

A second method is that the policy file must include domain uri entries for both the standalone "http://*" literal wildcard and the "https://*" literal wildcard. An example would be the following:

<allow-from>

<domain uri="http://*">

<domain uri="https://*">

</allow-from>).

You implicitly deny access for all domains not listed in a <domain> element tag in a Silverlight policy file.

Each domain must be in the following BNF format:

  • domain = "http:"|"https:" authority

  • authority = host [ ":" port ]

  • host = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )

  • port = *DIGIT

Each Silverlight application uri is an absolute uri with no query or fragment for an .html, .xaml, or .xap file.

The Silverlight policy file allows custom methods other than GET and POST to be allowed when the client HTTP handler has been specified for a URI. The default browser HTTP handler allows only GET and POST requests to be used. When an allow-from http-methods element is specified, the allowed request methods must be specified as the wildcard of "*". The domain includes the scheme information. An example would be the following:

<allow-from http-methods="*">

<domain uri="*">

</allow-from>).

This above policy would allow only custom requests other than GET and POST requests to be used by the client HTTP handler. The allow-from http-methods policy element was added for Silverlight 3. This policy element is not recognized by Silverlight 2 clients. If a server needs to support both Silverlight 3  and Silverlight 2 clients, then the policy file should contain two policy sections, one with the allow-from http-methods policy element and one with the allow-from policy element. An example would be the following:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
<!--Enables Silverlight 3 all methods functionality-->
    <policy>
      <allow-from http-methods="*">      
        <domain uri="*"/>
      </allow-from>      
      <grant-to>      
        <resource path="/api" include-subpaths="true"/>
      </grant-to>      
    </policy>
<!--Enables Silverlight 2 clients to continue to work normally -->
    <policy>
      <allow-from >      
        <domain uri="*"/>
      </allow-from>      
      <grant-to>      
        <resource path="/api" include-subpaths="true"/>
      </grant-to>      
    </policy>
  </cross-domain-access>
</access-policy>

If both HTTP and HTTPS services are provided for a domain, you should provide a client access policy specific to each protocol for the domain. In the client access policy file, you should only enable calls from the same protocol as the hosting domain. For example, if the domain is https://contoso.com, the policy file for this domain should only enable Silverlight clients using the HTTPS protocol like the following example.

<allow-from>

<domain uri="https://fabrikam.com"/>

</allow-from>

Caution noteCaution:

To prevent malicious attacks, you should never provide one client access policy file for both HTTP and HTTPS services on your domain that enable calls from both HTTP and HTTPS clients.

A single Silverlight policy file can have policies included for connection requests from WebClient and HTTP classes in the System.Net namespace and also policies for connection requests from sockets.

The process to determine if a request is permissible with the policy file is as follows:

Is the scheme of the requested URI the same as the application’s site of origin? Is HTTP the scheme of the requested URI and the scheme of the application's site of origin is HTTPS? Is HTTPS the scheme of the requested URI and the scheme of the application's site of origin is HTTP If not one of these three cases, the request does not have access and should not be sent.

For each <policy> element:

  • Is the application’s site of origin allowed access? This can be done either explicitly in the <policy> allow-from domain attribute or the allow-from attribute can have a domain element with a wildcard for the uri attribute, indicating that everyone is allowed access. Note that if allow-from is omitted, the default behavior is that nobody is allowed access.

  • Does the policy grant access to the request URI?

If any of the following conditions are true, then the request does have access and should be sent. Otherwise, go to next <policy> in file.

  • The requested URI exactly matches the domain and path in a <resource> tag.

  • The requested URI falls beneath the domain and path in a <grant-to> tag and the <grant-to> tag include-subpaths attribute has the value set to true.

  • For a socket request, the protocol and port attribute in a <socket-resource> tag in the <grant-to> section of this <policy> specifies tcp for the protocol and a port or port range within the allowable range of 4502-4534.

Example Policy Files for WebClient and HTTP Classes

Example 1 - An HTTP Service

A following is an example Silverlight policy file for cross-domain connections using the WebClient and HTTP classes in the System.Net namespace to an HTTP service.This policy file accepts connections from any domain. This policy file limits request headers and does not include subpaths.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>      
        <domain uri="*"/>
      </allow-from>      
      <grant-to>      
        <resource path="/api" include-subpaths="false"/>
      </grant-to>      
    </policy>
  </cross-domain-access>
</access-policy>

For the above policy file, these resources can be accessed from Silverlight HTTP applications hosted on any site:

/api#intro
/api?web=true#intro

For the above policy file, these resources cannot be accessed:

/api/
/api.txt
/api/sample
/api/sample.txt
/api/sample?web=true
/api/sample#intro
/web

For the above policy file, no request headers can be sent except for the Content-Type header that is always allowed.

Example 2 - An HTTP Service

A following is an example Silverlight policy file for cross-domain connections using the WebClient and HTTP classes in the System.Net namespace to an HTTP service. This policy file accepts connections from any domain. This policy file allows request headers and specifies resources that can be accessed and includes subpaths of these resources.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">      
        <domain uri="*"/>
      </allow-from>      
      <grant-to>      
        <resource path="/api" include-subpaths="true"/>
      </grant-to>      
    </policy>
  </cross-domain-access>
</access-policy>

For the above policy file, these resources can be accessed from Silverlight HTTP applications hosted on any site:

/api/sample
/api/sample.xml
/api/sample?web=true
/api#intro
/api?web=true#intro

For the above policy file, these resources cannot be accessed:

/web

For the above policy file, all request headers can be sent that are normally allowed with the HttpWebRequest class.

Example 3 - An HTTP Service

The following is an example Silverlight policy file for cross-domain connections using the WebClient and HTTP classes in the System.Net namespace to an HTTP service. This policy file accepts connections only from the domains and scheme specified. This policy file specifies specific request headers and specifies resources that can be accessed.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="MyHeader, X-API-*">      
        <domain uri="http://electronics.fabrikam.com"/>
        <domain uri="http://books.fabrikam.com"/>
        <domain uri="https://contoso.com:8080"/>
      </allow-from>      
      <grant-to>      
        <resource path="/costcalculations"/>
      </grant-to>      
    </policy>
  </cross-domain-access>
</access-policy>

For the above policy, the Silverlight HTTP applications listed below are allowed to have access to /costcalculations:

http://electronics.fabrikam.com/sample/app.xap
http://books.fabrikam.com/web/sample/app.html
https://contoso.com:8080/sample/app.xap

For the above policy, the Silverlight applications listed below are not allowed to have access to /costcalculations:

http://electronics.fabrikam.com:8080/sample/app.xap
http://electronics.fabrikam.com:8080/sample/app.xap
http://bar.com/sample/app.xaml
https://bar.com/sample/app.html

The following HTTP request headers can be sent (in addition to the Content-Type header that is always allowed):

MyHeader
all headers starting with X-API-

Example 4 - An HTTPS Service

The following is an example Silverlight policy file for cross-domain connections using the WebClient and HTTP classes in the System.Net namespace to an HTTPS service. This policy file accepts connections from any domain. This policy file limits request headers and specifies resources that can be accessed.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>      
        <domain uri="*"/>
      </allow-from>      
      <grant-to>      
        <resource path="/costcalculations"/>
      </grant-to>      
    </policy>
  </cross-domain-access>
</access-policy>

For the above policy file, Silverlight HTTPS applications hosted on any site are allowed to have access to /costcalculations.

For the above policy file, no request headers can be sent except the Content-Type header that is always allowed.

For the above policy, the Silverlight applications listed below are allowed to have access to /costcalculations:

https://electronics.fabrikam.com/sample/app.xap
https://books.fabrikam.com/web/sample/app.html
https://contoso.com:8080/app.xap

For the above policy, the Silverlight applications listed below are not allowed to have access to /costcalculations:

http://electronics.fabrikam.com/sample/app.xap
http://books.fabrikam.com/web/sample/app.html
https://contoso.com:8080/app.xap
http://bar.com/app.html

Example Policy File for Sockets

A following is a sample Silverlight policy file for connections using sockets.

<?xml version="1.0" encoding ="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>
        <domain uri="file:///" />
      </allow-from>
      <grant-to>
        <socket-resource port="4502-4506" protocol="tcp" />
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Sample Code for a Policy Server for Sockets

The follow sample implements a simple policy server for sockets in managed code that listens on port 943 for requests to retrieve the policy file to use by sockets. The sample policy server requires the name of the policy file to use as an argument when the server is started. If a name is not specified on the command-line, the sample code defaults to a policy file named PolicyFile.xml.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace PolicyServer
{
    // Encapsulate and manage state for a single connection from a client
    class PolicyConnection
    {
        private Socket m_connection;

        // buffer to receive the request from the client
        private byte[] m_buffer;
        private int m_received;

        // the policy to return to the client
        private byte[] m_policy;

        // the request that we're expecting from the client
        private static string s_policyRequestString = "<policy-file-request/>";



        public PolicyConnection(Socket client, byte[] policy)
        {
            m_connection = client;
            m_policy = policy;

            m_buffer = new byte[s_policyRequestString.Length];
            m_received = 0;

            try
            {
                // receive the request from the client
                m_connection.BeginReceive(m_buffer, 0, s_policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
            }
            catch (SocketException)
            {
                m_connection.Close();
            }
        }

        // Called when we receive data from the client
        private void OnReceive(IAsyncResult res)
        {
            try
            {
                m_received += m_connection.EndReceive(res);

                // if we haven't gotten enough for a full request yet, receive again
                if (m_received < s_policyRequestString.Length)
                {
                    m_connection.BeginReceive(m_buffer, m_received, s_policyRequestString.Length - m_received, SocketFlags.None, new AsyncCallback(OnReceive), null);
                    return;
                }

                // make sure the request is valid
                string request = System.Text.Encoding.UTF8.GetString(m_buffer, 0, m_received);
                if (StringComparer.InvariantCultureIgnoreCase.Compare(request, s_policyRequestString) != 0)
                {
                    m_connection.Close();
                    return;
                }

                // send the policy
                m_connection.BeginSend(m_policy, 0, m_policy.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
            }
            catch (SocketException)
            {
                m_connection.Close();
            }
        }

        // called after sending the policy to the client; close the connection.
        public void OnSend(IAsyncResult res)
        {
            try
            {
                m_connection.EndSend(res);
            }
            finally
            {
                m_connection.Close();
            }
        }
    }

    // Listens for connections on port 943 and dispatches requests to a PolicyConnection
    class PolicyServer
    {
        private Socket m_listener;
        private byte[] m_policy;

        // pass in the path of an XML file containing the socket policy
        public PolicyServer(string policyFile)
        {
            // Load the policy file
            FileStream policyStream = new FileStream(policyFile, FileMode.Open);

            m_policy = new byte[policyStream.Length];
            policyStream.Read(m_policy, 0, m_policy.Length);

            policyStream.Close();


            // Create the Listening Socket
            m_listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

            // Put the socket into dual mode to allow a single socket 
            // to accept both IPv4 and IPv6 connections
            // Otherwise, server needs to listen on two sockets,
            // one for IPv4 and one for IPv6
            // NOTE: dual-mode sockets are supported on Vista and later
            m_listener.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);

            m_listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 943));
            m_listener.Listen(10);

            m_listener.BeginAccept(new AsyncCallback(OnConnection), null);
        }

        // Called when we receive a connection from a client
        public void OnConnection(IAsyncResult res)
        {
            Socket client = null;

            try
            {
                client = m_listener.EndAccept(res);
            }
            catch (SocketException)
            {
                return;
            }

            // handle this policy request with a PolicyConnection
            PolicyConnection pc = new PolicyConnection(client, m_policy);

            // look for more connections
            m_listener.BeginAccept(new AsyncCallback(OnConnection), null);
        }

        public void Close()
        {
            m_listener.Close();
        }
    }



    public class Program
    {
        static void Main(string[] args)
        {
            string PolicyFile = (args.Length == 0) ? "PolicyFile.xml" : args[0];
            if (args.Length == 0) 
            {
                Console.WriteLine("No policy file specified; using PolicyFile.xml");
            }
            PolicyServer ps = new PolicyServer(PolicyFile);
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
        }

    }
}