Sulich's Blog

Sulich's Blog

Limiting Access to Office 365 Services Based on the Location of the Client

https://technet.microsoft.com/en-us/library/hh526961(v=ws.10).aspx#build

 

Some organizations may want to create policies that limit access to Microsoft ® Office 365 services, depending on where the client resides. For example, you might want to:

  • Block all extranet client access to Office 365
  • Block all extranet client access to Office 365, except for devices accessing Exchange Online for Exchange Active Sync

Active Directory Federation Services (AD FS) 2.0 provides a way for organizations to configure these types of policies. Office 365 customers using Single Sign-On (SSO) who require these policies can now use client access policy rules to restrict access based on the location of the computer or device that is making the request. Customers using Microsoft Online Services cloud User IDs cannot implement these restrictions at this time.

For more information about how to deploy AD FS 2.0 for SSO to Office 365, see Plan for and deploy AD FS 2.0 for use with single sign-on to Office 365 on the Office 365 content portal.

An AD FS 2.0 federation server proxy or a third-party proxy is required to forward requests from clients residing outside the corporate network to the internal Federation Service.

noteNote
If you are using a third-party proxy, it must be configured to do the following:

  1. Send an HTTP header named x-ms-proxy. The value of this header should be the DNS name of the proxy host.
  2. Send an HTTP header named x-ms-endpoint-absolute-path. The value of this header should be set to the name of the proxy endpoint that received the request.

Otherwise, an AD FS 2.0 federation server proxy must be deployed behind the third-party proxy.

noteNote
Scenario 3: Block all external access to Office 365 except browser-based applications is not supported with a third-part proxy because of limitations on client access policy headers with passive (Web-based) requests.

For more information about the use of third-party proxies with AD FS 2.0, see Using a Third-Party Proxy as a Replacement to an AD FS 2.0 Federation Server Proxy.

Client access policy works by identifying which authentication requests should be permitted based upon attributes of the request itself. To provide this additional request context information, client access policy introduces a set of new claim types that AD FS populates from header information sent by the requesting client. For a detailed description of the new claim types and values, see New Claim Types.

The following table describes the scenarios supported by the client access policy feature.

Scenario Description
Block all external access to Office 365 Office 365 access is allowed from all clients on the internal corporate network, but requests from external clients are denied based on the IP address of the external client.
Block all external access to Office 365, except Exchange ActiveSync Office 365 access is allowed from all clients on the internal corporate network, as well as from any external client devices, such as smart phones, that make use of Exchange ActiveSync. All other external clients, such as those using Outlook, are blocked.
Block all external access to Office 365, except for browser-based applications such as Outlook Web Access or SharePoint Online Blocks external access to Office 365, except for passive (browser-based) applications such as Outlook Web Access or SharePoint Online.
Block all external access to Office 365 for members of designated Active Directory groups This scenario is used for testing and validating client access policy deployment. It blocks external access to Office 365 only for members of one or more Active Directory group. It can also be used to provide external access only to members of a group.
noteNote
The following client access policy scenarios have the effect of blocking external access to Microsoft Lync Online and Office Subscription Services:

  • Scenario 1: Block all external access to Office 365
  • Scenario 2: Block all external access to Office 365 except Exchange ActiveSync
  • Scenario 3: Block all external access to Office 365 except browser-based applications

To enable client access policy, you must complete the following steps:

Download the Update Rollup 2 for Active Directory Federation Services (AD FS) 2.0 package and install it on all federation server and federation server proxies.

For more information about the fixes, new capabilities, download location and installation instructions associated with this package, see Description of Update Rollup 2 for Active Directory Federation Services (AD FS) 2.0 on the Microsoft Support site.

 

After the Update Rollup 2 for Active Directory Federation Services (AD FS) 2.0 package has been installed on all federation servers and federation server proxies, and the AD FS Windows service has been restarted, use the following procedure to add a set of claim rules that make the new claim types available to the policy engine.

In this step, you will have to add five acceptance transform rules for each of the new request context claim types using the following procedure.

On the Active Directory claims provider trust, create a new acceptance transform rule to pass through each of the new request context claim types.

 

  1. Click Start, point to Programs, point to Administrative Tools, and then click AD FS 2.0 Management.
  2. In the console tree, under AD FS 2.0\Trust Relationships, click Claims Provider Trusts, right-click Active Directory, and then click Edit Claim Rules.
  3. In the Edit Claim Rules dialog box, select the Acceptance Transform Rules tab, and then click Add Rule to start the Rule wizard.
  4. On the Select Rule Template page, under Claim rule template, select Pass Through or Filter an Incoming Claim from the list, and then click Next.
  5. On the Configure Rule page, under Claim rule name, type the display name for this rule; in Incoming claim type, type the following claim type URL, and then select Pass through all claim values.
    http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip
    
  6. To verify the rule, select it in the list and click Edit Rule, then click View Rule Language. The claim rule language should appear as follows:c:[Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip"] => issue(claim = c);
  7. Click Finish.
  8. In the Edit Claim Rules dialog box, click OK to save the rules.
  9. Repeat steps 2 through 6 to create an additional claim rule for each of the remaining four claim types shown below until all five rules have been created.
    • http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-application
      
    • http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-user-agent
      
    • http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy
      
    • http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-endpoint-absolute-path
      

Choose one of the example scenarios below to configure the claim rules on the Microsoft Office 365 Identity Platform relying party trust that best meets the needs of your organization.

noteNote
To ensure that the client access policy scenario works, verify that you have completed the instructions under To add a claim rule to the Active Directory claims provider trust for each of the five context claim types.

The client access policy scenario allows access from all internal clients and blocks all external clients based on the IP address of the external client. The rule set builds on the default Issuance Authorization rule Permit Access to All Users. You can use the following procedure to add an Issuance Authorization rule to the Office 365 relying party trust.

  1. Click Start, point to Programs, point to Administrative Tools, and then click AD FS 2.0 Management.
  2. In the console tree, under AD FS 2.0\Trust Relationships, click Relying Party Trusts, right-click the Microsoft Office 365 Identity Platform trust, and then click Edit Claim Rules.
  3. In the Edit Claim Rules dialog box, select the Issuance Authorization Rules tab, and then click Add Rule to start the Claim Rule Wizard.
  4. On the Select Rule Template page, under Claim rule template, select Send Claims Using a Custom Rule, and then click Next.
  5. On the Configure Rule page, under Claim rule name, type the display name for this rule. Under Custom rule, type or paste the following claim rule language syntax:
    exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip",
    Value=~"customer-provided public ip address regex"])
    => issue(Type = "http://schemas.microsoft.com/authorization/claims/deny", Value = "true"); 
    
    

    You will have to replace the value above for “public ip address regex” with a valid IP expression; see Building the IP address range expression for more information.

  6. Click Finish. Verify that the new rule appears immediately below the Permit Access to All Users rule in the Issuance Authorization Rules list.
  7. To save the rule, in the Edit Claim Rules dialog box, click OK.

