Tuesday, April 10, 2012

Crossing Domains without Password Pain

I work in consulting, and as such, my machine is never on the client domain.  This causes some headache because every time I want to connect to a client resource, I am prompted for my client username and password.  By default, the client’s resources are in the Internet zone, so nothing is trusted, nor are my saved passwords used to authenticate – I am asked to reenter my password each time I connect to any resource.  Fortunately, there is an easy solution – simply add the domain as a Local Intranet site in your Internet settings.  Under Internet Options, Security, Local Intranet, Sites, Advanced, you can enter the paths to the client resource that you commonly access.  Once this is done, after you check the “Save Password” option when you access a resource again, you won’t have to reenter the password again.

If the client has a TFS instance, you can save your username and password used to access it by going to the team web access site in Internet Explorer and saving your credentials when prompted.  When you launch Visual Studio and connect to that TFS instance, it will then use your saved credentials.

Monday, April 9, 2012

Setting up a new IIS Server for ASP.NET or MVC

When setting up a new Windows Server for hosting ASP.NET or MVC applications, I have several Powershell scripts that I run to modify some of the default IIS settings.  You can also modify the IIS settings manually, but don’t fear the command line – it is your friend.

Powershell has an IIS module that you will need to import to run most of these commands – WebAdministration.  Now for the first set of scripts:
Import-Module WebAdministration
#expire web content after 30 days
Set-WebConfigurationProperty -filter "/system.webServer/staticContent/clientCache" -name cacheControlMode -value "UseMaxAge"
Set-WebConfigurationProperty -filter "/system.webServer/staticContent/clientCache" -name cacheControlMaxAge -value "30.00:00:00"
# change logging to include two more properties
Set-WebConfigurationProperty -filter "/system.applicationHost/sites/siteDefaults/logFile" -name logExtFileFlags -value "Date, Time, ClientIP, UserName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, BytesSent, BytesRecv, TimeTaken, ServerPort, UserAgent, HttpSubStatus"
# change the IIS server's header value to from value -- applies to ENTIRE SERVER
$computer = gc env:computername
Set-WebConfiguration  -filter "/system.webServer/httpProtocol/customHeaders/add[@value='ASP.NET']/@name" -value "From"
Set-WebConfiguration  -filter "/system.webServer/httpProtocol/customHeaders/add[@name='From']/@value" -value $computer

The above scripts are mostly self-explanatory – adjusting logging, static caching, and making sure the HTTP header of the sites on the box will include the box name.  This is especially useful in load-balanced scenarios, when you need to troubleshoot an errant server.

The next script modifies IIS to allow anonymous and windows authentication to be set in the web.config of child applications.
# change the master IIS config file to allow override of anonymous and windows auth
[xml]$config = Get-Content C:\Windows\System32\inetsrv\config\applicationHost.config
$config.selectSingleNode("/configuration/configSections/sectionGroup[@name='system.webServer']/sectionGroup[@name='security']/sectionGroup[@name='authentication']/section[@name='anonymousAuthentication']").SetAttribute("overrideModeDefault", "Allow")
$config.selectSingleNode("/configuration/configSections/sectionGroup[@name='system.webServer']/sectionGroup[@name='security']/sectionGroup[@name='authentication']/section[@name='windowsAuthentication']").SetAttribute("overrideModeDefault", "Allow")

By default IIS does not allow child applications to define their own authentication.  You can change a site’s security policy in the IIS manager, but this modifies the security settings in the applicationHost.config file instead of the web.config of the application.  You can allow the local site’s web.config to define this with the script below:

And finally, I prefer IIS to be clear of any default sites and application pools before I start adding my own, so I remove them (Warning: this will clear all sites and application pools from a server):
# RESET IIS environment
Remove-Item 'IIS:\AppPools\*' -Recurse
Remove-Item 'IIS:\Sites\*' -Recurse

Thursday, April 5, 2012

Assembly Implicit References, Installations, and the MSBuild Impact

