Rewriting IIS Server Response Content from HTTP to HTTPS

eraser-paper

This may seem like an unusual post, but this may apply to “load-balancer gurus” who do SSL termination. In certain cases web-applications that you host have embedded code that reference http links. This can be resolved with F5 iRules, but it can be tricky with Cisco ACE.

Instead of reinventing the wheel, here’s how to do it with the URL Rewrite module in IIS. A good reference link can be found here.

Lets say your webserver keeps responding with image referrer links with http instead of https. This will give users on the web errors about mixed content. IIS can rewrite those responses for you without spending tons of man-hours fixing your code or bothering developers.

What this is doing is looking for any content that starts with HTTP and grabs any content after the star as a back-reference to basically plop into use in the next portion. {R:2} is that reference in the rewrite value.  I’m looking for http patterns after img, link and script tags. You can customize to your specific application.

 <rule name="Content-Rewrite" preCondition="" enabled="true" patternSyntax="Wildcard">
  <match filterByTags="Img, Link, Script" pattern="*http://*" />
   <conditions />
    <action type="Rewrite" value="https://{R:2}" />
  </rule>
  <preConditions>
  <preCondition name="http" logicalGrouping="MatchAny" patternSyntax="Wildcard">
  <add input="{RESPONSE_CONTENT_TYPE}" pattern="http:" />

Rewriting IIS Server Response Content from HTTP to HTTPS

Adding Routes on Windows Servers

I’ll preface this post by saying I HATE host routes (not often that I capitalize words so you know how serious this is…) Lets face it, sometimes you need to add one to make an old and a new environment work, testing, VPN, B2B networks, etc. etc.

Windows has a basic, but in my opinion, a somewhat lousy command tool called “route” to add host routes. In it’s most basic form and under most circumstances you can use it right out of the box without any issues.

There are, however, those times when a server has three NIC’s, you need to add routes for different subnet masks, specific hosts, etc. That’s where things can get tricky.

I recently encountered an issue where even though we added a host route, it did not work. I knew something was wrong because when I captured traffic on the firewall that was the gateway for the route, I just didn’t see anything. Here’s the scenario; I am on the 10.100.1.0 subnet with 10.100.1.1 as my default server gateway. I need to talk to 10.100.2.50 but through a different gateway.

The first thing I did was add a one-to-one host route:

route add -p 10.100.2.50 mask 255.255.255.255 10.100.1.2

Ok, so that’s it right? Nope. By default it assigns interface 1 to the route, which is the loopback interface. When I tried to ping that 10.100.2.50 host I never saw the traffic.

I had to run a route print to see what my interfaces were numbered as:

C:\Users\me>route print
=============================================================
Interface List
 17...00 50 46 84 00 13 ......vmxnet3 Ethernet Adapter #2
 14...00 0c c9 0d d2 da ......vmxnet3 Ethernet Adapter #1
 1...........................Software Loopback Interface 1
=============================================================

Ok, so ethernet Adapter 1 is the one I want to use, which is interface 14, so I need to adjust my route statement.

route add -p 10.100.2.50 mask 255.255.255.255 10.100.1.2 if 14

Nice! My traffic works now.

Why do I think the route command is lousy? Well, because when I add a route for a /24 subnet, it works 90% of the time, but when I add a specific host (/32) route, I have to specify the interface. For example:

route add -p 10.100.2.0 mask 255.255.255.0 10.100.1.2

This command normally would work without specifying any interfaces. Why? I have no idea, maybe some Microsoft employees can fill me in.

The other issue I have is the inability to ping using a different gateway. I can ping using a different IP on that host with the ping -S command, but there is no way for me to test a ping without messing about with routes until I see what I need on my firewall. I would love it if I could ping -G and use a gateway IP to send traffic. Alas, I am getting off topic…

Adding Routes on Windows Servers

Powershell: Find stale Users

old user

Having old, unused user accounts sitting in your domain can send red-flags flying by auditors. It’s easy to create an account and think it will be used for the foreseeable future, but often times this is not the case.

This script queries your domain for user accounts that have not logged in in the past 6 months. It creates an HTML report and emails you the results. The email can be reviewed and action can be taken based on your discretion. I have added an option for you to un-comment which will automatically disable accounts that fit this criteria. Powershell v3 with the new Active Directory module is required for this to work.

<# Workflow

Query AD for users who have not

logged in in over 6 months.

#>

 

#Import AD module

Import-Module ActiveDirectory

 

# 6 months ago

$6months = Get-date

$6months = $6months.adddays(-180)

 

$Format = @{Expression={$_.SamAccountName};Label=“User Login Name”},`

@{Expression={$_.name};Label=“Account Name”},`

@{Expression={$_.whencreated};Label=“Created”},`

@{Expression={$_.passwordneverexpires};Label=“Password Never Expires”},`