The following example allows access to all Office 365 applications, including Exchange Online, from internal clients including Outlook. It blocks access from clients residing outside the corporate network, as indicated by the client IP address, except for Exchange ActiveSync clients such as smart phones. The rule set builds on the default Issuance Authorization rule titled Permit Access to All Users. Use the following steps to add an Issuance Authorization rule to the Office 365 relying party trust using the Claim Rule Wizard:

  1. Click Start, point to Programs, point to Administrative Tools, and then click AD FS 2.0 Management.
  2. In the console tree, under AD FS 2.0\Trust Relationships, click Relying Party Trusts, right-click the Microsoft Office 365 Identity Platform trust, and then click Edit Claim Rules.
  3. In the Edit Claim Rules dialog box, select the Issuance Authorization Rules tab, and then click Add Rule to start the Claim Rule Wizard.
  4. On the Select Rule Template page, under Claim rule template, select Send Claims Using a Custom Rule, and then click Next.
  5. On the Configure Rule page, under Claim rule name, type the display name for this rule. Under Custom rule, type or paste the following claim rule language syntax:
    exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-application",
    Value=="Microsoft.Exchange.Autodiscover"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-application",
    Value=="Microsoft.Exchange.ActiveSync"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip",
    Value=~"customer-provided public ip address regex"])
    => issue(Type = "http://schemas.microsoft.com/authorization/claims/deny", Value = "true");
    

    You will have to replace the value above for “public ip address regex” with a valid IP expression; see Building the IP address range expression for more information.

  6. Click Finish. Verify that the new rule appears immediately below the Permit Access to All Users rule in the Issuance Authorization Rules list.
  7. To save the rule, in the Edit Claim Rules dialog box, click OK.

 

The rule set builds on the default Issuance Authorization rule titled Permit Access to All Users. Use the following steps to add an Issuance Authorization rule to the Microsoft Office 365 Identity Platform relying party trust using the Claim Rule Wizard:

noteNote
This scenario is not supported with a third-party proxy because of limitations on client access policy headers with passive (Web-based) requests.
  1. Click Start, point to Programs, point to Administrative Tools, and then click AD FS 2.0 Management.
  2. In the console tree, under AD FS 2.0\Trust Relationships, click Relying Party Trusts, right-click the Microsoft Office 365 Identity Platform trust, and then click Edit Claim Rules.
  3. In the Edit Claim Rules dialog box, select the Issuance Authorization Rules tab, and then click Add Rule to start the Claim Rule Wizard.
  4. On the Select Rule Template page, under Claim rule template, select Send Claims Using a Custom Rule, and then click Next.
  5. On the Configure Rule page, under Claim rule name, type the display name for this rule. Under Custom rule, type or paste the following claim rule language syntax:
    exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip",
    Value=~"customer-provided public ip address regex"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-endpoint-absolute-path", Value == "/adfs/ls/"])
    => issue(Type = "http://schemas.microsoft.com/authorization/claims/deny", Value = "true"); 
    

    You will have to replace the value above for “public ip address regex” with a valid IP expression; see Building the IP address range expression for more information.

  6. Click Finish. Verify that the new rule appears immediately below the Permit Access to All Users rule in the Issuance Authorization Rules list.
  7. To save the rule, in the Edit Claim Rules dialog box, click OK.

The following example enables access from internal clients based on IP address. It blocks access from clients residing outside the corporate network that have an external client IP address, except for those individuals in a specified Active Directory Group.The rule set builds on the default Issuance Authorization rule titled Permit Access to All Users. Use the following steps to add an Issuance Authorization rule to the Microsoft Office 365 Identity Platform relying party trust using the Claim Rule Wizard:

  1. Click Start, point to Programs, point to Administrative Tools, and then click AD FS 2.0 Management.
  2. In the console tree, under AD FS 2.0\Trust Relationships, click Relying Party Trusts, right-click the Microsoft Office 365 Identity Platform trust, and then click Edit Claim Rules.
  3. In the Edit Claim Rules dialog box, select the Issuance Authorization Rules tab, and then click Add Rule to start the Claim Rule Wizard.
  4. On the Select Rule Template page, under Claim rule template, select Send Claims Using a Custom Rule, and then click Next.
  5. On the Configure Rule page, under Claim rule name, type the display name for this rule. Under Custom rule, type or paste the following claim rule language syntax:
    exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy"]) &&
    exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", Value =~ "Group SID value of allowed AD group"]) &&
    NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip",
    Value=~"customer-provided public ip address regex"])
    => issue(Type = "http://schemas.microsoft.com/authorization/claims/deny", Value = "true");
    
    

    You will have to replace the value above for “public ip address regex” with a valid IP expression; see Building the IP address range expression for more information.

  6. Click Finish. Verify that the new rule appears immediately below the Permit Access to All Users rule in the Issuance Authorization Rules list.
  7. To save the rule, in the Edit Claim Rules dialog box, click OK.

Description Claim Rule language syntax
Default AD FS rule to Permit Access to All Users. This rule should already exist in the Microsoft Office 365 Identity Platform relying party trust Issuance Authorization Rules list. => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");
Adding this clause to a new, custom rule specifies that the request has come from the federation server proxy (i.e., it has the x-ms-proxy header)

It is recommended that all rules include this.

exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy"])
Used to establish that the request is from a client with an IP in the defined acceptable range. NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip",

Value=~"customer-provided public ip address regex"])

This clause is used to specify that if the application being accessed is not Microsoft.Exchange.ActiveSync the request should be denied. NOT exists([Type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-application",

Value=="Microsoft.Exchange.ActiveSync"])

This rule allows you to determine whether the call was through a Web browser, and will not be denied. NOT exists([Type ==
"http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-endpoint-absolute-path",
Value == "/adfs/ls/"])
This rule states that the only users in a particular Active Directory group (based on SID value) should be denied. Adding NOT to this statement means a group of users will be allowed, regardless of location. exists([Type ==
"http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid",
Value =~ "{Group SID value of allowed AD group}"])
This is a required clause to issue a deny when all preceding conditions are met. => issue(Type = "http://schemas.microsoft.com/authorization/claims/deny", Value = "true");

 

The x-ms-forwarded-client-ip claim is populated from an HTTP header that is currently set only by Exchange Online, which populates the header when passing the authentication request to AD FS. The value of the claim may be one of the following:

noteNote
Exchange Online currently supports only IPV4 and not IPV6 addresses.
  • A single IP address: The IP address of the client that is directly connected to Exchange Online
    noteNote
    • The IP address of a client on the corporate network will appear as the external interface IP address of the organization’s outbound proxy or gateway.
    • Clients that are connected to the corporate network by a VPN or by Microsoft DirectAccess (DA) may appear as internal corporate clients or as external clients depending upon the configuration of VPN or DA.
  • One or more IP addresses: When Exchange Online cannot determine the IP address of the connecting client, it will set the value based on the value of the x-forwarded-for header, a non-standard header that can be included in HTTP-based requests and is supported by many clients, load balancers, and proxies on the market.
    noteNote
    • Multiple IP addresses, indicating the client IP address and the address of each proxy that passed the request, will be separated by a comma.
    • IP addresses related to Exchange Online infrastructure will not appear on the list.