I spent quite a bit of time trying to figure out why two of our Silverlight XAP files did not include the System.Windows.Controls.Toolkit.Internals.dll file when packaged on a build server.  Of course, when I built these locally, the XAP files were packaged correctly with this assembly being included in the XAP package.  I finally ran the exact same MSBuild command on both servers and then compared the output to determine why it was not being included.  When the Silverlight Toolkit is installed, it puts the reference assemblies under C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Bin.  We have not installed the toolkit on the build server; we have just added the assemblies to source control under a shared path.  What I found is that if the assemblies are not in their “default” location, when MSBuild compiles the code, it won’t copy implied assemblies to the bin directory of the project, which will then prevent these from being included in the XAP file.  In this example, System.Windows.Controls.Toolkit.dll references System.Windows.Controls.Toolkit.Internals.dll, but the latter is not referenced in the project.  If I compile on a machine that has the Toolkit installed, the latter assembly will be copied to the bin.  On a machine that does not have the toolkit installed, the Internals assembly will not be copied to the bin.

Interesting compile behavior.  Lesson learned: make your references explicit, especially for Silverlight projects.

Tuesday, April 3, 2012

Creating and Modifying MSMQ’s Using Powershell

There are a few Powershell functions that I have written and use to create and delete queues in MSMQ and to modify permissions on these queues.  At the end of the script there are a few examples on how to use the functions.
function Create-Queue
        [switch]$isPrivate = $true,     
        [switch]$isTransactional = $false
    $innerQueueName = $queueName
    if ($isPrivate)
        $innerQueueName = ".\private$\"+$queueName
        $innerQueueName = ".\"+$queueName
    if (![System.Messaging.MessageQueue]::Exists($innerQueueName))
        [System.Messaging.MessageQueue]::Create($innerQueueName, $isTransactional) 
        Write-Host "Created queue " $innerQueueName
    return $innerQueueName
function Add-QueueUserPermission
        [string]$fullControl = $false
    $q = new-object System.Messaging.MessageQueue($queuePath)
        if ($fullControl -eq $true)
            Write-Host "FullControl granted to "  $user
            $q.SetPermissions($User, [System.Messaging.MessageQueueAccessRights]::FullControl, [System.Messaging.AccessControlEntryType]::Allow) 
            Write-Host "Restricted access granted to "  $user      
            $q.SetPermissions($User, [System.Messaging.MessageQueueAccessRights]::DeleteMessage, [System.Messaging.AccessControlEntryType]::Set) 
            $q.SetPermissions($User, [System.Messaging.MessageQueueAccessRights]::GenericWrite, [System.Messaging.AccessControlEntryType]::Allow) 
            $q.SetPermissions($User, [System.Messaging.MessageQueueAccessRights]::PeekMessage, [System.Messaging.AccessControlEntryType]::Allow) 
            $q.SetPermissions($User, [System.Messaging.MessageQueueAccessRights]::ReceiveJournalMessage, [System.Messaging.AccessControlEntryType]::Allow)
