Windows disable local users

Windows: Запретить сетевой доступ под локальным учетным записям

Использование локальных учетных записей (в том числе локального администратора) для доступа по сети в средах Active Directory нежелательно по ряду причин. Зачастую на многих компьютерах используются одинаковые имя и пароль локального администратора, что может поставить под угрозу множество систем при компрометации одного компьютера (угроза атаки Pass-the-hash). Кроме того, доступ под локальными учетными записями по сети трудно персонифицировать и централизованно отследить, т.к. подобные события не регистрируются на контроллерах домена AD.

Для снижения рисков, администраторы могут изменить имя стандартной локальной учетной записи администратора Windows (Administrator). Для регулярной смены пароля локального администратора на всех компьютерах в домене можно использовать MS LAPS (Local Administrator Password Solution). Но этими решениями не удастся решить проблему ограничения сетевого доступа под локальными учетными записями, т.к. на компьютерах может быть больше одной локальной учетки.

Ограничить сетевой доступ для локальных учетных записей можно с помощью политики Deny access to this computer from the network. Но проблема в том, что в данной политике придется явно перечислить все имена учетных записей, которым нужно запретить сетевой доступ к компьютеру.

В Windows 8.1 and Windows Server 2012 R2 появилась две новые группы безопасности (Well-known group) с известными SID. Одна включает в себя всех локальных пользователей, а вторая всех локальных администраторов.

S-1-5-113 NT AUTHORITY\Local account Все локальные учетная запись
S-1-5-114 NT AUTHORITY\Local account and member of Administrators group Все локальные учетные записи с правами администратора

Теперь для ограничения доступа локальным учетным записям не нужно перечислять все возможные варианты SID локальных учёток, а использовать их общий SID.

Данные группы добавляются в токен доступа пользователя при входе в систему под локальной учетной записью.

Чтобы убедится, что в Windows 10/Windows Server 2016 локальной учетной записи присвоены две новый группы NT AUTHORITY\Local account (SID S-1-5-113) и NT AUTHORITY\Local account and member of Administrators group (SID S-1-5-114) , выполните команду:

Проверить, имеются ли данные группы безопасности в вашей Windows можно по их SID так:

$objSID = New-Object System.Security.Principal.SecurityIdentifier («S-1-5-113»)
$objAccount = $objSID.Translate([System.Security.Principal.NTAccount])
$objAccount.Value
Если скрипт возвращает NT Authority\Local account, значит данная локальная группа (с этим SID) имеется.

Чтобы запретить сетевой доступ под локальным учетным записями, с этими SID-ами в токене, можно воспользоваться политиками из раздела GPO Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment.

Запрет на вход через RDP для локальных пользователей и администратора

Политика Deny log on through Remote Desktop Services (Запретить вход в систему через службу с удаленного рабочего стола) позволяет указать пользователей и группы, которым явно запрещен удаленный вход на компьютер через RDP. Вы можете запретить RDP доступ к компьютеру для локальных или доменных учетных записей.

Если вы хотите запретить RDP подключения только локальных пользователей (в том числе локальных администраторов), откройте локальной редактор GPO gpedit.msc (если вы хотите применить эти настройка на компьютерах в домене AD, используйте редактор доменных политик – gpmc.msc ). Перейдите в указанную выше секцию GPO и отредактируйте политику Deny log on through Remote Desktop Services.

Добавьте в политику встроенные локальные группу безопасности Local account and member of Administrators group и Local account. Обновите настройки локальных политик с помощью команды: gpupdate /force.

Теперь, если вы попытаетесь подключиться к компьютеру по RDP, появится ошибка:

Читайте также:  How to check the files in linux

Запрет сетевого доступа к компьютеру по сети

Вы можете запретить сетевой доступ к компьютеру под локальными учетными данными с помощью политики Deny access to this computer from the network (Отказать в доступе к этому компьютеру из сети).

Добавьте в политику Deny access to this computer from the network локальные группы Local account и Local account and member of Administrators group. Также стоит всегда запрещать анонимный доступ и доступ под гостевым аккаунтом.