When you have to match a range of IP addresses, it becomes necessary to construct a regular expression to perform the comparison. In the next series of steps, we will provide examples for how to construct such an expression to match the following address ranges (note that you will have to change these examples to match your public IP range):

  • 192.168.1.1 – 192.168.1.25
  • 10.0.0.1 – 10.0.0.14

First, the basic pattern that will match a single IP address is as follows: \b###\.###\.###\.###\b

Extending this, we can match two different IP addresses with an OR expression as follows: \b###\.###\.###\.###\b|\b###\.###\.###\.###\b

So, an example to match just two addresses (such as 192.168.1.1 or 10.0.0.1) would be: \b192\.168\.1\.1\b|\b10\.0\.0\.1\b

This gives you the technique by which you can enter any number of addresses. Where a range of address need to allowed, for example 192.168.1.1 – 192.168.1.25, the matching must be done character by character: \b192\.168\.1\.([1-9]|1[0-9]|2[0-5])\b

noteNote
The IP address is treated as string and not a number.

The rule is broken down as follows: \b192\.168\.1\.

This matches any value beginning with 192.168.1.

The following matches the ranges required for the portion of the address after the final decimal point:

  • ([1-9] Matches addresses ending in 1-9
  • |1[0-9] Matches addresses ending in 10-19
  • |2[0-5]) Matches addresses ending in 20-25
noteNote
Note that the parentheses must be correctly positioned, so that you don’t start matching other portions of IP addresses.

With the 192 block matched, we can write a similar expression for the 10 block: \b10\.0\.0\.([1-9]|1[0-4])\b

And putting them together, the following expression should match all the addresses for “192.168.1.1~25” and “10.0.0.1~14”: \b192\.168\.1\.([1-9]|1[0-9]|2[0-5])\b|\b10\.0\.0\.([1-9]|1[0-4])\b

Regex expressions can become quite tricky, so we highly recommend using a regex verification tool. If you do an internet search for “online regex expression builder”, you will find several good online utilities that will allow you to try out your expressions against sample data.

When testing the expression, it’s important that you understand what to expect to have to match. The Exchange online system may send many IP addresses, separated by commas. The expressions provided above will work for this. However, it’s important to think about this when testing your regex expressions. For example, one might use the following sample input to verify the examples above:

192.168.1.1, 192.168.1.2, 192.169.1.1. 192.168.12.1, 192.168.1.10, 192.168.1.25, 192.168.1.26, 192.168.1.30, 1192.168.1.20

10.0.0.1, 10.0.0.5, 10.0.0.10, 10.0.1.0, 10.0.1.1, 110.0.0.1, 10.0.0.14, 10.0.0.15, 10.0.0.10, 10,0.0.1

To verify that the new request context claims are being sent and are available to the AD FS claims processing pipeline, enable audit logging on the AD FS server. Then send some authentication requests and check for the claim values in the standard security audit log entries.

To enable the logging of audit events to the security log on an AD FS server, follow the steps at Configure auditing for AD FS 2.0

By default, failed requests are logged to the application event log located under Applications and Services Logs \ AD FS 2.0 \ Admin.For more information on event logging for AD FS, see Set up AD FS 2.0 event logging

AD FS tracing events are logged to the AD FS 2.0 debug log. To enable tracing, see Configure debug tracing for AD FS 2.0

After you have enabled tracing, use the following command line syntax to enable the verbose logging level:

wevtutil.exe sl “AD FS 2.0 Tracing/Debug” /l:5

 

To provide additional request context information, Client Access Policy introduces the following new claim types, which AD FS generates from request header information for processing by the policy engine:

Claim type: http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip

This AD FS claim represents a “best attempt” at ascertaining the IP address of the user (for example, the Outlook client) making the request. This claim can contain multiple IP addresses, including the address of every proxy that forwarded the request.  This claim is populated from an HTTP header that is currently only set by Exchange Online, which populates the header when passing the authentication request to AD FS. The value of the claim can be one of the following:

  • A single IP address – The IP address of the client that is directly connected to Exchange Online
    noteNote
    The IP address of a client on the corporate network will appear as the external interface IP address of the organization’s outbound proxy or gateway.
  • One or more IP addresses
    • If Exchange Online cannot determine the IP address of the connecting client, it will set the value based on the value of the x-forwarded-for header, a non-standard header that can be included in HTTP based requests and is supported by many clients, load balancers, and proxies on the market.
    • Multiple IP addresses indicating the client IP address and the address of each proxy that passed the request will be separated by a comma.
      noteNote
      IP addresses related to Exchange Online infrastructure will not be present in the list.
WarningWarning
Exchange Online currently supports only IPV4 addresses; it does not support IPV6 addresses.

Claim type: http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-application

This AD FS claim represents the protocol used by the end client, which corresponds loosely to the application being used.  This claim is populated from an HTTP header that is currently only set by Exchange Online, which populates the header when passing the authentication request to AD FS. Depending on the application, the value of this claim will be one of the following:

  • In the case of devices that use Exchange Active Sync, the value is Microsoft.Exchange.ActiveSync.
  • Use of the Microsoft Outlook client may result in any of the following values:
    • Microsoft.Exchange.Autodiscover
    • Microsoft.Exchange.OfflineAddressBook
    • Microsoft.Exchange.RPC
    • Microsoft.Exchange.WebServices
    • Microsoft.Exchange.Mapi
  • Other possible values for this header include the following:
    • Microsoft.Exchange.Powershell
    • Microsoft.Exchange.SMTP
    • Microsoft.Exchange.PopImap

Claim type: http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-user-agent

This AD FS claim provides a string to represent the device type that the client is using to access the service. This can be used when customers would like to prevent access for certain devices (such as particular types of smart phones).  This claim is populated from an HTTP header that is currently only set by Exchange Online, which populates the header when passing the authentication request to AD FS. Example values for this claim include (but are not limited to) the values below.

noteNote
The below are examples of what the x-ms-user-agent value might contain for a client whose x-ms-client-application is “Microsoft.Exchange.ActiveSync”
  • Vortex/1.0
  • Apple-iPad1C1/812.1
  • Apple-iPhone3C1/811.2
  • Apple-iPhone/704.11
  • Moto-DROID2/4.5.1
  • SAMSUNGSPHD700/100.202
  • Android/0.3
noteNote
It is also possible that this value is empty.

Claim type: http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-proxy

This AD FS claim indicates that the request has passed through the federation server proxy.  This claim is populated by the federation server proxy, which populates the header when passing the authentication request to the back end Federation Service. AD FS then converts it to a claim.

The value of the claim is the DNS name of the federation server proxy that passed the request.

Claim type: http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-endpoint-absolute-path