function Delete-Queue
function Delete-Queues
    [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine($Env:COMPUTERNAME) | ForEach-Object { Delete-Queue($_.Path) }
    [System.Messaging.MessageQueue]::GetPublicQueuesByMachine($Env:COMPUTERNAME) | ForEach-Object { Delete-Queue($_.Path) }
# creates a queue that is private but not transactional
#Create-Queue -queueName "My Queue" -isPrivate $true -isTransactional $false
# grants restricted access to the queue
#Add-QueueUserPermission -queuePath ".\private$\My Queue" -user 'domain\account'
# grants full control to the queue
#Add-QueueUserPermission -queuePath ".\private$\My Queue" -user 'domain\account' -fullControl

Build Projects and Solutions from Windows Explorer with MSBuild 4.0

Copy the following into a .reg file and run. This will give you the ability to Build, Clean, and Rebuild from the Windows Explorer Context menu.

Windows Registry Editor Version 5.00 




@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:build\"" 


@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:clean\""


@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:rebuild\""




@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:build\""


@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:clean\""


@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:rebuild\""




@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:build\""


@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:clean\""

@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe\" \"%1\" /t:rebuild\""

For more advanced control, try the MSBuild Launch Pad on Codeplex.

Sunday, April 1, 2012

Team Foundation Server 2010 Security Practices

A coworker asked me to point him to the location where to find the documents on TFS Security Best Practices and I realized they don’t exist!  There are a number of blog posts with people describing how they have configured TFS, and there are some documents on MSDN that provide the permissions and roles that are available in TFS, but I didn’t see anything that provided a good overview and guidance on setting up and managing TFS security.  So, I will briefly cover the surface area of TFS security, a couple of tools that will help make security management a bit easier, and then some practical recommendations on configuring security.

TFS Security

Managing security in TFS involves managing security to three different components: TFS itself, WSS or Sharepoint, and Reporting Services.  Each of these has different access levels, roles, and permissions, so it isn’t as simple as a single selection.  Out-of-the-box, a team project will be compromised of the following roles within the different application components:
Team Project RolesSharepoint RolesReporting Services Roles
Project Administrators
Full Control
Content Manager
  • ProjectName\Project Administrators Members of this group can administer all aspects of the team project, although they cannot create projects.
  • ProjectName\Contributors Members of this group can contribute to the project in multiple ways, such as adding, modifying, and deleting code and creating and modifying work items.
  • ProjectName\Readers Members of this group can view the project but not modify it.
  • ProjectName\Builders Members of this group have build permissions for the project. Members can manage test environments, create test runs, and manage builds.
Additionally, access to TFS can be granted at three primary levels – server, collection, and project.  You will very rarely assign permissions at the server and collection level, although the latter is a little more common.  Typically your TFS Admin account(s) and service accounts will be assigned at the server level, and your collection administrators will be assigned at the collection level.  The bulk of the role and permission assignments happen at the team project level.

TFS Security Tools

Fortunately, you don’t have to manage the permissions to all three locations separately.  TheTeam Foundation Server Administration Tool is a free, open-source, tool that consolidates this into a single interface.  The other tool that I have found extremely useful for viewing and managing user workspaces and content is the Team Foundation Sidekicks tool from Attrice(also free).  Note that both of these tools are specific to a team project; you can’t use either to manage the server or collection membership.

Configuring Security

Since TFS is built on top of and integrates nicely with Active Directory, it is strongly recommended to use Active Directory groups to manage access to TFS.  In fact, I’ll go so far as to say unless it is impossible to do so, manage all access to TFS through Active Directory groups.  I think you will find this can be done in almost all of the cases.  This will radically simplify the surface area of what must be managed.  As a practical note, typically a new hire will need to be added to certain A/D groups; why not include the appropriate TFS A/D groups in the “new hire ticket” as well?  In addition, by configuring access to an Active Directory group, granting users the same set of permissions involves simply adding them to that group, rather than duplicating the entire subset of permissions.
  • Use Active Directory groups to manage TFS access
The other strong recommendation I would make is that access to TFS should reflect the structure of the project teams.  Since we are remaining with A/D groups, this means my A/D group structure that provides access to TFS should reflect the team and project structure.  I’ll also add that it will be very helpful to create a tree structure of groups so that permissions will roll up.  I will talk more of this as we walk through some scenarios.  My primary push for this is to encourage you to work with your Infrastructure people to get groups defined in such a way that reflects your teams and projects, if possible.  Usually they like simple and easy-to-manage too!
  • A/D groups for TFS access should reflect team and project structure.
Let’s cover project collections and team projects.
When would I consider a new project collection?
The primary limitation to keep in mind with team project collections is that the artifacts are not accessible across collections. You cannot access work items, source, builds, etc. across collections. If your team or organization does not integrate with other teams and has very little if any dependencies, a collection may make more sense. However, keep in mind – moving a team project to a different collection is not supported. There are a variety of reasons for this – within each collection, work item IDs, changeset numbers, builds, etc. all start from 1, so you would have major clashes if you tried to consolidate collections. You might consider project collections at a department level – perhaps HR, Internal IT, and Products each have their own collection.
When would I consider a new team project?
A team project can provide a way to encapsulate security, code, and project management activities for a team or project. If you are leveraging Sharepoint and keep the option checked, TFS will create a new Sharepoint site when the project is created. Items across team projects are visible to other team projects within a collection, if security allows. This includes work items, builds, source control, and reports. You might consider team projects when you are creating a product, starting a new project that falls within existing department, or want to track activities that fall within a distinct bucket. Keep in mind that Areas and Iterations can be used within team projects to provide some segregation of activities, so you may not need a new team project if it is just an extension of an existing project or effort.
Now that we have the above two ideas defined and some collection versus team project recommendations, let’s walk through some practical scenarios.  These are based on several different organizations that I’ve been a part of and the work I did in managing TFS access for each organization.  My convention is to use a “TFS.” prefix on the A/D group name so that it is clear that it is for TFS access.  However, this can also be done via OUs in A/D, depending on your Infrastructure preferences.
Scenario 1: Multiple Departments, Multiple Products, Not-Shared within an IT organization
For our first scenario, let’s take an IT department that contains multiple teams, where each team works on multiple, independent internal company products.  It is very unusual for the teams to share resources and thus any sharing is considered a transfer to a new team.  Each team is cross-functional, containing QA, dev, BA, manager, and architect resources.  The access requirements for these resources are the following:
  • Architects and possibly team leads should have Project Admin rights, and are the ones responsible for builds.
  • Developers should be Contributors.
  • QA, BA, and managers should have read-only rights to the source control, but be able to manage work items, iterations, areas, etc.
  • The PMO office (executives) want to run reports and read access to source is fine.
We might create a group structure that looks like the following:
A/D Group NameTFS Team Project PermissionMembers
TFS.AllAll TFS.* groups
TFS.ProjectNameAll TFS.ProjectName.* groups
TFS.ProjectName.AdminsProject AdministratorArchitects, maybe leads
TFS.ProjectName.EditorsWork Item EditorQA, BAs, Managers
TFS.ProjectName.PMOReaderPMO office
The Work Item Editor role is a new TFS security group that we will create for the project, with the permissions for that role granting view and edit on work items, iterations, and areas, but read only on source control.  Note that we create a group that contains the other groups – this makes it easy to do team level activity, like email everyone on the team, regardless of role.  If you need to separate the Editor group into separate QA, BA, and Manager groups, that can be easily done as well.
Scenario 2: Multiple Departments, Multiple Products, Shared within an IT organization
For our second scenario, let’s modify one thing: the developer and QA resources within the organization are shared across projects, but the team leads, managers, and BAs are dedicated consistently to a project.  In this case, we might do something like:
A/D Group NameTFS Team Project PermissionMembers
TFS.AllAll TFS.* groups
TFS.ProjectNameAll TFS.ProjectName.* groups
TFS.ProjectName.AdminsProject AdministratorProject leads
TFS.ProjectName.EditorsWork Item EditorManagers and BAs
TFS.QAWork Item Editor for all dev projectsQA
TFS.DevelopersContributor for all dev projectsDev, Architects
Once again, you can separate the devs and architects, QA and BAs, if needed.
Scenario 3: Single Department, Multiple Products
For the third scenario, we just have a single department with multiple products (and thus I am assuming it is the same team that works the products).  You can create each product as a separate team project, and in some cases, this can make sense.  The big advantage to having the different products within the same team project is that you can roll everything up under a single project, so it makes resource availability, tracking, and iteration planning simpler.  Since this scenario assumes the same team, the groups don’t need any team or project designation:
A/D Group NameTFS Team Project PermissionMembers
TFS.AllAll TFS.* groups
TFS.AdminsProject AdministratorProject leads
TFS.ManagersWork Item EditorManagers
TFS.EditorsWork Item Editor for all dev projectsQA and BAs
TFS.DevelopersContributor for all dev projectsDev, Architects
Scenario 4: Multiple Teams, Multiple Products, Some Common, Some Team-Specific
For the fourth scenario, let’s take the same idea of multiple teams and products, but vary it slightly by stating that each team manages multiple products, and there are some projects that are common across all the teams.  In this instance, we might create team specific A/D groups and then assign them to the respective product-specific team projects and any common team projects for which they need access.  I’ve found it is helpful to create a team project named Common or Shared that contains the shared artifacts across the teams, so that it is clear that it is shared.  If you want to segregate it further (have multiple shared team projects), consider naming the common team projects with a Common or Shared prefix, such as “Common-Architecture”, “Common-Services”, etc.
A/D Group NameTFS Team Project PermissionMembers
TFS.AllAll TFS.* groups
TFS.TeamNameAll TFS.TeamName.* groups
TFS.TeamName.AdminsProject Administrator for team-specific and common projectsProject leads
TFS.TeamName.DevelopersContributor for team-specific and common projectsDevelopers
TFS.TeamName.EditorsWork Item Editor for team-specific and common projectsManagers, QA, BAs
You can of course separate the common project access into its own security groups, if needed (TFS.Common.Admins, TFS.Common.Developers,…).
Hopefully this helps as you define your TFS security model.