samedi 14 avril 2012

Activer PSRemoting


Après pas mal de galères pour activer PSRemoting voici les étapes nécessaire pour le bon fonctionnement:
Mon but était qu'une machine non intégrée au domaine puisse exécuter des commande powershell a distance

Pour ce faire, il est nécessaire côté serveur de:

  • Mettre en place un clef dans la base de registre (si seules les machines de votre domaine vont accéder  à votre serveur, inutile - RQ: dans certains cas des erreurs d'accès refuser peuvent apparaître si vous ne mettez pas cette clef, ceci est du à l'UAC, et il faut alors utiliser le compte Administrator et non votre compte habituel d'administration (même si vous élever votre prompt))
  • Créer un certificat pour le support SSL
  • Activer PSRemoting
  • Activer le support SSL
  • Ouvrir le firewall
  • Autoriser CREDSSP
Côté client, il sera nécessaire:
  • Mettre en place un clef dans la base de registre (si seules les machines de votre domaine vont accéder  à votre serveur, inutile)
  • Activer la délégation serveur




#Configuration du serveur:
#Autorise les "Workgroup" à se connecter
#NB si votre machine cliente est en Workgroup, il faut ajouter cette clef a la base de registre
new-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -propertyType DWord -value 1

#Créer un certificat pour PSRemoting sur SSL
Depuis une MMC, ajouter le composant logiciel enfichable "Certificates" pour "Computer Account"
Dans "Personal", effectuez un clique-droit/All Tasks/Advanced Operations/Create Custom Request
Dans "Certificate Enrollement Policy" > Choisissez "Custom Request/Proceed without enrollement policy"
Dans "Custom request" > Choisissez "(no template) Legacy key"
Dans "Certificate Information" > Cliquez sur "Details" puis Properties
Dans "General" indiquez un nom pour le certificat et une description

Dans "Subject" choisissez "Common name" comme type et indiquer le FQDN de votre serveur, puis cliquez sur "Add" (dans mon cas, le FQDN du serveur est FRSPS-UNFRA01.NEXT.LAN)

Dans "Extensions", comme "Key usage" choisissez "Digital signature" & "Key encipherment"
comme "Extended Key usage" choisissez "Server Authentication" & "Client Authentication"

Dans "Private key", "Select Cryptographic Provider" décochez "Microsoft Strong Cryptographic Provider (Signature)", puis cochez "Microsoft RSA SChannel Cryptographic Provider (Encryption)"
puis dans "Key options" choisissez 2048 comme "Key size" et cochez "Make private key exportable"

Faites signer votre requête par votre autorité de CA (NB: si vous faites signer la requête par navigateur Web, il sera peut être necessaire d’exécuter IE en mode Administrateur (UAC) afin de disposer du bon template)
Depuis la navigateur Web: http://FQDNAutoriteDeCA/certsrv > Request Certificate > advanced certificate request > Submit a certificate request by using a base-64-encoded CMC or PKCS #10 file, or submit a renewal request by using a base-64-encoded PKCS #7 file
Coller votre requete, puis choisissez "web Server" comme "Certificate Template"
Téléchargez ensuite le certificat.

Depuis la console MMC, dans "Personal", effectuez un clique-droit/All Tasks/Import et importez le certificat signé précédemment.

#Activartion de PSRemoting
Enable-PSRemoting

#Activation du mode HTTPS
winrm quickconfig -transport:https

#Ajout des autorisations sur le certificat
winrm enumerate winrm/config/listener > identifier le certificat utilisé (CertificateThumbprint)
certutil –store my > Identifier le "Key container" qui correspond au certificat
Dans C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys, sur le fichier correspondant ajouter "Network Service" en lecture
Restart-Service winrm




#Pour voir les parametres WINRM
#winrm enumerate winrm/config/listener

#Configuration du Firewall
netsh advfirewall firewall add rule name="Windows Remote Management (HTTPs-In)" profile="Domain,Private,Public" dir=in protocol=tcp localport=5986 action=allow program="System" description="Inbound rule for Windows Remote Management via WS-Management. [TCP 5986]"

#Activation de l'authentification CredSSP
Enable-WSManCredSSP –Role Server

#Verification de l'existence du SPN (Eventlog Windows Remote Management 10154):
setspn -L ComputerNamme => Doit etre present WSMAN/FQDNDuServeur (ex: WSMAN/FRVES-INFRA01.NSDC.LAN): Si non present => setspn -A WSMAN/FQDN ComputerName (ex: setspn -A WSMAN/FRVES-INFRA01.NSDC.LAN frves-infra01)
setspn -L ComputerNamme => Doit etre present WSMAN/NomDuServeur (ex: WSMAN/FRVES-INFRA01): Si non present => setspn -A WSMAN/NomDuServeur ComputerName (ex: setspn -A WSMAN/FRVES-INFRA01 frves-infra01)
Restart-Service winrm

#Configuration du client:
#Autorise les "Workgroup" à se connecter au serveur
#NB si votre machine cliente est en Workgroup, il faut ajouter cette clef a la base de registre
new-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -propertyType DWord -value 1

#Activation de la delegation vers le serveur
Enable-WSManCredSSP –Role Client –DelegateComputer ServerFQDNWhereYouWouldLikeToConenctTo
(ex: Enable-WSManCredSSP –Role Client –DelegateComputer frves-infra02.nsdc.lan)

#Pour voir les machines auxquelles votre client peut accéder:
Get-WSManCredSSP

#Definition des options pour la conenction à distance
$so = New-PsSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$cred = Get-Credential  # Login/password pour se connecter à la ressource
#connection au serveur distant
Enter-PSSession ServerName -UseSSL -Authentication Credssp –cred $cred -SessionOption $so
(ex: Enter-PSSession frves-infra02.nsdc.lan -UseSSL -Authentication Credssp –cred $cred -SessionOption $so)



Les erreurs rencontrées:
Eventlog:
SChannel 36870: A fatal error occurred when attempting to access the SSL server credential private key. The error code returned from the cryptographic module is 0x8009030d. The internal error state is 10001.

Connection PSSEssion:
Enter-PSSession : Connecting to remote server failed with the following error message : The WinRM client received an HTTP server error status (500), but the remote service did not include any other information about the cause of the failure. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:16
+ Enter-PSSession <<<<  ServerFQDN -UseSSL -Authentication Credssp -cred $cred -SessionOption $so
    + CategoryInfo          : InvalidArgument: (ServerFQDN:String) [Enter-PSSession], PSRemotingTransportE
   xception
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Ce probleme provient d'un manque q'autorisation sur le certificat du serveur:
winrm enumerate winrm/config/listener > identifier le certificat utilisé (CertificateThumbprint)
certutil –store my > Identifier le "Key container" qui correspond au certificat
Dans C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys, sur le fichier correspondant ajouter "Network Service" en lecture
Restart-Service winrm

Eventlog:
Windows Remote Management 10149: The WinRM service is not listening for WS-Management requests. User Action If you did not intentionally stop the service, use the following command to see the WinRM configuration:  winrm enumerate winrm/config/listener
Windows Remote Management 10154: The WinRM service failed to create the following SPNs: WSMAN/ComputerFQDN; WSMAN/ComputerName. Additional Data The error received was 8344: %%8344.User Action The SPNs can be created by an administrator using setspn.exe utility.

Connection PSSession:
Enter-PSSession : Connecting to remote server failed with the following error message : The WinRM client cannot process the request. A computer policy does not allow the delegation of the user credentials to the target computer because the computer is not trusted. The identity of the target computer can be verified if you configure the WSMAN service to use a valid certificate using the following command: winrm set winrm/config/service '@{CertificateThumbprint=""}'  Or you can check the Event Viewer for an event that specifies that the following SPN could not be created: WSMAN/. If you find this event, you can manually create the SPN using setspn.exe .  If the SPN exists, but CredSSP cannot use Kerberos to validate the identity of the target computer and you still want to allow the delegation of the user credentials to the target computer, use gpedit.msc and look at the following policy: Computer Configuration ->Administrative Templates -> System -> Credentials Delegation -> Allow Fresh Credentials with NTLM-only Server Authentication.  Verify that it is enabled and configured with an SPN appropriate for the target computer. For example, for a target computer name "myserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. Try the request again after these changes. For more information, see the about_Remote_Troubleshooting Help top
ic.
At line:1 char:16
+ Enter-PSSession <<<<  ServerFQDN -UseSSL -Authentication Credssp -cred $cred -SessionOption $so
    + CategoryInfo          : InvalidArgument: (ServerFQDN:String) [Enter-PSSession], PSRemotingTransportE
   xception
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Ce probleme provient du fait que le SPN n'a pas ete crée correctement:
setspn -L ComputerNamme => WSMAN/FQDNDuServeur doit etre present (ex: WSMAN/FRVES-INFRA01.NSDC.LAN)
Si non present => setspn -A WSMAN/FQDN ComputerName (ex: setspn -A WSMAN/FRVES-INFRA01.NSDC.LAN frves-infra01)
setspn -L ComputerNamme => WSMAN/NomDuServeur doit etre present (ex: WSMAN/FRVES-INFRA01)
Si non present => setspn -A WSMAN/NomDuServeur ComputerName (ex: setspn -A WSMAN/FRVES-INFRA01 frves-infra01)
Restart-Service winrm

Si des erreurs sont encore présente il faut ajouter à "Network Service" l'autorisation "Validated write to service principal name": Via adsiedit.msc, sur votre contrôleur de domaine effectuez un clique-droit/propriétés, puis sur sécurité ajoutez le droit adéquat (source: http://www.sysads.co.uk/2011/11/active-directory-event-logs/)

Aucun commentaire:

Enregistrer un commentaire