This claim type can be used for determining requests originating from “active” (rich) clients versus “passive” (web-browser-based) clients. This enables external requests from browser-based applications such as the Outlook Web Access, SharePoint Online, or the Office 365 portal to be allowed while requests originating from rich clients such as Microsoft Outlook are blocked.

The value of the claim is the name of the AD FS service that received the request.

Terminal servers configuration Windows 2012 R2

https://blogs.technet.microsoft.com/askperf/2013/09/20/rd-licensing-configuration-on-windows-server-2012/

 

RD Licensing Configuration on Windows Server 2012

 

Adding a new License Server in a new Deployment

Let us assume that you already have created a Remote Desktop Services Deployment. You have a Session Based Collection and a Virtual Desktop based collection as per your business requirement. Now, you have introduced a new Server in the domain that will serve as a License Server for Remote Desktop Services.

Before you configure Licensing on any Remote Desktop Server Session Host or Virtualization Host server, the RD Licensing Diagnoser looks like below. To open RD Licensing Diagnoser, Click Tools, go to Terminal Services and click RD Licensing Diagnoser.

clip_image002

The image below shows that the RD Session Host Server RDS1.contoso.com neither has a Licensing mode configured nor there is a License server configured for it.

In the RD Licensing Diagnoser Information section, it will throw 2 warning(s):
1. The licensing mode for the Remote Desktop Session Host server is not configured.
2. The Remote Desktop Session Host server is within its grace period, but the RD Session Host server has not been configured with any license server.

clip_image004

Configuring Windows Server 2012 Remote Desktop Services Licensing involves 2 step process.

Note Make sure that the new License Server is already added to the Server Pool on the RD Connection Broker Server before you add it to the deployment.
1. Configuring the Deployment Settings
a. In the Server manager RDMS console Overview page, click on clip_image006 to add a License server which is already added to the domain

clip_image008

b. In the ‘Add RD Licensing Servers’ applet choose the server that you want to add to the deployment from the Server Pool and click Next

clip_image010

c. Click on Add on the Confirmation page and click Add

d. If the Licensing Role Service is not already installed, the Wizard will install the role, reboot the system if required and add it to the Deployment.

clip_image012

e. Once done, the Overview page will look like this

clip_image014

Adding the License server to the deployment will not automatically configure the RD Session Host server or the RD Virtualization Host servers with the Licensing mode type or point them to the License server in the deployment that you just added. To configure them you need to follow below steps.

2. Configuring the Licensing Mode.
a. In deployment Overview page, select on Tasks and click ‘Edit Deployment Properties’

clip_image015

b. In the ‘Deployment properties’ applet, click on the ‘RD Licensing’ page. Here you will see the License server is already added i.e., License.contoso.com in our case, however, the Licensing mode is not selected. Choose the appropriate Licensing mode. Click Apply and OK to exit the wizard.

clip_image017

c. At this stage the License server is installed, added to the deployment and mode is configured. However, the Licenses are yet to be installed. On the Session Host server or on the RD Virtualization host server License Diagnoser will show up as below

clip_image019

d. Once you have installed the required Licenses and Activated the License server, the console will look something like below

clip_image021

e. Also make sure to check License Configuration and that there are no Warnings with respect to configuration. The License Server should be part of ‘Terminal Server License’ group in Active Directory Domain Services.

clip_image022

clip_image024

f. On the RD Session Host server if you rerun the Diagnoser, you will see that the server now recognizes the License server the CAL type.

clip_image026

Adding an existing License Server in a new RDS deployment

In this scenario, let us assume that you already have an existing License server with all the required licenses installed. You just deployed a RDS deployment and created a collection. You, now want to use the same License server in your environment for the new deployment.

The steps are exactly the same as “2. Configuring the Licensing Mode” above.

In the ‘Deployment properties’ applet, click on the ‘RD Licensing’ page. In the text box specify the Licensing server name with complete FQDN and then click Add. Choose the appropriate Licensing mode ‘Per device’ or ‘Per User’. Click Apply and OK to exit the wizard.

clip_image015[1]

clip_image027

Rest of the steps are similar and should be followed as applicable.

Configuring License server manually

There might be situation when you want to configure License server on the RD Session Host or on the RD Virtualization Host manually since you do not have any RD Connection Broker in your environment. You have already configured RD Session Host server or Virtualization Host Server as required and now you want to configure the License server which is already installed and configured with licenses. All you are left to do is configure the License Server and the Licensing mode on the corresponding RD session Host or Virtualization Host servers.

Note The following commands must be ran from an Administrative PowerShell prompt.

To configure the license server on RDSH/RDVH:

$obj = gwmi -namespace “Root/CIMV2/TerminalServices” Win32_TerminalServiceSetting

$obj.SetSpecifiedLicenseServerList(“License.contoso.com”)

Note “License” is the name of the License Server in the environment

To verify the license server configuration on RDSH/RDVH:

$obj = gwmi -namespace “Root/CIMV2/TerminalServices” Win32_TerminalServiceSetting

$obj.GetSpecifiedLicenseServerList()

To change the licensing mode on RDSH/RDVH:

$obj = gwmi -namespace “Root/CIMV2/TerminalServices” Win32_TerminalServiceSetting

$obj.ChangeMode(value) – Value can be 2 – per Device, 4 – Per user

To validate the licensing mode:

$obj = gwmi -namespace “Root/CIMV2/TerminalServices” Win32_TerminalServiceSetting

$obj. LicensingType

$obj.LicensingName

Configuring license server using Group Policy

Per your design requirements you can also configure License Server using Group Policy in your environment.
The policy is located here:

Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Licensing\

“Use the specified Remote Desktop license servers” – Provide the FQDN of the license servers to use

Set the Remote Desktop licensing mode – Specify the ‘per user’ or ‘per device’ licensing types.

Known issue with RD Licensing Diagnoser:

You may receive an error “Licenses are not available for this Remote Desktop Session Host server, and RD Licensing Diagnoser has identified licensing problems for the RD Session Host Server”

In the RD Licensing Diagnoser Information Section, will show the possible cause and its remediation.

clip_image029

To make sure that the License Diagnoser runs successfully, you need administrator privileges on the license server.

clip_image030

 

Windows 2012 R2 activation by phone

1. To Change Product Key Number in a Command Prompt Open an elevated command prompt. In the elevated command prompt, type in the command below and press enter.

NOTE: Substitute XXXXX-XXXXX-XXXXX-XXXXX-XXXXX in this command below with your actual product key number with dashes instead. slmgr.vbs /ipk XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

2. type slui.exe 4 to access the phone activation screen and follow the steps to activate over the phone.

login to the query service failed vcenter 5.5

The problem may be because FQDN settings on VCENTER :

Symptoms

  • Unable to query the virtual machine details using the vCenter Server search option.
  • Querying the virtual machine details using the vCenter Server search option fails.
  • You see the error:
Login to the query service failed. The remote name could not be resolved.
  • Querying for virtual machines directly within the ESX host works properly.

Cause

This issue may occur if an incorrect FQDN is referenced in the vCenter Server Advanced Settings. This can be due to DNS issue and FQDN is not able to resolve in the Environment.