После применения политики вы не сможете удаленно подключиться к этому компьютеру по сети под любой локальной учетной записью. При попытке подключиться к сетевой папке или подключить сетевой диск с этого компьютера под локальной учетной записью, появится ошибка:

При попытке установить RDP сессию под учетной записью локального администратора (.\administrator) появится сообщение об ошибке.

Запретить локальный вход в Windows

С помощью политики Deny log on locally (Запретить локальных вход) вы можете запретить и интерактивный вход на компьютер/сервер под локальными учетными записями. Перейдите в секцию GPO User Rights Assignment, отредактируйте политику Deny log on locally. Добавьте в нее нужную локальную группу безопасности.

Теперь, если пользователь или администратор попытается авторизоваться на компьютере под локальной учетной записью, появится сообщение.

Таким образом, вы можете ограничить доступ под локальными учетными записями на компьютеры и сервера домена, увеличить защищенность корпоративной сети.

Use PowerShell to Enable or Disable a Local User Account

November 22nd, 2010

Summary: Microsoft Scripting Guy Ed Wilson shows how to use Windows PowerShell to enable or to disable a local user account.

Hey, Scripting Guy! I need to enable local user accounts on my Windows Server 2008 servers. I have to use Windows PowerShell 1.0 because we are not going to upgrade to Windows Server 2008 R2 until April of next year. Because the end of the year is rapidly approaching, we are going into IT lockdown and will not make any changes until after the end of January. At that time, we will begin evaluating our new projects, and server upgrades are on tap for Q2 next year. I know you have been writing about Windows PowerShell 2.0 a lot here lately, but I am wondering if you can do a retro thing for me?

Hello GB, Microsoft Scripting Guy Ed Wilson here. It is interesting that you mention Windows PowerShell 1.0. I have actually run across two other companies like yours this week, GB. I decided to take a look at the Windows PowerShell Scripting Guide book that I wrote for Microsoft Press, and excerpt a portion of one of the chapters in that most excellent book.

Portions of today’s post are excerpted from Ed Wilson’s Windows PowerShell Scripting Guide, Microsoft Press, 2008.

Unlike domain accounts, it is not very often that we will create a disabled user account. Local user accounts are primarily created to provide access to local resources, or for local service accounts. They are not often used, except in workgroup settings, for actual logon user accounts. This does not mean they are obsolete. To the contrary, with the enhanced peer-to-peer capabilities of Windows Vista and above, as well as the new features of Windows Server 2008 and Windows Server 2008 R2, local user accounts are even more important today than they were even five years ago.

It is also true, that when Windows Vista and above are installed the local administrator account is disabled. This is seen in the figure below. You may want to enable that account to perform certain management tasks.

Читайте также:  Open rar files with windows

To enable the admin account, you can use the EnableDisableUser.ps1 script to enable the account, perform the requisite activities, and then use the EnableDisableUser.ps1 script to disable the local admin account. You can also use this script to change the local admin password as well. To do this, you would just “pretend” you were going to enable the local admin account, and run the script with enable option specified.

In the EnableDisableUser.ps1 script, we begin with the param statement. We specify five parameters. The first one is -computer, which determines where the script will execute. By default, the -computer parameter is set to run on the local machine. The -a parameter determines the action to perform when the script is run. The -user parameter and -password parameter are used for working with the local user. The -help parameter will display help. This line of code is seen here.

param($computer=”localhost”, $a, $user, $password, $help)

The funhelp function displays help when the script is run with the -help parameter specified. The funhelp function is similar to the other ones that I have used in other articles. It uses a here-string, and stores the information in the $helpText variable. Once the description, parameters, and syntax are detailed, the contents of the $helpText variable are displayed and the script exits. This function is seen here.

Enables or Disables a local user on either a local or remote machine.

-computer Specifies the name of the computer upon which to run the script

-a(ction) Action to perform

-user Name of user to create

-help prints help file

Generates an error. You must supply a user name

EnableDisableUser.ps1 -computer MunichServer -user myUser

-password Passw0rd^&! -a e

Enables a local user called myUser on a computer named MunichServer

