Tuesday, December 21, 2010

Macs, Windows 7, and SMB shares

I was recently creating a SMB share on one of my Mac 10.6 servers that acted funny.  It would keep asking me to log in, even though I had the correct credentials.  I accidentally discovered that a Windows 2008 R1 machine could hit it just fine... but my Windows 7 box could not.  This lead to a search of the internets, and I discovered a somewhat-related problem (it was actually crashing Samba on the server side)...  Someone on that blog wrote that it has to do with NTLM.  I figure the security permissions were changed from Windows 2008 R1 to R2, and also between Vista and Windows 7.  The post mentions to change a bunch of stuff in the "local security policy" of the Windows box to make it work.  I don't like changing a whole lot of security stuff, especially loosing it... so here is all I changed to make this work , citing "nikonz" from the site above for the original fix (with my changes):

"Control Panel --> Administrative Tools --> Local Security Policy

Local Policies --> Security Options

Network security: LAN Manager authentication level
Send LM & NTLM responses - use NTLMv2 session security if negotiated"

There, once again my Macs and PCs are at peace with each other again.

Wednesday, December 8, 2010

3 hours = worlds longest command line

This was on one line, thought I would share it with everyone:

msdeploy -verb:sync -source:"metakey=lm/w3svc/571459,computername=server1" -dest:"metakey=lm/w3svc/2989,computername=server2" -skip:"objectName=metaProperty,attributes.name=LogFileDirectory" -skip:"objectName=metaProperty,attributes.name=SSLStoreName" -skip:"objectName=metaProperty,attributes.name=SSLCertHash" -skip:"objectName=metaProperty,attributes.name=SSLStoreName" -skip:"objectName=metaProperty,attributes.name=ServerBindings" -skip:"objectName=metaKey,attributes.path=blahTOBlah" -skip:"objectName=metaKey,attributes.path=HTTPtoHTPPS" -skip:"objectName=metaKey,attributes.path=redirectToBLAH" -skip:"objectName=metaProperty,attributes.name=AppFriendlyName" -skip:"objectName=metaProperty,attributes.name=SecureBindings" -skip:skipAction=delete -replace:"objectName=metaProperty,match=m:\websitelocation1,replace=x:\websitelocation1" -replace:"objectName=metaProperty,targetAttributeName=value,match=apppool2\.0,replace=apppool" -replace:"objectName=dirPath,match=m:\website1,replace=x:\website" -enableLink:AppPool -disableLink:ContentExtension -whatif > msdeploysync.log



Ouch.
--Bryan

Tuesday, December 7, 2010

Microsoft finally follows it's own RFC... now stuff is broken.

We have a web service that goes out and talks to other web services. Our web service and the other ones are protected by firewalls, as we don't want just anyone hitting our web services. As we move to windows 2008 r2, we noticed something funny was happening..... our connections were being blocked.
Turns out that Microsoft is finally following their own RFC and it is breaking things.  Windows servers now will use the "IP address most closely matching the gateway" to decide what IP address to use as the default one.  So now our webservice was using the "lowest" ip address we had, which was for a site that had nothing to do with the webservice.
I found out I wasn't alone being surprised by this new "feature" and found that there is a workaround.
In short, you need to:
-Download and apply the hofix. (the MS extractor was currupt, so I used 7zip to extract the files)
-Reboot for the hotfix to take effect.
-Gather a list of all your IP addresses on that machine, take out the one you want to be the "default IP." Put them in the variable $currentIPs.  Then you can run the script as below, it will remove and add the IPs all at once with little downtime.

I forgot to remote desktop using the FQDN, so I was disconnected, but when I reconnected everything was happy.


$currentIps = "10.1.1.1","10.1.1.2","10.1.1.3","10.1.1.4"


foreach ($ip in $currentIps){

netsh interface ip delete address public $ip
write-host "$ip deleted"
netsh interface ip add address "public" $ip 255.255.255.0 skipassource=true
write-host "$ip added"
}
Write-Host "I suggest you reboot your server now, just in case."