Resolution

To resolve the issue if FQDN is incorrect :
  1. Navigate to Administration > vCenter Server Settings… > Advanced Settings .
  2. Update these attributes with the correct FQDN for vCenter Server:

    VirtualCenter.VimApiUrl : https://<vCenter Server FQDN>:443/sdk
    VirtualCenter.VimWebServiceUrl : https://<vCenter ServerFQDN>:8443/vws

  3. Restart the VirtualCenter Management Webservices service.

The another option is multiple domains :

When you try to access to VCENTER from another dmain, you can’t do query properly. What you need is to add VCENTER address  in your host files

 

Fail2ban Centos 5

http://www.md3v.com/install-fail2ban-on-centos-5-5

Webmin installation

http://www.webmin.com/deb.html

 

 

 

NGINX on Ubuntu

http://www.howtoforge.com/perfect-server-ubuntu-12.04-lts-nginx-bind-dovecot-ispconfig-3

 

http://stackoverflow.com/questions/6045020/how-to-redirect-to-a-different-domain-using-nginx

Q.

How can I redirect mydomain.com and any subdomain *.mydomain.com to www.adifferentdomain.com using NGINX?

into /etc/nginx/conf.d/iis.conf

A.

server_name supports suffix matches using .mydomain.com syntax:

server {
  server_name .mydomain.com;
  rewrite ^ http://www.adifferentdomain.com$request_uri? permanent;
}

Windows 2008 TCP/IP Protocol Stack Hardening (Part 2)

http://winsrvtuts.com/2011/09/windows-2008-tcpip-protocol-stack-hardening-part-2/

As a quick cheat sheet these are the registry values that we added in the video for you to simply copy and paste instead of typing them all out.

Registry Location

HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters

DisableIPSourceRouting

REG_DWORD
Value 2
This will not only disable IP source routed packets but also stop them from being accepted

IPEnableRouter

REG_DWORD
Value 0
This will disable all IP forwarding between interfaces

SynAttackProtect

REG_DWORD
Value 3
This will enable the SYN Attack Protect Function after 3 half open connections are created

TcpMaxConnectResponseRetransmissions

REG_DWORD
Value 1
This will set any SYN / ACK handshake to time out after 3 seconds and will drop the connection after 9 seconds

TcpMaxHalfOpen

REG_DWORD
Value 500
Sets the total number of half open connections a system will allow

TcpMaxHalfOpenRetried

REG_DWORD
Value 400
Sets the total number of half open connections a system try and reestablish

 

Укрепление стека TCP/IP для защиты от SYN атак

http://www.securitylab.ru/analytics/216320.php

 

Мариус Бурдач, перевод Александр Антипов

Большинство людей знает, насколько может быть проблематична защита от SYN-атак. Обычно используются несколько более или менее эффективных методов. Почти в каждом случае, основным решением является правильная фильтрация пакетов. В дополнение к созданию пакетных фильтров, администратором может быть выполнена модификация TCP/IP стека данной операционной системы. Данный метод – настройка TCP/IP стека в различных операционных системах, и будет описан ниже.

В то время как невозможно полностью предотвратить SYN атаки, настройка TCP/IP стека помогает уменьшить влияние этого вида атак, при этом все еще разрешая легальный клиентский трафик через сервер. Необходимо отметить, что некоторые SYN атаки не всегда пытаются “положить” серверы, вместо этого они пытаются потребить всю пропускную способность вашего Internet канала.

Что может сделать администратор, когда его серверы подвергаются классической (не использующей заполнения пропускной способности интернет-канала), SYN атаке? Одним из наиболее важных шагов является включение встроенных в операционную систему механизмов защиты, таких как SYN cookies или SynAttackProtect. Дополнительно, в некоторых случаях, необходима настройка параметров TCP/IP стека. Изменение заданных по умолчанию значений стековых переменных, является уже другим уровнем защиты и помогает нам лучше защитить наши хосты. В этой статье мы сконцентрируем наше внимание на:

  • Увеличении очереди полуоткрытых соединений (в состоянии SYNRECEIVED).
  • Уменьшении, в очереди, периода времени хранения незавершенных подключений в состоянии SYNRECEIVED.

Этот метод выполняется с помощью уменьшения времени первой повторной передачи пакета или уменьшения (вплоть до полного отключения) количества повторных передач пакета. Процесс повторной передачи пакета выполняется сервером, до получения от клиента ACK пакета. Пакет с флагом ACK завершает процесс установления соединения между сервером и клиентом.

Необходимо обратить внимание на то, что нападающий может посылать большее количество пакетов с флагом SYN, и тогда вышесказанные операции не смогут решить эту проблему. Однако их выполнение может увеличить вероятность создания полного подключения с легальными клиентами.

Также необходимо помнить, что модификация переменных, изменит режим работы стека TCP/IP. Так, после модификации, мы должны удостовериться, что сервер может должным образом связываться с другими хостами. Например, отключение повторных передач пакета в некоторых системах низкой пропускной способностью, может привести к отказу в работе при легальных запросах. В этой статье можно найти описание TCP/IP переменных для следующих операционных систем: Microsoft Windows 2000, RedHat Linux 7.3, Sun Solaris 8 и HP-UX 11.00.

Определения: SYN атака и SYN спуфинг.

SYN атака -это один из типов DDoS атак. Мы можем говорить, что хост жертвы подвергся SYN атаке, в случае, когда злоумышленник пытается создать огромное количество подключений в состоянии SYNRECEIVED до тех пор, пока не переполнится очередь соединений. Состояние SYN RECEIVED создается, когда хост жертвы получает запрос на подключение (пакет с набором флага SYN) и распределяет для этого некоторые ресурсы памяти. При SYNатаке создается такое количество полуоткрытых подключений, что система переполняется и больше не может обрабатывать поступающие запросы.

Для увеличения эффективности SYN атаки, злоумышленник использует фиктивные IP адреса в SYN пакетах. В этом случае хост жертвы не может быстро закончить процесс инициализации, потому что исходный IP адрес может быть недостижим. Эта злонамеренная операция называется SYN спуфингом.

Мы должны знать, что процесс создания полного подключения занимает некоторое время. Первоначально, после получения запроса на подключение (пакет с набором флага SYN), хост жертвы помещает это полуоткрытое соединений в очередь и посылает первый ответ (пакет с флагами SYN и ACK). Если жертва не получает ответ от удаленного хоста, то она повторно передает SYN+ACK пакеты, до тех пор, пока не наступит тайм-аут, а затем удаляет это полуоткрытое соединение из очереди. В некоторых операционных системах этот процесс, для каждого отдельного SYN запроса, может занимать приблизительно 3 минуты! В этом документе Вы узнаете, как можно изменить эту закономерность. Другой, не менее важной информацией, которой Вы должны владеть является то, что операционная система может обрабатывать только определенное количество полуоткрытых подключений в очереди. Это количество управляется размером очереди соединений. Например, заданный по умолчанию размер очереди в RedHat 7.3 – 256, а в Windows 2000 Professional – 100. Когда размер очереди достигнет этого размера, система больше не будет принимать поступающие запросы.