with a password of Passw0rd^&!

EnableDisableUser.ps1 -user myUser -a d

Disables a local user called myUser on the local machine

Displays the help topic for the script

Following the funhelp function, we declare two variables. These variables contain ADS_USER_FLAG_ENUM enumeration values which were retrieved from the Windows SDK. These values will be used to either enable a user, or to disable the user account.

While the ADS_USER_FLAG_ENUM enumeration values are documented in the Windows SDK, their use as described here are not documented. Since we do not have direct support for the IadsUser interface in Windows PowerShell this means we do not have access to the accountdisabled Boolean property that was available in VBScript. This makes the EnableDisableUser.ps1 script an important example as “re-branded” VBScripts simply will not work using the WinNT provider.

After we define the two variables, now we test to see if we need to display the help string by checking for the presence of the $help variable. To be honest, we could have moved this line up two spaces, and checked prior to setting the $EnableUser and the $DisableUser variables as it makes no difference in performance of the script, we decided to define these variables earlier in the script. We now use code to see if help needs to be displayed. It looks for the presence of the $help variable, prints out a string, and calls the funhelp function if the $help variable is found.

Now we check to see if the $user variable is present. If the $user variable is not present, then we use the throw statement to generate an error.

Читайте также:  Запуск windows по сети pxe

The throw statement is not documented in the Windows PowerShell documentation, although it shows up in one piece of sample syntax (when talking about code signing). It is easier to use than the syntax: if(xxx) < xxx ; exit >. The disadvantage is that the output is not very pretty.

In the error text we mention that a user name is required, and we print out the syntax for obtaining help. This section of the script is seen here.

if(!$user)
<
$(Throw ‘A value for $user is required.
Try this: EnableDisableUser.ps1 -help ?’)
>

Once we have determined that the user name has been supplied, then we use the [ADSI] type accelerator and the WinNT Active Directory Services Interface (ADSI) provider to connect to the local computer SAM account database where we retrieve the user object. This line of code is seen here.

The switch statement is used to evaluate the value of the $a variable. The $a variable is used to specify the action we want the script to perform. If we are going to enable the user account, we will need to set a password. The letter “e” (for enable) is supplied for the -a parameter to enable the user account. We use the if statement to look for a password contained in the $password parameter. If the password is not present, then we once again throw an exception, and point the user back to the help file. If however, the password is present, then we use the setpassword method to set the password on the user object. We change the description to “enabled account” and then supply the appropriate value for the userflags property. Once we have done all that, we call the setinfo() method to commit the changes back to the SAM account database. This section of the switch statement is seen here.

$(Throw ‘a value for $password is required.

Try this: EnableDisableUser.ps1 -help ?’)

$objUser.description = “Enabled Account”

If we want to disable an user account, then all we really need to do is set the appropriate value for the userflags, and call the setinfo() method. While we are at it, we change the user description property to “disabled account”. We only perform this action if the value of “d” is supplied for the -a parameter. This section of code is seen here.

“d” <
$objUser.description = “Disabled Account”
$objUser.userflags = $DisableUser
$objUser.setinfo()
>

If a value other than “e” or “d” is supplied for the -a parameter, we will go to the default switch. For this script, we decided to print out a string that points the user to the help file. This section of the code is seen here.

DEFAULT
<
“You must supply a value for the action.
Try this: EnableDisableUser.ps1 -help ?”
>
>

The completed EnableDisableUser.ps1 script is seen here.

EnableDisableUser.ps1

param($computer=”localhost”, $a, $user, $password, $help)

Enables or Disables a local user on either a local or remote machine.

-computer Specifies the name of the computer upon which to run the script

-a(ction) Action to perform

-user Name of user to create

-help prints help file

Generates an error. You must supply a user name

EnableDisableUser.ps1 -computer MunichServer -user myUser

-password Passw0rd^&! -a e

Enables a local user called myUser on a computer named MunichServer

with a password of Passw0rd^&!

EnableDisableUser.ps1 -user myUser -a d

Disables a local user called myUser on the local machine

Оцените статью