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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Xml;

using Microsoft.Win32;

using Dbg = System.Management.Automation;

namespace Microsoft.WSMan.Management
{
    #region WSManCredSSP cmdlet base

    /// <summary>
    /// Base class used *-WSManCredSSP cmdlets (Enable-WSManCredSSP, Disable-WSManCredSSP)
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
    [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")]
    public class WSManCredSSPCommandBase : PSCmdlet
    {
        #region Protected / Internal Data

        internal const string Server = "Server";
        internal const string Client = "Client";

        #endregion

        #region Parameters

        /// <summary>
        /// Role can either "Client" or "Server".
        /// </summary>
        [Parameter(Mandatory = true, Position = 0)]
        [ValidateSet(Client, Server)]
        public string Role
        {
            get { return role; }

            set { role = value; }
        }

        private string role;
        #endregion

        #region Utilities

        /// <summary>
        /// </summary>
        /// <returns>
        /// Returns a session object upon successful creation..otherwise
        /// writes an error using WriteError and returns null.
        /// </returns>
        internal IWSManSession CreateWSManSession()
        {
            IWSManEx wsmanObject = (IWSManEx)new WSManClass();
            IWSManSession m_SessionObj = null;

            try
            {
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
                return m_SessionObj;
            }
            catch (COMException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "COMException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }

            return null;
        }

        #endregion
    }

    #endregion

    #region DisableWsManCredSsp

    /// <summary>
    /// Disables CredSSP authentication on the client. CredSSP authentication
    /// enables an application to delegate the user's credentials from the client to
    /// the server, hence allowing the user to perform management operations that
    /// access a second hop.
    /// </summary>
    [Cmdlet(VerbsLifecycle.Disable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096628")]
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
    [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")]
    public class DisableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable
    {
        #region private

        // The application name MUST be "wsman" as wsman got approval from security
        // folks who suggested to register the SPN with name "wsman".
        private const string applicationname = "wsman";

        private void DisableClientSideSettings()
        {
            WSManHelper helper = new WSManHelper(this);
            IWSManSession m_SessionObj = CreateWSManSession();
            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                string result = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlDocument resultopxml = new XmlDocument();
                resultopxml.LoadXml(result);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp);
                XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr);
                if (xNode is null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string inputXml = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>";

                m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0);

                if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                {
                    this.DeleteUserDelegateSettings();
                }
                else
                {
                    ThreadStart start = new ThreadStart(this.DeleteUserDelegateSettings);
                    Thread thread = new Thread(start);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                }

                if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname))
                {
                    helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null);
                }
            }
            catch (System.Xml.XPath.XPathException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                    Dispose(m_SessionObj);
            }
        }