Обнаружение SYN атак

Обнаружить SYN атаку очень легко. Команда netstat показывает нам количество подключений находящихся в полуоткрытом состоянии. Полуоткрытое состояние описано как SYN_RECEIVED в Windows и как SYN_RECV в Unix системах.

  # netstat -n -p TCP
tcp 0 0 10.100.0.200:21 237.177.154.8:25882 SYN_RECV -
tcp 0 0 10.100.0.200:21 236.15.133.204:2577 SYN_RECV -
tcp 0 0 10.100.0.200:21 127.160.6.129:51748 SYN_RECV -
tcp 0 0 10.100.0.200:21 230.220.13.25:47393 SYN_RECV -
tcp 0 0 10.100.0.200:21 227.200.204.182:60427 SYN_RECV -
tcp 0 0 10.100.0.200:21 232.115.18.38:278 SYN_RECV -
tcp 0 0 10.100.0.200:21 229.116.95.96:5122 SYN_RECV -
tcp 0 0 10.100.0.200:21 236.219.139.207:49162 SYN_RECV -
tcp 0 0 10.100.0.200:21 238.100.72.228:37899 SYN_RECV -
...

Мы можем также подсчитать количество полуоткрытых подключений находящихся в очереди в настоящее время. В приведенном ниже примере, 769 подключений (для TELNET) находящихся в состоянии SYNRECEIVED сохраняются в очереди задач.

* netstat-n-p TCP | grep SYN_RECV | grep:23 | wc-l

769

Другой метод обнаружения SYN атак состоит в распечатке статистики TCP и просмотре параметров TCP, подсчитывающих количество отклоняемых запросов. Во время атаки значения этих параметров быстро возрастают.

В этом примере мы пронаблюдаем за значением параметра TcpHalfOpenDrop на системе SunSolaris.

* netstat-s-P tcp | grep tcpHalfOpenDrop

 tcpHalfOpenDrop = 473

Важно обратить внимание на то, что каждый tcp порт имеет свою собственную очередь соединений, но только одна переменная стека tcp/IP управляет размером этой очереди для всех портов.

Очередь соединений

Очередь соединений – большая структура памяти, используемая для обработки поступающих пакетов с набором флага SYN до момента установления соединения между клиентом и сервером. Операционная система распределяет часть системной памяти для каждого поступающего соединения. Мы знаем, что каждый tcp порт может обрабатывать только определенное количество поступающих запросов. Очередь соединений управляет количеством полуоткрытых подключений, способных одновременно обрабатываться операционной системой. Когда количество поступающих соединений достигнет максимального уровня, все последующие запросы будут отклонены операционной системой.

Как упомянуто выше, обнаружение большого количества соединений в состоянии SYN RECEIVED скорее всего означает, что хост подвергся SYN атаке. Кроме того, исходные IP адреса, этих пакетов могут быть фиктивными. Для ограничения эффективности SYN атак мы должны включить некоторые встроенные защитные механизмы. Иногда мы также можем использовать методы типа увеличения размера очереди соединений и уменьшения времени хранения незавершенных соединений в распределяемой памяти (в очереди соединений).

Встроенные механизмы защиты

Операционная система: Windows 2000

Наиболее важным параметром в Windows 2000 и в Windows Server 2003 является параметр SynAttackProtect. Включение этого параметра позволяет операционной системе более эффективно обрабатывать поступающие соединения. Защита может быть установлена, путем добавления значения SynAttackProtect, типа DWORD, в следующий ключ системного реестра:

HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters В случае обнаружения SYN атаки, параметр SynAttackProtect изменяет режим работы стека TCP/IP, что позволяет операционной системе обрабатывать большее количество SYN запросов. Принцип работы заключается в отключении некоторые опций сокета, добавлении дополнительных задержек к показаниям соединения и изменении тайм-аута для запросов.

Когда значение SynAttackProtect равно 1, количество повторных передач уменьшено, а маршрутизация содержимого кеша отсрочена до создания соединения. Рекомендуемое значение SynAttackProtect – 2, при котором дополнительно задерживается признак соединения с Windows Socket до установления связи сервера с клиентом. В ходе нападения, лучшая производительность в обработке соединений достигается с помощью отключения нескольких параметров (эти параметры обычно используются системой в течение процесса создания новых соединений). Параметр TCPINITIALRTT, определяющий время первой перепередачи, больше не будет использоваться.

Как мы можем увидеть, включение параметра SynAttackProtect не изменяет режим работы стека TCP/IP до и при SYN атаке. Но даже при включенном параметре SynAttackProtect, операционная система может обрабатывать легальные поступающие соединения.

Операционная система автоматически включает защиту от SYNатак, когда обнаруживает превышение значений следующих трех параметров: TcpMaxHalfOpen, TcpMaxHalfOpenRetried и TcpMaxPortsExhausted.

Чтобы изменить значения этих параметров, сначала мы должны добавить их к тому же самому ключу системного реестра, как и в случае с SynAttackProtect.

Элемент системного реестра TcpMaxHalfOpen определяет максимальное количество состояний SYN RECEIVED, которые могут быть одновременно обработаны, прежде чем сработает SYN защита. Рекомендуемое значение этого параметра – 100 для Windows 2000 Server и 500 для Windows 2000 Advanced Server.

TcpMaxHalfOpenRetried определяет максимальное количество полуоткрытых подключений, для которых операционная система выполнила по крайней мере одну повторную передачу, прежде, чем сработает SYN защита. Рекомендуемое значение – 80 для Windows 2000 Server, и 400 для Advanced Server.

Элемент системного реестра TcpMaxPortsExhausted определяет число отклоненных SYN запросов, после которого сработает защита от SYN атак. Рекомендованное значение – 5.

Операционная система: LinuxRedHat

В RedHat, как и в других Linux системах, осуществлен механизм SYN cookies, который включается следующим способом:

* ECHO 1 >/proc/sys/net/ipv4/tcp_syncookies

Обратите внимание, что для того чтобы сделать это изменение постоянным, мы должны создать загрузочный файл, который будет присваивать значение этой переменной. Мы должны проделать ту же самую операцию и для других UNIX переменных, описанных в этой статье, потому что значения этих переменных после перезагрузки системы вернуться к прежним значениям.