@{Expression={$_.lastlogondate};Label=“Last Logon”},`

@{Expression={$_.enabled};Label=“Enabled”}

 

#Filter for users who havent logged in for 6 months as the basis of the filter. Add some additional properties.

Get-ADUser -filter { (lastlogondate -le $6months) } -properties * | Sort-Object lastlogondate | ConvertTo-Html $Format -Title “AD User Report” > .\Documents\Users.htm

 

#Send the email

Send-MailMessage -to you@domain.com -Subject “AD Account Report” SmtpServer 192.168.1.1 -From server@domain.com -Attachments .\Documents\Users.htm

 

#Un-comment this line to automatically disable the accounts rather than send a report 

#Get-ADUser -filter { (lastlogondate -le $6months) -and (enabled –eq “true”) } | Set-Aduser -enabled $false

–>

Powershell: Find stale Users

Powershell: Query domain for expiring certificates

Certificate expirations can be a pain to manage and are often overlooked. Some people have spreadsheets, set calendar reminders or just wait until a customer complains. I used to have a Unix script that would search an entire subnet for servers with expiring certs, but it was not very robust, searching subnets can return some questionable results.

This script starts by querying active directory to get a list of computer names that match string(s) that you enter. Then powershell searches the servers for certs that are within 14 days of expiring. The script will then email you an HTML report if there are certs expiring, if not it will do nothing. This script is highly customizable, so tweak it as needed.

<#

Script to check AD computers

for expiring certificates.

Author: Ryan Clark

Date: 4/1/13

#>

 

 

#Import AD module

Import-Module ActiveDirectory

 

#Make sure computers array is empty incase script has been run
in this session before

$Computers.Clear()

 

#Fill array with computers you want to filter by this example
is computers that start with DEV and PRD

$Computers = Get-ADComputer -Filter ‘Name -like “DEV*” -or Name -like “PRD*”’ | Foreach {$_.Name}

 

#Count Computers

$CompNum= $Computers.count

 

#Set a date variable for today and two weeks ago. Change the
date in TwoWeeks to modify the expiration time

$Today = (Get-Date).ToString(yyyy/MM/dd)

$TwoWeeks= (Get-Date).AddDays(+30).ToString(yyyy/MM/dd)

 

#HTML Style config

$a = “<style>”

$a = $a + BODY{background-color:white;}”

$a = $a + TABLE{border-width:1px;border-style: solid;border-color: black;border-collapse: collapse;}”

$a = $a + TH{border-width:1px;padding: 5px;border-style: solid;border-color: black;background-color:#D0A9F5}”

$a = $a + TD{border-width:1px;padding: 5px;border-style: solid;border-color: black;background-color:#FAFAFA}”

$a = $a + “</style>”

 

#Run through each computer and check for certs within the
configured date period

$i=0

Clear-content C:\Admin\CertReport.htm

while($i lt $CompNum)

{

Write-Host “Working on:” $Computers[$i]

#If your certs are in a different store change the Cert:\ path

$Certs = invoke-command ComputerName $Computers[$i] ScriptBlock {Get-ChildItem Cert:\LocalMachine\My}

$CertCount=$certs.count

$j=0

 while($j lt $CertCount)

 { 

   if (($Certs[$j].NotAfter gt $Today) -and ($Certs[$j].NotAfter lt $TwoWeeks) )

   {

    $Certs[$j] | ConvertTo-Html -head $a -title “Expiry Information” -property PSComputerName,Subject,NotAfter
>> C:\Admin\CertReport.htm

   }

   ++$j

 }

++$i

}

 

#Either email a report or do nothing

if
((Get-Content “C:\Admin\CertReport.htm”eq $Null)

{

 write-host
“No expiring certificates. Ending script.”

}

else

{

 #Modify the -to field to send to another user or DL

 write-host
“Expired certificates found, emailing report”

 Send-MailMessage -to me@mydomain.com -Subject
“Certificate Report” SmtpServer x.x.x.x -From myserver@domain.com -Attachments C:\Admin\CertReport.htm

}

Powershell: Query domain for expiring certificates

Load balance based on CPU Load – (Windows 2008 Hosts)

Some load-balanced applications create considerable load independent to number of connections. For example reporting a server may become overloaded if users submit a report that requires a lot of historical data to generate. If there are three servers in a farm and they each have 10 connections, one server could have people running intensive reporting, while the other is sitting idle, which is imperceptible to the ACE with out some sort of CPU inspection. This is where SNMP probes come in…

The first thing we need to do is enable SNMP services. In my case I’m using Windows Server 2008 hosts. On Unix or other OS’s your process will vary or it may already be running SNMP services.

  • Open Server Manager
  • Click Features
  • Click Add Features on the right side
  • Scroll down and check the box marked SNMP Services
  • Click Next then Install

The next thing you need to do is configure it so that the ACE can talk to the host with the right strings.

  • Go back to Server Manager and expand Configuration
  • Click Services
  • Right click on SNMP Service and click Properties
  • Click the Security tab
  • Uncheck Send authentication trap
  • Under Accepted community names click Add...
  • Leave READ ONLY
  • Enter a community name appropriate for your environment (or use public) and click Add
  • Under Accept SNMP packets from these hosts click Add
  • Enter the IP of the ACE and click Add
  • Right click the service and click Restart

Now the ACE can poll the server for SNMP entries.

The first step is configuring the rserver(s) that are going to be monitored.

rserver host SERVER1
  ip address 192.168.1.1
  inservice
rserver host SERVER2
  ip address 192.168.1.2
  inservice

Now we want to build out our SNMP probe. The first step is to define it.

probe snmp CPU-PROBE

What was your community name? Enter it next.

community public

How often do you want the ACE to check the CPU? I used 10 seconds.

interval 10

If the server goes down, how many successful probes before it comes back online? Six would be 60 seconds, so I’ll use that.

passdetect count 6

The next section is tricky. How many CPU’s does your server have? You’ll have to customize your probe based on the number of CPU’s. In my case my server has two CPU’s. For one CPU the oid is .1.3.6.1.2.1.25.3.3.1.2.2 and the other is .1.3.6.1.2.1.25.3.3.1.2.3

What I’ll need to do is add both OID’s to the probe, then give them equal weight. In my example each CPU has a weight of 8000 (all your OID’s have to add up to 16000). If you had 8 CPU’s the weight would be 4000 each, and so on.

oid .1.3.6.1.2.1.25.3.3.1.2.2
 weight 8000
oid .1.3.6.1.2.1.25.3.3.1.2.3
 weight 8000

Now you can assign it to a serverfarm as a predictor method.

serverfarm MYFARM
  predictor least-loaded probe CPU-PROBE
  rserver SERVER1
    inservice
  rserver SERVER2
    inservice

The load is computed with the total weight of the probe, which is 16000. Run the show probe CPU-PROBE detail command to view the load on the server. Take that number and divide by 16000 to get the percentage value.

Here are some examples, the first one is for two-CPU servers and the second is for six-CPU servers.

Two CPU

probe snmp CPU-PROBE-TWO-CPU
 interval 10
 passdetect interval 60
 passdetect count 6
 community public
 oid .1.3.6.1.2.1.25.3.3.1.2.2
 weight 8000
 oid .1.3.6.1.2.1.25.3.3.1.2.3
 weight 8000

Six CPU

probe snmp CPU-PROBE-SIX-CPU
  interval 10
  passdetect interval 60
  passdetect count 6
  community public
  oid .1.3.6.1.2.1.25.3.3.1.2.2
    weight 2667
  oid .1.3.6.1.2.1.25.3.3.1.2.3
    weight 2666
  oid .1.3.6.1.2.1.25.3.3.1.2.4
    weight 2667
  oid .1.3.6.1.2.1.25.3.3.1.2.5
    weight 2667
  oid .1.3.6.1.2.1.25.3.3.1.2.6
    weight 2666
  oid .1.3.6.1.2.1.25.3.3.1.2.7
    weight 2667
Load balance based on CPU Load – (Windows 2008 Hosts)

WSUS Trouble?

Sometimes when I build a new server it can take a few days for it to show up in WSUS or it may not even show up at all. If I’m having trouble I use this batch file. I only use this after the group policy settings have been created and the server is sitting in that OU. 99% of the time this fixes my issues with the server showing up in the WSUS console.

reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate /v AccountDomainSid /f
reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate /v PingID /f
reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate /v SusClientId /f
cls
gpupdate /force
@echo Triggering detection after resetting WSUS client identity
net stop wuauserv
net start wuauserv
wuauclt /resetauthorization /detectnow
WSUS Trouble?

Autodelete Files by Age

In my last post I covered how to back up files based on age. This is a nice script to supplement it, this will auto-delete files based on their age. It’s an easy way to backup files to a disk somewhere and not overflow it with backups.

This example is for a Windows host, to delete a file older than 3 days:

1. Create a batch script with the following

echo on
 rem Delete files older than 3 days
 FORFILES /P C:\Admin\Test\ /S /M 1*.bmp /D -3 /c " CMD /c del /q @FILE "

2. Modify the following flags to suit your need

/p = The path to search for the files you want to check the date of and remove
/s = Recurse subdirectories contained within the path specified using /p and check them as well
/m = The search mask to be used for the file type you want to check the date on (*.* being all files)
/d = The date to compare the files against. A standard date type can also be used (dd/mm/yyyy)
/c = The command to be used on a file that matches the /m and /d criteria
/q = Used within /c to instruct the del command to delete files quietly

3. Add the batch file to the scheduler based on your need

Autodelete Files by Age