El TecnoBaúl de Kiquenet

Kiquenet boring stories

Posts Tagged ‘credentials’

Manage Credentials programmatically using C#

Posted by kiquenet en 2 enero 2015

Credential Manager

CredentialManagement
http://nuget.org/packages/CredentialManagement/

http://credentialmanagement.codeplex.com/SourceControl/latest

CredMan.ps1
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde

        [TestMethod]
        public void Set_Credentials_for_older_domain_whe_migration_to_new_domain()
        {
            var accesos = new List<string> {
            "intranet",
            "intranet.xxxxx.net",
            "intranet.zzzzzzzz.com",
            "intranetescritorio.zzzzzzzz.net",
            "more…",
            };

            accesos.ForEach(acceso => SaveCredential(acceso));
        }

        private static Credential SaveCredential(string CredentialName)
        {
            var UserName = @"OLDERDOMAIN\user";
            var Password = "pass";

            var cm = new Credential { Target = CredentialName, Type = CredentialType.DomainPassword };
            if (cm.Exists())
            {
                cm.Load();
                Console.WriteLine("Credential " + cm.Target + ". Data: " + cm.Username + " " + cm.Password);

                //if (cm.Type == CredentialType.Generic)  cm.Delete();

                return cm;
            }

            cm = new Credential
            {
                Target = CredentialName,
                Type = CredentialType.DomainPassword,
                PersistanceType = PersistanceType.Enterprise,
                Username = UserName,
                Password = Password
            };
            cm.Save();
            return cm;
        }

Tools useful: PromptForCredentials Builder and Credential Set Manager by Kenny Kerr (Microsoft)

Windows 8 – New API Windows.Security
http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.aspx
https://code.msdn.microsoft.com/windowsapps/PasswordVault-f01be74a

[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ }

It only displays data from the Web Credentials store, not the Windows Credentials

The new api has no way to access the Windows Credentials

http://stackoverflow.com/questions/14813370/how-to-access-the-stored-credentials-passwordvault-on-win7-and-win8

Sources:

http://msdn.microsoft.com/en-us/library/aa480470.aspx#cred_topic5

http://stackoverflow.com/questions/9221245/how-do-i-store-and-retrieve-credentials-from-the-windows-vault-credential-manage

http://stackoverflow.com/questions/17741424/retrieve-credentials-from-windows-credentials-store-using-c-sharp

Posted in .NET, Security, Seguridad | Etiquetado: | Leave a Comment »

Using different credentials to connect to Team Foundation Server

Posted by kiquenet en 27 agosto 2014

TFS Cache
<system drive>\Users\<your profile>\AppData\Microsoft\Team Foundation

You can try clearing the cache manually here: C:\Users[USERNAME]\AppData\Local\Microsoft\Team Foundation\5.0\Cache

Control Panel->User Accounts –> Manage your credentials (CredentialManager)

You can also use the command line to open the credential manager.

control /name Microsoft.CredentialManager

This will open the credential manager.

Recently, I had to authenticate to Team Foundation Server using an account with greater permissions to perform some administrative tasks.  As you may know, this requires entering alternate credentials when you add the server to the list of TFS servers, or when you need to connect to the server.  Once you’ve connected once, you aren’t prompted again as the credentials are cached locally.

In the past, to remedy this, you could simply delete the local TFS cache, which is located in the following directory (Windows Vista and onwards):

<system drive>\Users\<your profile>\AppData\Microsoft\Team Foundation

image

However, in more recent versions this has changed somewhat, and the user’s credentials are no longer linked to the local TFS cache or configuration.

Where are the Credentials?

Good question.  After some digging about, it seems that the credentials are now stored in the user’s Credential Manager store within Windows.  If you aren’t familiar with this, it was introduced on the more recent versions of Windows, and it lives via the Control Panel, under the following path: Control Panel->User Accounts

image

Inside this location, you can view all the locally cached credentials, including Windows Credentials:

image

Note: that it appears that for TFS credentials used by Team Explorer and other applications, the credentials are the ones under “Generic Credentials” not under “Windows Credentials” (in case you have TFS entries in both).

Making Changes

To modify or remove the credentials you use to connect to TFS, simply expand the appropriate entry and click on “Edit”, or to delete the local credentials, click on “Remove”.  If you opt to remove the credentials, you’ll be prompted to enter new credentials next time you connect to the specified TFS server.

image