Защита SYN cookies особенно полезна, в случае, когда система подверглась SYN атаке, а исходные IP адреса пакетов – фиктивные (SYN спуфинг). Этот механизм позволяет структурировать пакеты с набором флагов SYN и ACK, которые имеют специально обработанный “начальный номер последовательности” (ISN), называемый cookie. Значение cookie это не псевдослучайное число, сгенерированное системой, а результат действия хеш-функции. Это значение генерируется хеш-функцией в зависимости от следующей информации: IP-адрес источника, порт источника, IP адрес получателя, порт получателя плюс некоторые секретные значения. В ходе SYN атаки, когда заполняется очередь соединений, система вместо отклонения запроса, генерирует ответ, посылая клиенту пакет с cookie. Когда сервер получает пакет с набором флажка ACK (последняя стадия процесса установления соединения с клиентом), тогда он проверяет значение cookie. Если это значение правильно, то сервер создает подключение, даже в случае если нет никакого соответствующего элемента в очереди соединений. В этом случае мы знаем, что это легальное соединение, и что исходный IP адрес не фиктивный. Важно обратить внимание на то, что механизм работы SYN cookie, вообще не использует очередь соединений, так что теперь мы не должны изменять её размер. Более подробную информацию об использовании SYN cookies можно найти здесь.

Также необходимо обратить внимание на то, что механизм SYN cookies работает только когда опция CONFIG_SYNCOOKIES установлена в ходе компиляции ядра системы.

В следующем разделе будут описаны другие полезные методы защиты от SYN атак. Я хотел бы подчеркнуть, что при более сложных видах SYN атак,  эти методы могут помочь, но не решить проблему.

Увеличение размера очереди соединений

При SYN атаке, мы можем изменить размер очереди задач для поддержки большего количества полуоткрытых соединений так, чтобы не отклонять доступ к серверу легальным клиентам. В некоторых операционных системах, размер очереди задач очень маленький, поэтому производители рекомендуют увеличение этого значения, в случае если система подверглась SYN атаке.

Увеличение размера очереди задач требует, чтобы система резервировала дополнительные ресурсы памяти для входящих соединений. Если в системе отсутствует достаточное количество свободной памяти для этой операции, то пострадает производительность системы. Также мы должны удостовериться, что сетевые приложения (Apache, IIS и т.д.) смогут принимать большее количество подключений.

Операционная система: Windows 2000

Кроме описанных выше переменных TcpMaxHalfOpen и TcpMaxHalfOpenRetried, в Windows 2000 количество полуоткрытых подключений может быть установлено через динамическую очередь соединений. Конфигурирование этой очереди выполняется через драйвер AFD.SYS. Этот драйвер используется для поддержки Windows Socket приложений (FTP, Telnet и т.д.). Для увеличения количества полуоткрытых соединений, AFD.SYS поддерживает четыре элемента системного реестра. Все эти значения расположены в следующем ключе системного реестра:

HKLM\System\CurrentControlSet\Services\ AFD\Parameters

Значение системного реестра EnableDynamicBacklog – глобальный переключатель, включающий или выключающий динамическую очередь соединений. Значение 1 – включает динамическую очередь.

MinimumDynamicBacklog – управляет минимальным количеством свободных соединений, разрешенных на каждом отдельном TCP порте. Если количество свободных соединений снижается ниже этого значения, то дополнительные свободные соединения будут созданы автоматически. Рекомендованное значение 20.

Значение MaximumDynamicBacklog определяет сумму активных полуоткрытых соединений и максимального количества свободных соединений. Если это значение будет превышено, то система больше не будет создавать свободные соединения. Рекомендованное значение не должно превышать 20000.

Последний параметр DynamicBacklogGrowthDelta управляет количеством свободных соединений, создаваемых в случае необходимости. Рекомендуемое значение: 10.

Ниже расположена таблица, показывающая рекомендуемые значения для драйвера AFD.SYS:

Значение подключа реестра

Формат

Значение

EnableDynamicBacklog
DWORD

1

MinimumDynamicBacklog

DWORD

20

MaximumDynamicBacklog

DWORD

20000

DynamicBacklogGrowthDelta

DWORD

10

Операционная система: Linux

Переменная Tcp_max_syn_backlog определяет количество полуоткрытых подключений сохраняемых в очереди соединений. Например, 256 – общее количество полуоткрытых подключений, размещенных в памяти Linux RedHat 7.3. Переменные TCP/IP стека могут быть сконфигурированы с помощью команды sysctl или стандартными командами Unix. Ниже показан пример изменения заданного по умолчанию размера очереди соединений с помощью команды sysctl:

 # sysctl -w net.ipv4.tcp_max_syn_backlog=”2048″

Операционная система: Sun Solaris

В операционной системе Sun Solaris есть два параметра, управляющие максимальным количеством подключений. Первый параметр управляет общим количеством полных подключений. Второй параметр tcp_conn_req_max_q0, определяет при каком количестве полуоткрытых соединений, поступающие запросы не будут отклонены системой. Заданное по умолчанию значение этого параметра в ОС Sun Solaris 8 равно 1024. Мы можем изменять это значение при помощи команды ndd.

# nddset /dev/tcptcp_conn_req_max_q0 2048

Операционная система: HPUX

В операционной системе HPUX, ответственной за управление максимальным количеством полуоткрытых соединений в состоянии SYNRECEIVED, является переменная TCP/IP стека tcp_SYN_rcvd_max. По умолчанию, в ОС HPUX 11.00, значение этой переменной равно 500. Изменение этого значения, как и в ОС SunSolaris, происходит с помощью команды ndd.

# ndd -set /dev/tcp tcp_syn_rcvd_max 2048

Уменьшение полного времени обработки запроса на соединение

Поскольку мы знаем, что SYN атака/спуфинг это просто ряд SYN пакетов, главным образом с фиктивными IP адресами. В прошлом разделе мы увеличили размер очереди соединений. Теперь, когда наши системы могут обрабатывать большее количество SYN запросов, мы должны уменьшить полное время хранения полуоткрытых соединений в очереди. Когда сервер получает запрос, он немедленно посылает пакет с набором флагов SYN и ACK, помещает это полуоткрытое соединение в очередь, а затем ожидает от клиента пакет с флагом ACK. Если сервер не получает ответа от клиента, то он еще несколько раз передает ответный пакет (с флагами SYN и ACK), (количество ответов зависит от установок операционной системы), давая клиенту возможность для пересылки ACK пакета. Ясно, что в случае фиктивности исходного IP адреса клиента, ACK пакет никогда не прибудет. После нескольких минут ожидания сервер удаляет это полуоткрытое соединение. Мы можем ускорить процесс удаления соединений в состоянии в SYNRECEIVED из очереди соединений, изменяя время первой перепередачи и общего количества перепередач.

Другая методика защиты от SYN атак заключается в отключении некоторые параметров TCP, которые всегда активны в течение процесса установления связи сервера с клиентом. Некоторые из этих параметров автоматически выключаются механизмами, описанными в первом разделе (SynAttackProtect и Syncookies).

Теперь мы рассмотрим переменные стека TCP/IP, которые позволяют уменьшить время хранения полуоткрытых соединений в очереди задач.

Операционная система: Windows 2000

В Windows 2000, время для первой перепередачи, по умолчанию, равно 3 секундам (3000 миллисекундам) и может быть изменено с помощью значения элемента системного реестра TcpInitialRtt (для каждого интерфейса). Например, для уменьшения времени первой перепередачи до 2 секунд, мы должны установить значение TcpInitialRtt равным 2000 миллисекундам (в десятичном формате). Количество перепередач (пакетов с флагами SYN и ACK) управляется параметром системного реестра TcpMaxConnectResponseRetransmissions, который добавляется к ключу HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters.