Notice the "skipassource=true."  This will not work before the hotfix.  Again you do not want to run that parameter with your IP address that you DO want to be the default one.
(My Subnet mask is 255.255.255.0, if yours is different, then change it above.)

Monday, November 29, 2010

Windows Auditing can be annoying. (Shut up already)

My audit logs were filling up with a bunch of B.S. from perfectly good packets being successfully sent and received. (event id 5157, and 5152) By default, Windows thinks you want all of these packets logged... and perhaps some admins do. But they can be logged in the firewall log, I don't want them in the event log too. (Default location of the Windows Firewall log is at "C:\Windows\system32\LogFiles\Firewall\pfirewall.log") So after a bunch of googleing, I found several answers that almost worked. Here is what really worked for me on Windows 2008 R2 and R1:


auditpol /set /subcategory:"Filtering Platform Packet Drop" /success:disable /failure:disable

auditpol /set /subcategory:"Filtering Platform Connection" /success:disable /failure:disable

So there you go, save some audit log space for something that matters, like non-firewall stuff.
-Bryan

(oh, and one more thing, if you want to create a Group policy for this, it is under
computer configuration --> policies --> windows settings --> security settings --> advanced audit policy configuration --> audit policies --> object access. Then double click "Audit Filtering Platform Connection" and check only the box next to "configure the following audit events." DO NOT CLICK THE OTHER TWO BOXES. Repeat for "Audit Filtering Platform Packet Drop" too. If this does not work, edit your GPO to include the policy outlined in Method 1, steps 2 and 3 from http://support.microsoft.com/kb/921468 .  REMEMBER, THE GPO MIGHT TAKE SOME TIME, so if you don't reboot, give it at least 90 min before you give up on the GPO idea.)

Monday, October 11, 2010

Social Engineering, be careful what you ask for.

After planning on the trip to Vegas involving a unique idea with friends, I learned some things: (vagueness is purposeful as to not give too much away, this was in Vegas after all)
1) sometimes people will inherently trust or hate you based upon only what you are wearing.
2) Everyone likes to hang around with someone who is having a good time that is considered someone who shouldn't/can't.
3) Combined with #1, if you listen, people will speak to you.
4) Sometimes people just need to speak about their problems, even if the foundation of their trust is a lie. See #1. No matter what the trust is based on, it will still make them feel better.
5) By hearing other people's problems, it will probably make your problems seem smaller in comparison.
6) Everyone loves a man in a uniform.
7) Sometimes the best person to convince others to become religious is an atheist.
8) Margarita salt is not crack rock, no matter what crazy ladies tell you on the street corner.
9) No one wants to hit a father, or hit on, or be hit on by.
10) Everyone is curious about Buddhism, so will believe anything.... even if it is nothing.
11) If you are going to wear it, go all the way.
12) Lesbians are ok with men of the cloth, as long as they stay that way. But their friends might be ok with some change.
13) Photo bombing is not a sin if you are the judge of sin.
14) Hooters waitresses are usually nice girls who just need a job.
15) A priest who is having trouble walking is more convincing than a priest with communion wine bottle on his own two feet.
16) Motorcycles are still awesome.

Thursday, September 30, 2010

Install IIS and other IIS stuff on Server or a Desktop

I searched around, and didn't find anyone who had a way to install IIS from POSH. And if they got close, they didn't say that it didnt work on a server, or a desktop depending on the script. So here is one that will work on both, depending on what the user says they have:
#########################################################
#
# Script to install IIS.
#
# Created Sept 20, 2010
# Bryan Loveless 
#
#
# Requires Powershell 2.0
#
# Change your Execution policy to RemoteSigned if running locally
# by: Set-executionpolicy -executionpolicy RemoteSigned
#
#Prereqs: 
#
########################################################


$whorunsthis = Read-host "Is this a (S)erver or your (L)ocal_Developer box? (S/L)"