        private void DisableServerSideSettings()
        {
            WSManHelper helper = new WSManHelper(this);
            IWSManSession m_SessionObj = CreateWSManSession();
            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0);
                XmlDocument resultopxml = new XmlDocument();
                resultopxml.LoadXml(result);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", helper.Service_CredSSP_XMLNmsp);
                XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr);
                if (xNode is null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex,
                        helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"),
                        ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string inputXml = string.Format(
                    CultureInfo.InvariantCulture,
                    @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>",
                    helper.Service_CredSSP_XMLNmsp);

                m_SessionObj.Put(helper.Service_CredSSP_Uri, inputXml, 0);
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }

        private void DeleteUserDelegateSettings()
        {
            System.IntPtr KeyHandle = System.IntPtr.Zero;
            IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass();
            GPO.OpenLocalMachineGPO(1);
            KeyHandle = GPO.GetRegistryKey(2);
            RegistryKey rootKey = Registry.CurrentUser;
            const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects";
            RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true);
            foreach (string keyname in GPOKey.GetSubKeyNames())
            {
                if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase))
                {
                    string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows";
                    DeleteDelegateSettings(applicationname, Registry.CurrentUser, key, GPO);
                }
            }

            KeyHandle = System.IntPtr.Zero;
        }

        private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, string Registry_Path, IGroupPolicyObject GPO)
        {
            WSManHelper helper = new WSManHelper(this);
            RegistryKey rKey;
            int i = 0;
            bool otherkeys = false;
            try
            {
                string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation";
                RegistryKey Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true);
                if (Allow_Fresh_Credential_Key != null)
                {
                    string[] valuenames = Allow_Fresh_Credential_Key.GetValueNames();
                    if (valuenames.Length > 0)
                    {
                        Collection<string> KeyCollection = new Collection<string>();
                        foreach (string value in valuenames)
                        {
                            object keyvalue = Allow_Fresh_Credential_Key.GetValue(value);
                            if (keyvalue != null)
                            {
                                if (!keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase))
                                {
                                    KeyCollection.Add(keyvalue.ToString());
                                    otherkeys = true;
                                }
                            }

                            Allow_Fresh_Credential_Key.DeleteValue(value);
                        }

                        foreach (string keyvalue in KeyCollection)
                        {
                            Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), keyvalue, RegistryValueKind.String);
                            i++;
                        }
                    }
                }

                if (!otherkeys)
                {
                    rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true);
                    if (rKey != null)
                    {
                        object regval1 = rKey.GetValue(helper.Key_Allow_Fresh_Credentials);
                        if (regval1 != null)
                        {
                            rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false);
                        }

                        object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh);
                        if (regval2 != null)
                        {
                            rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false);
                        }

                        if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null)
                        {
                            rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials);
                        }
                    }
                }

                GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814"));
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidArgument, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.SecurityError, null);
                WriteError(er);
            }
            catch (UnauthorizedAccessException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.SecurityError, null);
                WriteError(er);
            }
        }
        #endregion private
        /// <summary>
        /// Begin processing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            // If not running elevated, then throw an "elevation required" error message.
            WSManHelper.ThrowIfNotAdministrator();

            if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase))
            {
                DisableClientSideSettings();
            }

            if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase))
            {
                DisableServerSideSettings();
            }
        }

        #region IDisposable Members

        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose()
        {
            // CleanUp();
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose(IWSManSession sessionObject)
        {
            sessionObject = null;
            this.Dispose();
        }

        #endregion IDisposable Members
    }
    #endregion DisableWsManCredSSP

    #region EnableCredSSP
    /// <summary>
    /// Enables CredSSP authentication on the client. CredSSP authentication enables
    /// an application to delegate the user's credentials from the client to the
    /// server, hence allowing the user to perform management operations that access
    /// a second hop.
    /// This cmdlet performs the following:
    ///
    /// On the client:
    /// 1. Enables WSMan local configuration on client to enable CredSSP
    /// 2. Sets CredSSP policy AllowFreshCredentials to wsman/Delegate. This policy
    /// allows delegating explicit credentials to a server when server
    /// authentication is achieved via a trusted X509 certificate or Kerberos.
    /// </summary>
    [Cmdlet(VerbsLifecycle.Enable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096719")]
    [OutputType(typeof(XmlElement))]
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
    [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")]
    public class EnableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable/*, IDynamicParameters*/
    {
        /// <summary>
        /// Delegate parameter.
        /// </summary>
        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public string[] DelegateComputer
        {
            get { return delegatecomputer; }

            set { delegatecomputer = value; }
        }

        private string[] delegatecomputer;

        /// <summary>
        /// Property that sets force parameter.
        /// </summary>
        [Parameter]
        public SwitchParameter Force
        {
            get { return force; }

            set { force = value; }
        }

        private bool force = false;

        // helper variable
        private WSManHelper helper;

        // The application name MUST be "wsman" as wsman got approval from security
        // folks who suggested to register the SPN with name "wsman".
        private const string applicationname = "wsman";

        #region Cmdlet Overloads

        /// <summary>
        /// BeginProcessing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            // If not running elevated, then throw an "elevation required" error message.
            WSManHelper.ThrowIfNotAdministrator();
            helper = new WSManHelper(this);

            // DelegateComputer cannot be specified when Role is other than client
            if ((delegatecomputer != null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase))
            {
                string message = helper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified",
                    "DelegateComputer",
                    "Role",
                    Role,
                    Client);

                throw new InvalidOperationException(message);
            }

            // DelegateComputer must be specified when Role is client
            if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer == null))
            {
                string message = helper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified",
                    "DelegateComputer",
                    "Role",
                    Client);

                throw new InvalidOperationException(message);
            }

            if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase))
            {
                EnableClientSideSettings();
            }

            if (Role.Equals(Server, StringComparison.OrdinalIgnoreCase))
            {
                EnableServerSideSettings();
            }
        }

        #endregion

        /// <summary>
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        private void EnableClientSideSettings()
        {
            string query = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery");
            string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption");
            if (!force && !ShouldContinue(query, caption))
            {
                return;
            }

            IWSManSession m_SessionObj = CreateWSManSession();
            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                // get the credssp node to check if wsman is configured on this machine
                string result = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp);

                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                const string newxmlcontent = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>";
                try
                {
                    XmlDocument xmldoc = new XmlDocument();

                    // push the xml string with credssp enabled
                    xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0));

                    // set the Registry using GroupPolicyObject
                    if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                    {
                        this.UpdateCurrentUserRegistrySettings();
                    }
                    else
                    {
                        ThreadStart start = new ThreadStart(this.UpdateCurrentUserRegistrySettings);
                        Thread thread = new Thread(start);
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();
                    }

                    if (helper.ValidateCreadSSPRegistryRetry(true, delegatecomputer, applicationname))
                    {
                        WriteObject(xmldoc.FirstChild);
                    }
                    else
                    {
                        helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer);
                    }
                }
                catch (COMException)
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }

        private void EnableServerSideSettings()
        {
            string query = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery");
            string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption");
            if (!force && !ShouldContinue(query, caption))
            {
                return;
            }

            IWSManSession m_SessionObj = CreateWSManSession();
            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                // get the credssp node to check if wsman is configured on this machine
                string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0);
                XmlNode node = helper.GetXmlNode(result,
                    helper.CredSSP_SNode,
                    helper.Service_CredSSP_XMLNmsp);

                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    string newxmlcontent = string.Format(
                        CultureInfo.InvariantCulture,
                        @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>",
                        helper.Service_CredSSP_XMLNmsp);

                    // push the xml string with credssp enabled
                    xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0));
                    WriteObject(xmldoc.FirstChild);
                }
                catch (COMException)
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }

        /// <summary>
        /// </summary>
        private void UpdateCurrentUserRegistrySettings()
        {
            System.IntPtr KeyHandle = System.IntPtr.Zero;
            IGroupPolicyObject GPO = (IGroupPolicyObject)new GPClass();
            GPO.OpenLocalMachineGPO(1);
            KeyHandle = GPO.GetRegistryKey(2);
            RegistryKey rootKey = Registry.CurrentUser;
            const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects";
            RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true);
            foreach (string keyname in GPOKey.GetSubKeyNames())
            {
                if (keyname.EndsWith("Machine", StringComparison.OrdinalIgnoreCase))
                {
                    string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows";
                    UpdateGPORegistrySettings(applicationname, this.delegatecomputer, Registry.CurrentUser, key);
                }
            }
            // saving gpo settings
            GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("7A9206BD-33AF-47af-B832-D4128730E990"));
        }

        /// <summary>
        /// Updates the grouppolicy registry settings.
        /// </summary>
        /// <param name="applicationname"></param>
        /// <param name="delegatestring"></param>
        /// <param name="rootKey"></param>
        /// <param name="Registry_Path"></param>
        private void UpdateGPORegistrySettings(string applicationname, string[] delegatestring, RegistryKey rootKey, string Registry_Path)
        {
            // RegistryKey rootKey = Registry.LocalMachine;
            RegistryKey Credential_Delegation_Key;
            RegistryKey Allow_Fresh_Credential_Key;
            int i = 0;
            try
            {
                string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation";
                // open the registry key.If key is not present,create a new one
                Credential_Delegation_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation, RegistryKeyPermissionCheck.ReadWriteSubTree);

                Credential_Delegation_Key.SetValue(helper.Key_Allow_Fresh_Credentials, 1, RegistryValueKind.DWord);
                Credential_Delegation_Key.SetValue(helper.Key_Concatenate_Defaults_AllowFresh, 1, RegistryValueKind.DWord);

                // add the delegate value
                Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree);

                if (Allow_Fresh_Credential_Key != null)
                {
                    i = Allow_Fresh_Credential_Key.ValueCount;
                    foreach (string del in delegatestring)
                    {
                        Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), applicationname + @"/" + del, RegistryValueKind.String);
                        i++;
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccessException", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
        }

        #region IDisposable Members

        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose()
        {
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose(IWSManSession sessionObject)
        {
            sessionObject = null;
            this.Dispose();
        }

        #endregion IDisposable Members
    }
    #endregion EnableCredSSP

    #region Get-CredSSP

    /// <summary>
    /// Gets the CredSSP related configuration on the client. CredSSP authentication
    /// enables an application to delegate the user's credentials from the client to
    /// the server, hence allowing the user to perform management operations that
    /// access a second hop.
    /// This cmdlet performs the following:
    /// 1. Gets the configuration for WSMan policy on client to enable/disable
    /// CredSSP
    /// 2. Gets the configuration information for the CredSSP policy
    /// AllowFreshCredentials . This policy allows delegating explicit credentials
    /// to a server when server authentication is achieved via a trusted X509
    /// certificate or Kerberos.
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
    [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")]
    [Cmdlet(VerbsCommon.Get, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096838")]
    [OutputType(typeof(string))]
    public class GetWSManCredSSPCommand : PSCmdlet, IDisposable
    {
        #region private
        private WSManHelper helper = null;
        /// <summary>
        /// Method to get the values.
        /// </summary>
        private string GetDelegateSettings(string applicationname)
        {
            RegistryKey rootKey = Registry.LocalMachine;
            RegistryKey rKey;
            string result = string.Empty;
            string[] valuenames = null;
            try
            {
                string Reg_key = helper.Registry_Path_Credentials_Delegation + @"\CredentialsDelegation";
                rKey = rootKey.OpenSubKey(Reg_key);
                if (rKey != null)
                {
                    rKey = rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials);
                    if (rKey != null)
                    {
                        valuenames = rKey.GetValueNames();
                        if (valuenames.Length > 0)
                        {
                            string listvalue = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
                            foreach (string value in valuenames)
                            {
                                object keyvalue = rKey.GetValue(value);
                                if (keyvalue != null)
                                {
                                    if (keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase))
                                    {
                                        result = keyvalue.ToString() + listvalue + result;
                                    }
                                }
                            }

                            if (result.EndsWith(listvalue, StringComparison.OrdinalIgnoreCase))
                            {
                                result = result.Remove(result.Length - 1);
                            }
                        }
                    }
                }
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }
            catch (ObjectDisposedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "ObjectDisposedException", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }

            return result;
        }
        #endregion private

        #region overrides
        /// <summary>
        /// Method to begin processing.
        /// </summary>
        protected override void BeginProcessing()
        {
            // If not running elevated, then throw an "elevation required" error message.
            WSManHelper.ThrowIfNotAdministrator();
            helper = new WSManHelper(this);
            IWSManSession m_SessionObj = null;
            try
            {
                IWSManEx wsmanObject = (IWSManEx)new WSManClass();
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
                string result = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp);
                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }
                // The application name MUST be "wsman" as wsman got approval from security
                // folks who suggested to register the SPN with name "wsman".
                const string applicationname = "wsman";
                string credsspResult = GetDelegateSettings(applicationname);
                if (string.IsNullOrEmpty(credsspResult))
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred"));
                }
                else
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult);
                }

                // Get the server side settings
                result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0);
                node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp);
                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured"));
                }
                else
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured"));
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (System.Xml.XPath.XPathException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
        #endregion overrides
        #region IDisposable Members

        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose()
        {
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// Public dispose method.
        /// </summary>
        public
        void
        Dispose(IWSManSession sessionObject)
        {
            sessionObject = null;
            this.Dispose();
        }

        #endregion IDisposable Members
    }

    #endregion
}