Ниже показана таблица, содержащая примеры значений, и соответствующее им время хранения полуоткрытых соединений в очереди задач (время первой перепередачи равно 3 секундам).

Значение Время перепередачи Полное время хранения полуоткрытых соединений в очереди
1

на 3-ей секунде

9 секунд

2

на 3-ей и 9-ой секундах

21 секунда

3

на 3-ей, 9-ой и 21 секундах

45 секунд

Мы можем установить это значение системного реестра в 0, после чего Windows вообще повторно не передает пакеты. В этом случае, система посылает только один ответ и удаляет полуоткрытое соединение через 3 секунды. Эта установка игнорируется, когда ее значение равно или больше 2, и когда включен механизм SynAttackProtect.

Операционная система: LinuxRedHat

Переменная Tcp_synack_retries управляет количеством перепередач в операционной системе Linux. По умолчанию, для большинства операционных систем Linux, это значение равно 5, что означает удаление полуоткрытого соединения через 3 минуты. Ниже приведена таблица с вычислениями для других значений.

Значение

Время перепередачи

Полное время хранения полуоткрытых соединений в очереди

1

на 3-ей секунде

9 секунд

2

на 3-ей и 9-ой секундах

21 секунда

3

на 3-ей, 9-ой и 21 секундах

45 секунд

Операционная система: Sun Solaris

В этой операционной системе невозможно отключить перепередачи пакетов, непосредственно используя команду ndd. Кроме того, в ОС Sun Solaris есть параметры, которые являются неконфигурируемыми и которые управляют количеством перепередач (как минимум 3) и полным временем перепередачи пакетов (как минимум 3 минуты). Более детальную информацию об этих параметрах можно найти здесь.

Операционная система: HPUX

В HP-UX, время обработки полуоткрытых соединений в очереди задач управляется параметром tcp_ip_abort_cinterval. Используя ndd команду, мы можем определить время ожидания ACK пакета. Изменяя это значение мы косвенно можем управлять количеством выполненных перепередач. Взгляните на таблицу представленную ниже.

Значение Время перепередачи Полное время хранения полуоткрытых соединений в очереди
1000

1 секунда

5000

На 2-ой секунде

5 секунд

10000

на 2-ой и 5-ой секундах

10 секунд

60000

на 2-ой, 5-ой, 11 и 47-ой секундах

1 минута

Мы можем изменить время первой перепередачи, изменив значение tcp_rexmit_interval_initial. Интервалы последующих перепередач управляются двумя параметрами: tcp_rexmit_interval и tcp_rexmit_interval_min. Эти три переменной такие же, как и в ОС SunSolaris.

Выводы

Методы укрепления защиты стека TCP/IP, представленные в этой статье, делают серверы более стойкими к SYN-атакам – одним из видов DDoS атак. Модификация заданных по умолчанию параметров настроек  стека TCP/IP также рекомендуется в течение процесса защиты операционной системы.

Finding Files and Counting Lines at the Windows Command Prompt

http://isc.sans.edu/diary.html?storyid=2244

 

Yesterday, Microsoft delivered to us a bouquet of a dozen patches, just in time for our Valentine’s Day celebration today.  With those patches, and a recent inundation of other vulnerabilities (Solaris Telnet?  Are you kidding me?), I’d like do a quick change of pace to give you a couple of fun tips for using the Windows command line.

It’s become something of a ritual around here.  Whenever I’m Handler on Duty, I reinforce my ultimate goal of eliminating the Windows GUI from use by administrators and incident handlers by writing a tip or two for using the Windows command line.  One of the most frequent questions I get recently whenever I teach a SANS session on the Windows command line involves searching for files with a given name.  Suppose, for example, that you want to find the program wmic.exe in your directory structure.  There are two approaches I use:

First, you can change into a given directory that you want to search (such as C:\windows\system32), and then run the dir command appropriately:

C:\> cd c:\windows\system32
C:\> dir /s /b wmic.exe

The /s means that we want to recurse subdirectories.  The /b means that we want the bare form of output (which will omit the volume information, ., and .. from our listing).  When /b is used with /s, it will print out the full path to the item for which we search (context-specific command flags that change their behavior in light of other flags can be trouble for memorization, I admit).  The downside of doing this is that you have changed out of your current directory to do the search.

But, diligent readers Michael Wilson, Chris Wolf, and a reader desiring anonymity have pointed out that you can search for something without changing your current directory by running the command thusly:

C:\> dir /s /b c:\windows\system32\wmic.exe

It looks like this command would only find a wmic.exe if it is system32 itself, but it actually looks through system32 and all of its subdirectories, doing just what we want.  Pretty cool!  And, you don’t lose your current directory in the process.

The second approach is to use the dir command again, but to scrape through its output using the find command, as in:

C:\> dir /s /b c:\windows\system32 | find “wmic.exe”

The first approach has better performance (because we are not scraping through Standard Out).

Oh, and another frequent question I get: How can I do a line count on the output of another command?  UNIX and Linux folks frequently use “wc –l” to count stuff…. How can we do this in Windows?  Suppose, for example, you wanted to count the number of files and subdirectories inside of c:\temp.  There is no wc command built in, but here is a method I use:

C:\> dir /b c:\temp | find /c /v “~~~”

The dir command gets a directory listing, in bare format (/b) of c:\temp.  I use the find command to count (/c) lines that DO NOT contain (/v) the string ~~~.  It would be very unusual to have that string, so it gives me a pretty accurate line count.  If you are really concerned about having such lines, you can run it without the /v and make sure the count is 0.  Also, you can recurse subdirectories using /s, as you might expect.  And, this technique can also be used to count other things, like the number of running processes called svchost.exe, using the tasklist command (built into Win XP Pro and 2003):

C:\> tasklist /fi “imagename eq svchost.exe” | find /c /v “~~~”

Don’t forget to subtract the appropriate number of column headers and footer lines from your output (in the case of tasklist, you have to subtract 3, because of the Column titles, the ===== under the columns, and an extra carriage return it puts at the end).   Attentive reader Chris Luhman mentioned that you can use the /nh option in tasklist to get it to omit the header (nh stands for no header).  Then, you’ll only have to subtract one from the output.  It is an odd but recurring thing in Windows command line tools.  They often put an extra line at either the beginning or the end of their output.  I see this a lot with wmic.

Oh, and there are other things you can do with the line count method I’ve described above.  For example, to count the number of lines in your win.ini file, you can use the type command (the rough equivalent to the UNIX cat command):

c:\> type c:\windows\win.ini | find /c /v “~~~”

And the list goes on and on…

This is a rather contrived way of doing a line count, but it works very nicely for me.  If you know of a better way, using only built-in Windows commands, please let me know.

Thanks!
–Ed Skoudis
Handler on Duty
Intelguardians

Post Navigation