if ($whorunsthis -eq "S" )
    {   
 #get-windowsfeature will get list of Windows Component Intalled on SERVER

 Import-Module servermanager

 add-windowsfeature Application-Server
 add-windowsfeature AS-NET-Framework
 add-windowsfeature AS-Web-Support 
 add-windowsfeature AS-WAS-Support
 add-windowsfeature AS-HTTP-Activation  
 add-windowsfeature File-Services
 add-windowsfeature FS-FileServer
 add-windowsfeature Web-Server
 add-windowsfeature Web-WebServer
 add-windowsfeature Web-Common-Http
 add-windowsfeature Web-Static-Content
 add-windowsfeature Web-Default-Doc
 add-windowsfeature Web-Dir-Browsing
 add-windowsfeature Web-Http-Errors
 add-windowsfeature Web-Http-Redirect
 add-windowsfeature Web-App-Dev
 add-windowsfeature Web-Asp-Net
 add-windowsfeature Web-Net-Ext
 add-windowsfeature Web-ISAPI-Ext
 add-windowsfeature Web-ISAPI-Filter
 add-windowsfeature Web-Health
 add-windowsfeature Web-Http-Logging
 add-windowsfeature Web-Log-Libraries
 add-windowsfeature Web-Request-Monitor
 add-windowsfeature Web-Http-Tracing
 add-windowsfeature Web-Security
 add-windowsfeature Web-Basic-Auth
 add-windowsfeature Web-Windows-Auth
 add-windowsfeature Web-Digest-Auth
 add-windowsfeature Web-Client-Auth
 add-windowsfeature Web-Cert-Auth
 add-windowsfeature Web-Url-Auth
 add-windowsfeature Web-Filtering
 add-windowsfeature Web-IP-Security
 add-windowsfeature Web-Performance
 add-windowsfeature Web-Stat-Compression
 add-windowsfeature Web-Dyn-Compression
 add-windowsfeature Web-Mgmt-Tools
 add-windowsfeature Web-Mgmt-Console
 add-windowsfeature Web-Scripting-Tools
 add-windowsfeature Web-Mgmt-Service
 add-windowsfeature NET-Framework
 add-windowsfeature NET-Framework-Core
 add-windowsfeature NET-Win-CFAC
 add-windowsfeature NET-HTTP-Activation
 add-windowsfeature Multipath-IO
 add-windowsfeature RSAT
 add-windowsfeature RSAT-Role-Tools
 add-windowsfeature RSAT-Web-Server       
 add-windowsfeature SNMP-Services
 add-windowsfeature SNMP-Service
 add-windowsfeature SNMP-WMI-Provider
 add-windowsfeature Windows-Internal-DB
 add-windowsfeature PowerShell-ISE
 add-windowsfeature WAS
 add-windowsfeature WAS-Process-Model
 add-windowsfeature WAS-NET-Environment
 add-windowsfeature WAS-Config-APIs
 add-windowsfeature WSRM

}

elseif ($whorunsthis -eq "L")
    { 

 #oclist will give a list of what is possible
 # or try http://technet.microsoft.com/en-us/library/cc722041%28WS.10%29.aspx

 #below is for Desktops (windows 7)

 # install IIS Role
 ocsetup IIS-WebServerRole
 ocsetup IIS-WebServer
 ocsetup IIS-CommonHttpFeatures
 ocsetup IIS-DefaultDocument
 ocsetup IIS-HttpErrors
 ocsetup IIS-HttpRedirect
 ocsetup IIS-StaticContent
 ocsetup IIS-HealthAndDiagnostics
 ocsetup IIS-CustomLogging
 ocsetup IIS-HttpLogging
 ocsetup IIS-LoggingLibraries
   #ocsetup MSMQ-HTTP possbily needed for Ektron
 ocsetup IIS-RequestMonitor
 ocsetup IIS-Performance
 ocsetup IIS-HttpCompressionDynamic
 ocsetup IIS-HttpCompressionStatic
 ocsetup IIS-Security
 ocsetup IIS-BasicAuthentication
 ocsetup IIS-ClientCertificateMappingAuthentication
 ocsetup IIS-IISCertificateMappingAuthentication
 ocsetup IIS-IPSecurity
 ocsetup IIS-RequestFiltering
 ocsetup IIS-WindowsAuthentication
 ocsetup IIS-WebServerManagementTools
 ocsetup IIS-IIS6ManagementCompatibility
 ocsetup IIS-ManagementConsole

 # install .net
 ocsetup NetFx2-ServerCore
 ocsetup NetFx2-ServerCore-WOW64
 ocsetup NetFx3
 
 #install ASP
 ocsetup IIS-ASP
 
 # install asp.net  start /w
 ocsetup WAS-NetFxEnvironment
 ocsetup IIS-ISAPIExtensions
 ocsetup IIS-ISAPIFilter
 ocsetup IIS-NetFxExtensibility
 ocsetup IIS-ASPNET
 ocsetup IIS-ApplicationDevelopment
 ocsetup WCF-HTTP-Activation

}