So that was a little out of the way. When I tested this, I made sure that I’d disconnected from TFS before changing/removing the credential configuration.

It would be nice if Team Explorer linked to the Credentials Manager so we didn’t have to go digging to work this out, wouldn’t it?

TFS credentials

When you connect TFS from Visual Studio you will be asked to give user credential to connect. If you checked the option Remember my credentials while connecting TFS, you won’t be asked credentials again to connect TFS. In that case, if you wanted to change different credentials to connect TFS. you need to follow below solution to force Visual Studio to ask new credentials to connect TFS.

Revert TFS credentials in Visual Studio

Force to change TFS credentials in Visual Studio

      You need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio
      1. Go to Control Panel (Start -> Control Panel).
      2. Click User Accounts ( or User Accounts and Family Safety->User Accounts in Windows 7 Machine)
      3. Click Credential Manager (or Manage your credentials)

Remove TFS user credentials in Visual Studio

     4. In Credential Manager page, you can see the two type of credentials
           i. Windows Credentials
           ii. Generic Credentials

     5. Click on two credential’s modify link,  click the link Remove from vault to remove stored TFS credentials.

Now, When you login into Visual Studio you will be asked to give credentials to connect TFS.

Note:
Don’t forgot to uncheck the option Remember my credentials to force to ask credentials for every TFS connections.

References:
http://sanderstechnology.com/2013/using-different-credentials-to-connect-to-team-foundation-server/11865/#.U-iskPl_vij
http://www.morgantechspace.com/2013/09/how-to-change-user-credentials-for-tfs.html

Posted in Seguridad, TFS | Etiquetado: , , | Leave a Comment »

PSExec Troubleshooting

Posted by kiquenet en 6 agosto 2014


Version PsExec v2.11


PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c
time /t

PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c echo ^%computername^%

Useful commands:

Checked the ports used by PSExec, 445 and 135, and both are open on the SERVER machine (nc is a unix commad)

nc –z SERVER 445
nc –z SERVER 135

Telnet SERVER 445

net user administrator /enable:yes

runas /user:myDomain\UserDeployTFS cmd

cmdkey.exe /add: SERVER /user:myDomain\UserDeployTFS /pass:XXXX

cmdkey.exe /delete: SERVER

all network based authentication/credentials between the two computers with differing clocks will fail. Local accounts will still be able to login. If you use something like psexec and instead of using your domain credentials, you specify valid administrative credentials on the local machine, it should connect just fine and allow you to fix the clock.

schtasks.exe /create /F /S $RemoteHost /ru domain\User /rp password /tn Sync-Time /sc Once /st $NowPlusOneMinute /tr "w32tm /resync"

PsExec needs the local administrator account on windows to be enabled. Recent Windows(following linux) has made this account default set to disabled(the logic is the same as for ‘sudo’ in linux: security). Enable this account by the following command(run command prompt as administrator)…

net user administrator /enable:yes

set the network credentials:
cmdkey /list:%DOMAIN% | find "%DOMAIN_USER%" >NUL || cmdkey /add:%DOMAIN% /user:%DOMAIN%\%DOMAIN_USER% /pass:%DOMAIN_USER_PWD% >>%LOGFILE% 2>>&1

Runas was not possible with local shares and other permissions.

Errors:

Couldn’t access SERVER:

Access is denied.

http://stackoverflow.com/questions/25035759/access-denied-using-psexec-when-connect-to-remote-server

http://serverfault.com/questions/616583/access-denied-using-psexec-when-connect-to-remote-server

References:

http://serverfault.com/questions/489822/psexec-is-not-connecting-to-machine-using-supplied-username-and-password/489845

http://serverfault.com/questions/216466/cannot-access-client-pc-remotely-due-to-time-date-issue-xp-win2k3-environment

http://stackoverflow.com/questions/20373885/psexec-and-windows-2008-server-access-denied

http://stackoverflow.com/questions/18791468/psexec-win7-to-win7-access-denied-psexesvc-remains

Posted in Comandos, Errores, Scripts | Etiquetado: , | Leave a Comment »

The Perils and Pitfalls of Launching a Process Under New Credentials by Asprosys

Posted by kiquenet en 9 mayo 2014

This isn’t a common need but it also isn’t that rare, so I thought I had better post this step by step guide to troubleshooting the launching of a process under impersonated credentials. This is based on using the Start method of the .Net Process class but it is also applicable to the underlying API calls: CreateProcessWithLogonW and CreateProcessWithTokenW.

