PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Bootstrapper/Set-SecureAutoLogon.ps1

http://boxstarter.codeplex.com
Powershell | 319 lines | 232 code | 23 blank | 64 comment | 4 complexity | 74febbbc7e5d5f803bb7d8b434cc6170 MD5 | raw file
Possible License(s): MIT
  1. <#
  2. ***********************************************************************************
  3. * This function was written by Andy Arismendi
  4. * Published at http://poshcode.org/2982
  5. * Under Creative Commons Lisence
  6. * http://creativecommons.org/publicdomain/zero/1.0/legalcode
  7. ***********************************************************************************
  8. #>
  9. function Set-SecureAutoLogon {
  10. [cmdletbinding()]
  11. param (
  12. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]
  13. $Username,
  14. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.Security.SecureString]
  15. $Password,
  16. [string]
  17. $Domain,
  18. [Int]
  19. $AutoLogonCount,
  20. [switch]
  21. $RemoveLegalPrompt,
  22. [System.IO.FileInfo]
  23. $BackupFile
  24. )
  25. begin {
  26. [string] $WinlogonPath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon"
  27. [string] $WinlogonBannerPolicyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
  28. [string] $Enable = 1
  29. [string] $Disable = 0
  30. #region C# Code to P-invoke LSA LsaStorePrivateData function.
  31. Add-Type @"
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Text;
  35. using System.Runtime.InteropServices;
  36. namespace ComputerSystem
  37. {
  38. public class LSAutil
  39. {
  40. [StructLayout(LayoutKind.Sequential)]
  41. private struct LSA_UNICODE_STRING
  42. {
  43. public UInt16 Length;
  44. public UInt16 MaximumLength;
  45. public IntPtr Buffer;
  46. }
  47. [StructLayout(LayoutKind.Sequential)]
  48. private struct LSA_OBJECT_ATTRIBUTES
  49. {
  50. public int Length;
  51. public IntPtr RootDirectory;
  52. public LSA_UNICODE_STRING ObjectName;
  53. public uint Attributes;
  54. public IntPtr SecurityDescriptor;
  55. public IntPtr SecurityQualityOfService;
  56. }
  57. private enum LSA_AccessPolicy : long
  58. {
  59. POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
  60. POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
  61. POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
  62. POLICY_TRUST_ADMIN = 0x00000008L,
  63. POLICY_CREATE_ACCOUNT = 0x00000010L,
  64. POLICY_CREATE_SECRET = 0x00000020L,
  65. POLICY_CREATE_PRIVILEGE = 0x00000040L,
  66. POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
  67. POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
  68. POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
  69. POLICY_SERVER_ADMIN = 0x00000400L,
  70. POLICY_LOOKUP_NAMES = 0x00000800L,
  71. POLICY_NOTIFICATION = 0x00001000L
  72. }
  73. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  74. private static extern uint LsaRetrievePrivateData(
  75. IntPtr PolicyHandle,
  76. ref LSA_UNICODE_STRING KeyName,
  77. out IntPtr PrivateData
  78. );
  79. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  80. private static extern uint LsaStorePrivateData(
  81. IntPtr policyHandle,
  82. ref LSA_UNICODE_STRING KeyName,
  83. ref LSA_UNICODE_STRING PrivateData
  84. );
  85. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  86. private static extern uint LsaOpenPolicy(
  87. ref LSA_UNICODE_STRING SystemName,
  88. ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
  89. uint DesiredAccess,
  90. out IntPtr PolicyHandle
  91. );
  92. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  93. private static extern uint LsaNtStatusToWinError(
  94. uint status
  95. );
  96. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  97. private static extern uint LsaClose(
  98. IntPtr policyHandle
  99. );
  100. [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
  101. private static extern uint LsaFreeMemory(
  102. IntPtr buffer
  103. );
  104. private LSA_OBJECT_ATTRIBUTES objectAttributes;
  105. private LSA_UNICODE_STRING localsystem;
  106. private LSA_UNICODE_STRING secretName;
  107. public LSAutil(string key)
  108. {
  109. if (key.Length == 0)
  110. {
  111. throw new Exception("Key lenght zero");
  112. }
  113. objectAttributes = new LSA_OBJECT_ATTRIBUTES();
  114. objectAttributes.Length = 0;
  115. objectAttributes.RootDirectory = IntPtr.Zero;
  116. objectAttributes.Attributes = 0;
  117. objectAttributes.SecurityDescriptor = IntPtr.Zero;
  118. objectAttributes.SecurityQualityOfService = IntPtr.Zero;
  119. localsystem = new LSA_UNICODE_STRING();
  120. localsystem.Buffer = IntPtr.Zero;
  121. localsystem.Length = 0;
  122. localsystem.MaximumLength = 0;
  123. secretName = new LSA_UNICODE_STRING();
  124. secretName.Buffer = Marshal.StringToHGlobalUni(key);
  125. secretName.Length = (UInt16)(key.Length * UnicodeEncoding.CharSize);
  126. secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize);
  127. }
  128. private IntPtr GetLsaPolicy(LSA_AccessPolicy access)
  129. {
  130. IntPtr LsaPolicyHandle;
  131. uint ntsResult = LsaOpenPolicy(ref this.localsystem, ref this.objectAttributes, (uint)access, out LsaPolicyHandle);
  132. uint winErrorCode = LsaNtStatusToWinError(ntsResult);
  133. if (winErrorCode != 0)
  134. {
  135. throw new Exception("LsaOpenPolicy failed: " + winErrorCode);
  136. }
  137. return LsaPolicyHandle;
  138. }
  139. private static void ReleaseLsaPolicy(IntPtr LsaPolicyHandle)
  140. {
  141. uint ntsResult = LsaClose(LsaPolicyHandle);
  142. uint winErrorCode = LsaNtStatusToWinError(ntsResult);
  143. if (winErrorCode != 0)
  144. {
  145. throw new Exception("LsaClose failed: " + winErrorCode);
  146. }
  147. }
  148. public void SetSecret(string value)
  149. {
  150. LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING();
  151. if (value.Length > 0)
  152. {
  153. //Create data and key
  154. lusSecretData.Buffer = Marshal.StringToHGlobalUni(value);
  155. lusSecretData.Length = (UInt16)(value.Length * UnicodeEncoding.CharSize);
  156. lusSecretData.MaximumLength = (UInt16)((value.Length + 1) * UnicodeEncoding.CharSize);
  157. }
  158. else
  159. {
  160. //Delete data and key
  161. lusSecretData.Buffer = IntPtr.Zero;
  162. lusSecretData.Length = 0;
  163. lusSecretData.MaximumLength = 0;
  164. }
  165. IntPtr LsaPolicyHandle = GetLsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET);
  166. uint result = LsaStorePrivateData(LsaPolicyHandle, ref secretName, ref lusSecretData);
  167. ReleaseLsaPolicy(LsaPolicyHandle);
  168. uint winErrorCode = LsaNtStatusToWinError(result);
  169. if (winErrorCode != 0)
  170. {
  171. throw new Exception("StorePrivateData failed: " + winErrorCode);
  172. }
  173. }
  174. }
  175. }
  176. "@
  177. #endregion
  178. }
  179. process {
  180. try {
  181. $ErrorActionPreference = "Stop"
  182. $decryptedPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
  183. [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
  184. )
  185. if ($BackupFile) {
  186. # Initialize the hash table with a string comparer to allow case sensitive keys.
  187. # This allows differentiation between the winlogon and system policy logon banner strings.
  188. $OrigionalSettings = New-Object System.Collections.Hashtable ([system.stringcomparer]::CurrentCulture)
  189. $OrigionalSettings.AutoAdminLogon = (Get-ItemProperty $WinlogonPath ).AutoAdminLogon
  190. $OrigionalSettings.ForceAutoLogon = (Get-ItemProperty $WinlogonPath).ForceAutoLogon
  191. $OrigionalSettings.DefaultUserName = (Get-ItemProperty $WinlogonPath).DefaultUserName
  192. $OrigionalSettings.DefaultDomainName = (Get-ItemProperty $WinlogonPath).DefaultDomainName
  193. $OrigionalSettings.DefaultPassword = (Get-ItemProperty $WinlogonPath).DefaultPassword
  194. $OrigionalSettings.AutoLogonCount = (Get-ItemProperty $WinlogonPath).AutoLogonCount
  195. # The winlogon logon banner settings.
  196. $OrigionalSettings.LegalNoticeCaption = (Get-ItemProperty $WinlogonPath).LegalNoticeCaption
  197. $OrigionalSettings.LegalNoticeText = (Get-ItemProperty $WinlogonPath).LegalNoticeText
  198. # The system policy logon banner settings.
  199. $OrigionalSettings.legalnoticecaption = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticecaption
  200. $OrigionalSettings.legalnoticetext = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticetext
  201. $OrigionalSettings | Export-Clixml -Depth 10 -Path $BackupFile
  202. }
  203. # Store the password securely.
  204. $lsaUtil = New-Object ComputerSystem.LSAutil -ArgumentList "DefaultPassword"
  205. $lsaUtil.SetSecret($decryptedPass)
  206. # Store the autologon registry settings.
  207. Set-ItemProperty -Path $WinlogonPath -Name AutoAdminLogon -Value $Enable -Force
  208. Set-ItemProperty -Path $WinlogonPath -Name DefaultUserName -Value $Username -Force
  209. Set-ItemProperty -Path $WinlogonPath -Name DefaultDomainName -Value $Domain -Force
  210. if ($AutoLogonCount) {
  211. Set-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -Value $AutoLogonCount -Force
  212. } else {
  213. Remove-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -ErrorAction SilentlyContinue
  214. }
  215. if ($RemoveLegalPrompt) {
  216. Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeCaption -Value $null -Force
  217. Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeText -Value $null -Force
  218. Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticecaption -Value $null -Force
  219. Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticetext -Value $null -Force
  220. }
  221. } catch {
  222. throw 'Failed to set auto logon. The error was: "{0}".' -f $_
  223. }
  224. }
  225. }
  226. <#
  227. .SYNOPSIS
  228. Enables auto logon using the specified username and password.
  229. .PARAMETER Username
  230. The username of the user to automatically logon as.
  231. .PARAMETER Password
  232. The password for the user to automatically logon as.
  233. .PARAMETER Domain
  234. The domain of the user to automatically logon as.
  235. .PARAMETER AutoLogonCount
  236. The number of logons that auto logon will be enabled.
  237. .PARAMETER RemoveLegalPrompt
  238. Removes the system banner to ensure interventionless logon.
  239. .PARAMETER BackupFile
  240. If specified the existing settings such as the system banner text will be backed up to the specified file.
  241. .EXAMPLE
  242. PS C:\> Set-SecureAutoLogon `
  243. -Username $env:USERNAME `
  244. -Password (Read-Host -AsSecureString) `
  245. -AutoLogonCount 2 `
  246. -RemoveLegalPrompt `
  247. -BackupFile "C:\WinlogonBackup.xml"
  248. .INPUTS
  249. None.
  250. .OUTPUTS
  251. None.
  252. .NOTES
  253. Revision History:
  254. 2011-04-19 : Andy Arismendi - Created.
  255. 2011-09-29 : Andy Arismendi - Changed to use LSA secrets to store password securely.
  256. .LINK
  257. http://support.microsoft.com/kb/324737
  258. .LINK
  259. http://msdn.microsoft.com/en-us/library/aa378750
  260. #>