else
    {write-host "you must select S or L"  
    Exit}


Tuesday, September 28, 2010

App pool restart using POSH

We sometimes want to restart an app pool on a server that is either misbehaving, or coud be locked up.  Here is a script to return all the app pools that are running on the server you specify, and enables you to restart just the app pool you want. This is my raw script, including some code I was expirementing with at the end of the script.

#############################################################################################
#
#Simple script to recycle an app pool of the User's choice on the server of the user's choice
#
# May 24, 2010
#Bryan Loveless 
#
#This must have PowerShell v2 or newer, find it at http://support.microsoft.com/kb/968929 if
# running win2k r1 or earlier. run Get-host if you are not sure what version you have.
# AS OF THIS DATE, THIS SCRIP MUST NOT USE POWERGUI, USE ISE TO MODIFY OR RUN.
#
#############################################################################################
#import-module webAdministration

#get servername to restart the pools on
$servername = Read-Host "Enter the name of the server to restart the pools on."

#connect to the server listed above
$connection = New-PSSession -ComputerName $servername 

#incase there are mutiple machines listed, this should keep track of them all (future implementation)
$psall = Get-PSSession

Write-Host "Here are the avalible app pools on the server you selected."

# run the command to see what app pools there are, but not enter the session yet.
# invoke-command -ComputerName $servername {get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool"} 


#Enter-PSSession -ComputerName $severname  #this way doesnt seem to work, see line below
# $connection | Enter-PSSession
Enter-PSSession -Session $connection

# tried a wait event to establish the connection, didn't work
# wait-event -timeout 5