Access Denied – The first attempt and an access denied exception right off the bat. This is the most common initial problem and is caused by the fact that the service is running under the LOCAL SYSTEM account. Strangely, the SYSTEM account is the most powerful account on the computer but one of the few things it cannot do is launch a process using CreateProcessWithLogonW which is the API underlying the call to Process.Start. So change your service account to Local Service, it’s probably the more appropriate account anyway.

Access Denied Again – Aargh, I thought we solved this. Oops, double check the permissions on the application that you are trying to launch. Remember that the system tries to access the application file as the user account that the process will be running under, not the service account.

Invalid Directory Error – What? All the paths are correct. All the directories are spelled correctly, no invalid characters. This is an incredibly annoying error and is not very consistent. Usually when we run a process we don’t bother setting the WorkingDirectory property and just accept the default from the parent process. When starting a process with new credentials you can’t do that, you must explicitly set a path for the WorkingDirectory or you’ll get a "The directory name is invalid." Win32Exception.

Failure: No Error? – Process.Start handles the creation of the Environment block for the new process for you quite well. So this is a problem only if you are using the underlying API. When calling one of the CreateProcess* APIs it is normal to leave the lpEnvironment parameter as NULL and have the system use the default of copying the block from the parent process. But when launching under new credentials you must create an environment block explicitly, either manually or using CreateEnvironmentBlock. What makes this worse is, if you leave this out the CreateProcess* call will fail but GetLastError will return ERROR_SUCCESS and if you make an error creating your environment block there will be no error but the process may just not run at all.

Application Failed to Initialize Properly – No more exceptions, you’ve solved all the problems and the process has been launched. Oops again, where is the process? Check the event log (or you may have received an Application Error pop-up). There should be an entry for Application Error that says that your process was the faulting application, either user32.dll or kernel32.dll was the faulting module and the exception was: 0xC0000142. There may be some minor variation in this but basically it is saying that your application could not initialize. The reason for this is that on initialization, before any application code is run, all processes are attached to a Window Station and all threads are attached to a Desktop but the user you are launching under does not have permission to access the Window Station and Desktop in which your process is being launched, ergo it can’t initialize. The security descriptors for the Window Station and Desktop must be adjusted to give AllAccess permission to the user the process is being launched under. This is a devil to do directly in .Net, so you might find the security wrapper classes here useful.

No More Errors – Really, no more errors, your process should be running smoothly now. There may be some variations in what you need to do based on who the user is (for instance an administrator will already have the correct permissions in some cases) or what kind of session you are launching in. But following these steps should make your life smooth and easy (well maybe not your whole life).

Solution:

I had to add a reference to AsproLock.dll and associated code in order to permit the user account to have access to the running resource.

            //The following security adjustments are necessary to give the new 
            //process sufficient permission to run in the service's window station
            //and desktop. This uses classes from the AsproLock library also from 
            //Asprosys.
            IntPtr hWinSta = NativeMethods.GetProcessWindowStation();
            WindowStationSecurity ws = new WindowStationSecurity(hWinSta,
              System.Security.AccessControl.AccessControlSections.Access);
            ws.AddAccessRule(new WindowStationAccessRule(userPassDto.Usuario,
                WindowStationRights.AllAccess, System.Security.AccessControl.AccessControlType.Allow));
            ws.AcceptChanges();

            IntPtr hDesk = NativeMethods.GetThreadDesktop(NativeMethods.GetCurrentThreadId());
            DesktopSecurity ds = new DesktopSecurity(hDesk,
                System.Security.AccessControl.AccessControlSections.Access);
            ds.AddAccessRule(new DesktopAccessRule(userPassDto.Usuario,
                DesktopRights.AllAccess, System.Security.AccessControl.AccessControlType.Allow));
            ds.AcceptChanges();

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetProcessWindowStation();

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetThreadDesktop(int dwThreadId);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern int GetCurrentThreadId();


References

http://asprosys.blogspot.com.es/2009/03/perils-and-pitfalls-of-launching.html

http://stackoverflow.com/questions/17488220/wcf-service-process-start-under-network-service-account-impersonating-as-a-diffe

Aspro Lock – Access Control

Code Samples

Creating New Process Under Alternate Credentials (createprocessasuser)

processstart-hangs

Posted in .NET, Security | Etiquetado: , , , | Leave a Comment »