#perhaps above return just the app pool name and status?
$pools= (get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool")

foreach($item in $pools)
{
 Write-Host $item.name
 Write-Host $item.status

}


$apppoolname = Read-Host "What is the name of the app pool you want to restart?"

#entering the session above so we can see the apps running
#Enter-PSSession -ComputerName $severname

#$appPoolName = $args[0]
$appPool = (get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"})

# it doesnt like to "restart" pools that are stopped, so I will stop and start them instead of recycle
# $appPool.Recycle()
$appPool.Stop()
$appPool.Start()


#end the connection to the server above
Exit-PSSession 
#Remove-PSSession -session $psall

#to help close sessions while coding
#$psall = Get-PSSession
#Remove-PSSession $psall

#Other interesting things that can be done with this variable once declared:
#
#EnumAppsInPool      Method       System.Management.ManagementBaseObject Enum...
#Recycle             Method       System.Management.ManagementBaseObject Recy...
#Start               Method       System.Management.ManagementBaseObject Start()
#Stop                Method       System.Management.ManagementBaseObject Stop()
#Caption             Property     System.String Caption {get;set;}
#Description         Property     System.String Description {get;set;}
#InstallDate         Property     System.String InstallDate {get;set;}
#Name                Property     System.String Name {get;set;}
#Status              Property     System.String Status {get;set;}
#

#Another interesting bit of code to borrow:
#function recycle-pool($strServerName)
#{
#    $objWMI = [WmiSearcher] "Select * From IIsApplicationPool"
#    $objWMI.Scope.Path = "\\" + $strServerName + "\root\microsoftiisv2"
#    $objWMI.Scope.Options.Authentication = 6
#    $pools = $objWMI.Get()
#    foreach ($pool in $pools)
#    {
#        $pool.recycle()
#        if (!$?)
#        {
#            Write-Host $pool.name " - ERROR"
#        }
#        else
#        {
#            Write-Host $pool.name " - Recycled"
#        }
#}


Using POSH to shutdown machines quickly

We were having some electrical issues in our building, and I wanted to have a script that would shutdown all of our test, dev, and QA machines in a hurry to preserve the remaining UPS power for the production machines. Below is a simple script I wrote to shutdown a predefined list of machines quickly:

----------------------------
###########################################################################
#
# Shutdown Test and Dev servers
#
# Created Aug 27, 2010
# Bryan Loveless 
# 
#
#
# Requires Powershell 2.0
#
# Change your Execution policy to RemoteSigned if running locally
# by: Set-executionpolicy -executionpolicy RemoteSigned
#
#Prereqs: 
#
#Caviots: 
# 
#
#
###########################################################################





$Victims="devserverWINSname1","testserverWINSname1","devserverWINSname2"

$shutdownjob = stop-computer -computername $victims -throttlelimit 5 AsJob 
#throttle limit is how many commands to send at once, this can be many, many more than 5 if you wish

Write-Host $shutdownjob



Run this script and  those machines named will be down before you know it.

Friday, August 27, 2010

trick POSH into modifying the security's username

Sometimes you have to find a way around things. When you get creds from POSH, it leaves a "/" in the username, so you cannot just pull out the username for use in something that is non-microsoft. Well you can trick it into modifying it by copying it out into a new object. I am not smart enough to figure this out, a coworker of mine did though. I give full credit to him for figuring this out, as we could not find anyone on the internet who had.
So the story is, I wanted to copy our subversion code repository from the REPO server over HTTPS to the local box to update the websites on it. We didn't want to put any passwords in the file, so we wanted to use the operator's MS domain username and password. It is important to note that our domain name has three letters, so we pull 4 out of the credentials. If your domain is more or less, you will have to pull out more or less.

#########################################################
#
# Script to copy Machine and Webconfigs from the ... repository to the local host.
#
# Created Aug 18, 2010
# Bryan Loveless 
#  Props to "Catatonic Prime" for figuring out the Creds object thing
#
#
# Requires Powershell 2.0
#
# Change your Execution policy to RemoteSigned if running locally
# by: Set-executionpolicy -executionpolicy RemoteSigned
#
#Prereqs: Run on local machine runnning as THE administrator.  (right click, run as)
#
#Caviots:  If the files dont seem to renew, make sure the repo on ... is updated
#          by running the svn update bat file in the root of C 
#   called "...." .
#   Also, if it doesnt run as a script, you can copy/paste into POSH cmd line.
#  
#
########################################################

#import the bitstransfer module to transfer files
Import-Module BitsTransfer

#get user credentials
Write-Host "use ... domain when logging in (123\ABC123)"
$Dirtycreds = Get-credential "123\USERNAME"

#clean up the username, as it doesnt want a / before the username
#one below only removes first character, need 4 removed to preserve domain in $DirtyCreds for later use
#$creds = New-Object -typeName 'System.Management.Automation.PSCredential' -ArgumentList $Dirtycreds.UserName.Remove(0,1),$Dirtycreds.Password
$creds = New-Object -typeName 'System.Management.Automation.PSCredential' -ArgumentList $Dirtycreds.UserName.Remove(0,4),$Dirtycreds.Password


#####refresh common components to update svn on ..., dont have to do if pulling from HTTPS
##$session1 New-PSSession -ComputerName servername.fully.qualified.here
##Invoke-Command -Session $session1 ""filethatcleansupSVN""
#Import-Module BitsTransfer

#set a timestamp to rename the file with, uses seconds so that it can be run more than once a minute
$timestamp = Get-Date -UFormat %Y%m%d%H%M%S

#set the path to the SVN server
$svnserver = "servername.fully.qualified.here"

#ask the user if they want a dev, test, prod, localhost config
$machinetype = Read-Host "What type of machine is this?  (dev, test, prod, localhost)"


#below compares to see what the user wanted, then changes the variable for the path accordingly
switch ($machinetype)
{
dev {$svnpath = "svn/projects/Configuration/Machine%20Configs/IIS7/2.0/Dev/"
$smbpath = "\\$svnserver\c$\Projects\Configuration\Machine Configs\IIS7\2.0\Dev"}
test {$svnpath = "svn/projects/Configuration/Machine%20Configs/IIS7/2.0/Test/" 
$smbpath = "\\$svnserver\c$\Projects\Configuration\Machine Configs\IIS7\2.0\Test"}
prod {$svnpath = "svn/projects/Configuration/Machine%20Configs/IIS7/2.0/Prod/" 
$smbpath = "\\$svnserver\c$\Projects\Configuration\Machine Configs\IIS7\2.0\Prod"}
localhost {$svnpath = "svn/projects/Configuration/Machine%20Configs/IIS7/2.0/localhost_developer/" 
$smbpath = "\\$svnserver\c$\Projects\Configuration\Machine Configs\IIS7\2.0\localhost_developer"}
default {  Write-Host "I dont know what you want. Close this and try again."
break }
}



#set the path to the .net directory on the local machine
$mypath = "C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG"

#rename the old files
rename-item -path "$mypath\web.config" -NewName web$timestamp.config 
rename-item -path "$mypath\machine.config" -NewName machine$timestamp.config 

#copy the files to the correct locations

#HTTPs method below 
start-bitstransfer -Authentication basic -Displayname "grabwconfig" -credential $creds -Source "https://$svnserver/$svnpath/web.config" -Destination $mypath\web.config 
start-bitstransfer -Authentication basic -Displayname "grabmconfig" -credential $creds -Source "https://$svnserver/$svnpath/machine.config" -Destination $mypath\machine.config 

#Below replaced by HTTPS method
#Copy-Item -Path "$smbpath/web.config" -Credential $creds -Destination "$mypath/web.Config"
#Copy-Item -Path "$smbpath/web.config" -Destination "$mypath/web.Config"
#Copy-Item -Path "$smbpath/machine.config" -Destination "$mypath/machine.Config"


# this will only do the part below if a 64 bit machine
$mypath = "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG"
if (test-path $mypath)
{
#rename the old files
rename-item -path $mypath\web.config -NewName web$timestamp.config
rename-item -path $mypath\machine.config -NewName machine$timestamp.config

#below replaced by HTTPs method
# Copy-Item -Path "$smbpath/web.config" -Destination "$mypath/web.Config"
# Copy-Item -Path "$smbpath/machine.config" -Destination "$mypath/machine.Config"

#pull it from HTTPs
start-bitstransfer -Authentication basic -Displayname "grabw64config" -credential $creds -Source "https://$svnserver/$svnpath/web.config" -Destination $mypath\web.config 
start-bitstransfer -Authentication basic -Displayname "grabm64config" -credential $creds -Source "https://$svnserver/$svnpath/machine.config" -Destination $mypath\machine.config

}


#copy applicationhost.config to the correct location and rename the old one
$mypath = "C:\Windows\System32\inetsrv\config"
$smbpath = "\\$svnserver\c$\Projects\Configuration\Machine Configs\IIS7"
$svnpath = "svn/projects/Configuration/Machine Configs/IIS7/"
rename-item -path $mypath\applicationHost.config -NewName applicationHost$timestamp.config

start-bitstransfer -Authentication basic -Displayname "grabAHconfig" -credential $creds -Source "https://$svnserver/$svnpath/applicationHost.config" -Destination $mypath\applicationHost.config 

#below replaced by HTTPs method
#Copy-item -path $smbpath\applicationHost.config -Destination "$mypath/applicationHost.config"

fix NTFS permissions on website directories using POSH

#########################################################
#
# Script to Fix web NTFS permissions.
#
# Created Aug 23, 2010
# Bryan Loveless 
#
#
# Requires Powershell 2.0
#
# Change your Execution policy to RemoteSigned if running locally
# by: Set-executionpolicy -executionpolicy RemoteSigned
#
#Prereqs: 
#
#
#based on http://blog.netnerds.net/2007/07/powershell-set-acl-does-not-appear-to-work/
#
########################################################



#the correct permissions on All Tiers (edited) are FC:(usernames went here for documentation)
# RXLR: localmachine\IIS_IUSRS


$whorunsthis = Read-host "Is this a (S)erver (c:\otherplaceIhavethem) or your (L)ocal box (C:\intetorsomething\Websites)? (S/L)"
Write-Host "Also, this script will take a few minutes, give it some time."

if ($whorunsthis -eq "S" )
{$path = "c:\otherplaceIhavethem" }
elseif ($whorunsthis -eq "L")
{$path = "C:\intetorsomething\Websites" }
else
{write-host "you must select S or L" 
Exit}

$fullControlDomainFolks = "user1","abc123","edf456","anotherusername"
$fullControlLocalUsers = "system"
$readOnlyLocalUsers = "IIS_IUSRS"

#now to run through the list of users listed in the $fullControlDomainFolks list.
ForEach ($specificUser in $fullControlDomainFolks)
{
$user = $specificUser
$userdomain = "DomainName"
#set up inheritance to be turned on
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
#set up propagation
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
#since get-acl only can deal with objects, we have to give it an object to start with.
$acl = Get-Acl $path

#setting what type of access we want the user to have.
#FYI, the possible values for $aclType are "ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, 
#ReadExtendedAttributes, WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, 
#ReadAttributes, WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions, 
#TakeOwnership, Synchronize, FullControl".
$aclType = "FullControl"
#set up the access rule by creating a new object with the variables set above.
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("$userdomain\$user", $aclType, $inherit, $propagation, "Allow")
#now to change the object we borrowed to what we actually want it to be
$acl.AddAccessRule($accessrule)
#now to actualy change the permissions on the path we specified.
set-acl -aclobject $acl $path
}

#now to run throught he list of users listed in the $fullcontrolLocalUsers list.
ForEach ($specificUser in $fullControlLocalUsers)
{
$user = $specificUser
#set up inheritance to be turned on
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
#set up propagation
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
#since get-acl only can deal with objects, we have to give it an object to start with.
$acl = Get-Acl $path

#setting what type of access we want the user to have.
#FYI, the possible values for $aclType are "ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, 
#ReadExtendedAttributes, WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, 
#ReadAttributes, WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions, 
#TakeOwnership, Synchronize, FullControl".
$aclType = "FullControl"
#set up the access rule by creating a new object with the variables set above.
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("$user", $aclType, $inherit, $propagation, "Allow")
#now to change the object we borrowed to what we actually want it to be
$acl.AddAccessRule($accessrule)
#now to actualy change the permissions on the path we specified.
set-acl -aclobject $acl $path
}

#now to run throught he list of users listed in the $ReadOnlyLocalUsers list.
ForEach ($specificUser in $ReadOnlyLocalUsers)
{
$user = $specificUser
#set up inheritance to be turned on
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
#set up propagation
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
#since get-acl only can deal with objects, we have to give it an object to start with.
$acl = Get-Acl $path

#setting what type of access we want the user to have.
#FYI, the possible values for $aclType are "ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, 
#ReadExtendedAttributes, WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, 
#ReadAttributes, WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions, 
#TakeOwnership, Synchronize, FullControl".
$aclType = "ReadAndExecute"
#set up the access rule by creating a new object with the variables set above.
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("$user", $aclType, $inherit, $propagation, "Allow")
#now to change the object we borrowed to what we actually want it to be
$acl.AddAccessRule($accessrule)
#now to actualy change the permissions on the path we specified.
set-acl -aclobject $acl $path
}

create a bunch of websites using POSH

#########################################################
#
# Script to Create the websites in all tiers.
#
# Created Aug 20, 2010
# Bryan Loveless 
#
#
# Requires Powershell 2.0
#
# Change your Execution policy to RemoteSigned if running locally
# by: Set-executionpolicy -executionpolicy RemoteSigned
#
#Prereqs: Have physical paths created already.  
#    Also must have at least one site that exists.  Keep the "Default" 
#        one for now.
#
########################################################
import-module webadministration

$physicalpath = "C:\Projects\Websites" 

#New-Item iis:\Sites\$sitename -bindings @{protocol="http";bindingInformation=":80:$sitename"} -physicalPath $physicalpath\$sitename

#list all websites below, IIS names are same as Physical Paths ON PURPOSE!

$listofwebsites = "site1","site2","site3","YouGetTheIdeaRight","wehavelotsmore","butforthisblog","IshortendTheList"

foreach ($site in $listofwebsites)
{
#create the site, associate with physical path. WILL OVERWRITE OLD SITE!
New-Item iis:\Sites\$site -bindings @{protocol="http";bindingInformation="*:80:"} -physicalPath $physicalpath\$site -Force

#Adds the HTTPS port to all sites.

New-WebBinding -Name "$site" -IP "*" -Port 443 -Protocol https

#stop the site after creating it
Stop-Website $site
}

# to see what a site has, try:
# get-webbinding -name "NAMEOFSITE"

Convert an IIS cert to an apache one

Here is a simple powershell script I wrote to convert a "iis" cert to one that apache is happy with to use with SSL:

####################################################


#convert IIS certs to openSSL ones for Apache to use
# openssl is installed with Apache by default.
#
#created May 24, 2010
#Bryan Loveless 
#
#

Write-host "This script assumes you have openssl installed in the C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin Directory 
And your certs are in the C:\Program Files (x86)\Apache Software Foundation\Apache2.2\certs Directory"


####################################################

Set-Location "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin"

$OrgCert=Read-Host "What is the name of your cert? (Include the .pfx)"

$NewCert= Read-Host "What do you want to name the new one? (Include the .pem) Normally it is apache.key.pem"

$NewKey= Read-Host "What do you want to name the new one? (Include the .key) Normally it is apache.key"

$newkey2= Read-Host "What do you want to name the new one? (Include the .pem) Normally it is apache.cert.pem"

#PS C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin> 

.\openssl.exe pkcs12 -in ..\certs\$OrgCert -nocerts -out ..\certs\$NewCert -nodes

#Enter Import Password:
#MAC verified OK
#Enter PEM pass phrase:
#Verifying - Enter PEM pass phrase:

#PS C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin> 
.\openssl.exe pkcs12 -in ..\certs\$OrgCert -clcerts -nokeys -out $newkey2
#Enter Import Password:
#PS C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin> 
.\openssl.exe rsa -in ..\certs\$NewCert -out ..\certs\$NewKey
#Enter pass phrase for ..\certs\apache.key.pem:
#writing RSA key
 for converting the chain 
#OpenSSL Convert P7B
#
#Convert P7B to PEM
#
#openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
#
#Convert P7B to PFX
#
#openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
#
#openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
#OpenSSL Convert PFX
#
#Convert PFX to PEM
#
#openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

Intro

With being an IT guy, sometimes it is easy to Google your way out of a problem.  Sometimes you may be the first one to discover something.  Sometimes you are not the first person to discover something, but the first to put the solution on the internet.  This blog is to possibly help someone else out with a problem I faced that I have solved.  Sometimes this may not just be about work though.  After all, the internet is supposed to know everything, right?  Lets help it out a bit.