Mmraff/net-localgroup

Examples

The following example displays a list of all the local groups on the local server, type:

The following example adds a local group called Exec to the local user accounts database, type:

net localgroup exec /add

The following example adds a local group called Exec to the domain user accounts database, type:

net localgroup exec /add /domain

The following example adds the existing user accounts stevev, ralphr (from the Sales domain), and jennyt to the Exec local group on the local computer, type:

net localgroup exec stevev sales\ralphr jennyt /add

The following example adds the existing user accounts stevev, ralphr, and jennyt to the Exec group of a domain, type:

net localgroup exec stevev ralphr jennyt /add /domain

The following example displays users in the Exec local group, type:

net localgroup exec

The following example adds a comment to the Exec local group record, type:

net localgroup exec /comment:»The executive staff.»

Tracking Local Administrators by Group Policy Objects

We first started diving into GPO enumeration a while ago when Skip Duckwall asked me if it was possible, through PowerView, to enumerate what organizational units a particular Group Policy Globally Unique Identifier (GUID) applied to. The “GPP and PowerView” post demonstrated how this could be done, by tracing a GPP GUID name back to the computers it applies to.

We then tried to take it one step further, and realized it was possible to map what machines a specific user or group has local administrator (or RDP) rights on by correlating GPO, OU, and user membership data. This approach has the advantage of no communication with a target system, as it only queries your primary (or specified) domain controller for the relevant information. I’ll walk through this process step by step and show how some of PowerView’s weaponized functions take care of this for you.

Get-NetGPOGroup is where everything starts. It will enumerate all current GPOs with Get-NetGPO and will parse any GptTmpl.inf files (located at “$GPOPath\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf”) and any Groups.xml files (located at “$GPOPath\MACHINE\Preferences\Groups\Groups.xml”). GptTmpl.inf is used by Group Policy to set ‘Restricted Groups’, i.e. what users are members of specific local groups on machines where the policy is applied. Groups.xml is used by Group Policy Preferences to perform similar task. The results of Get-NetGPOGroup will look something like this:

You can see above that Members contains the security identifiers of users/groups we’re interested in, and the MemberOf field specifies their local group membership (in this case ‘Administrators’, with well known SIDs documented here). If we combine this information with the complete group membership of a target user to identify what GPOs set local group membership for our target user, and then find linked OUs and resulting computers similar to how we enumerated GPP, we can get machines our target can access with only sending traffic to our domain controller.

Find-GPOLocation will do just that, taking a specified -UserName <USER> or -GroupName <GROUP> and returning the set of computers they can access. If a user or group name is not specified, all relationships for the domain will be returned. Also, a different -LocalGroup can be specified (default of ‘Administrators’).

Here’s how it works:

  1. Retrieve the SID for the specified user or group name.
  2. Enumerate all groups the user/group is currently a part of by invoking Get-NetGroup -UserName X which will retrieve membership from the tokenGroups attribute. Use this to build a list of target SIDs of all groups the target is a member of.
  3. Enumerate all GPOs that set ‘Restricted Groups’ or Groups.xml by calling Get-NetGPOGroup.
  4. Matching the target SID list to the queried GPO SID list to enumerate all GPOs the target is effectively applied with.
  5. Enumerate all OUs and sites that any resulting GPOs by linking the GPO GUID with the gplink attribute.
  6. Query for any computers in resulting OUs and return any resulting sites.

There’s also a functional inverse, Find-GPOComputerAdmin, that will return what objects have membership for a specified -LocalGroup on a target system. The -Recurse flag will resolve the membership of any results that are a group themselves.

And just like Get-NetLocalGroup, these functions don’t need elevated access to query this information. However, Find-GPOComputerAdmin will only return domain results, i.e. local user accounts will not be returned.

Examples

The following example displays a list of all the local groups on the local server, type:

The following example adds a local group called Exec to the local user accounts database, type:

net localgroup exec /add

The following example adds a local group called Exec to the domain user accounts database, type:

net localgroup exec /add /domain

The following example adds the existing user accounts stevev, ralphr (from the Sales domain), and jennyt to the Exec local group on the local computer, type:

net localgroup exec stevev sales\ralphr jennyt /add

The following example adds the existing user accounts stevev, ralphr, and jennyt to the Exec group of a domain, type:

net localgroup exec stevev ralphr jennyt /add /domain

The following example displays users in the Exec local group, type:

net localgroup exec

The following example adds a comment to the Exec local group record, type:

net localgroup exec /comment:»The executive staff.»

Открытие и управление локальным пользователем и управлением группами

Версии Windows 10 Pro, Enterprise и т. Д. Предлагают такие программы, как lusrmgr.msc, Netplwiz, и даже userpasswords2 программы, позволяющие управлять пользователями и группами.

Пользователи Windows 10 Home с правами администратора могут использовать интерфейсы командной строки, такие как ЧИСТАЯ ЛОКАЛЬНАЯ ГРУППА и Microsoft.МощностьРакушка.Местныйучетные записи сделать то же самое.

Как использовать Net LocalGroup

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

NET LOCALGROUP 
[groupname ] 
groupname {/ADD  | /DELETE} 
groupname name  {/ADD | /DELETE} 

Когда вы запустите только «Net Localgroup», он отобразит все группы на ПК с Windows 10.

net localgroup <group_name> UserLoginName /add
net localgroup users domainname<username> /add

5]Удалить пользователя из группы

net localgroup <groupname> /delete

PowerShell LocalМодуль учетных записей

PowerShell предлагает модуль LocalAccount, который предоставляет 15 командлетов для управления пользователями и группами Windows. Вот список:

  • Добавить-LocalGroupMember — Добавить пользователя в локальную группу
  • Отключить-LocalUser —Отключить локальную учетную запись пользователя
  • Включить-LocalUser — Включить локальную учетную запись пользователя
  • Get-LocalGroup — Просмотр предпочтений местной группы
  • Get-LocalGroupMember — Просмотр списка всех членов локальной группы
  • Get-LocalUser — Просмотр настроек локальной учетной записи пользователя
  • New-LocalGroup — Создать новую локальную группу
  • New-LocalUser — Создайте новую локальную учетную запись пользователя
  • Удалить-LocalGroup — Удалить локальную группу
  • Удалить-LocalGroupMember — Удалить участника из локальной группы
  • Удалить-LocalUser — Удалить локальную учетную запись пользователя
  • Переименовать-LocalGroup — Переименовать локальную группу
  • Переименовать-LocalUser — Переименовать локальную учетную запись пользователя
  • Set-LocalGroup — Изменить настройки локальной группы
  • Set-LocalUser — Изменить настройки учетной записи локального пользователя

Итак, если вы хотите создать новую локальную группу, выполните следующую команду

New-LocalGroup -Name "TWC"

Чтобы удалить участника из группы, выполните эту команду:

Add-LocalGroupMember -Group 'TWC' –Member 'ashis'

Используя оба ЧИСТАЯ МЕСТНАЯ ГРУППА и Microsoft.МощностьРакушка.Местныйучетные записи интерфейс, вы можете легко управлять пользователями и группами. Эти команды просты в использовании, но если вам нужен программный подход, попробуйте Инструмент Lusrmgr.

Local Groups, Server Targeting, and Domain Trusts

We soon started heavily utilizing Get-NetLocalGroup to target specific machines beyond passing-the-hash with local machine credentials. By enumerating the local administrators on a remote machine, we can pull any domain accounts that can install agents or otherwise triage a target. An example we run often is Get-NetDomainController | Get-NetLocalGroup to see what users can compromise the domain controllers in an environment. One sometimes confusing point is that these results for a domain controller are NOT just the members of the ‘Domain Admins’ group, but rather the members of the Administrators BUILTIN container on the DC. While ‘Domain Admins’ will be a part of the result set, you’ll sometimes find additional groups and users that have local administrative rights on a DC. These make excellent targets for later user hunting.

If you’re on a shorter timeframe pentest, and want to run this functionality on ALL machines in the network, you can execute Invoke-EnumerateLocalAdmin  (with optional -Threads X for threaded functionality). This will perform local admin access enumeration on all computers listed in Active Directory and output everything to a nicely sortable .csv. But be warned: this can be very slow for large environments, and it is definitely not stealthy, as you are touching every machine as quickly as your system will allow.

Another nice side effect of Get-NetLocalGroup output is that you can easily determine if a result is a member of the target machine’s domain, or if the access is operating across a domain trust. The “Domain Trusts: We’re Not Done Yet” post covers the Invoke-EnumerateLocalTrustGroups (now “Invoke-EnumerateLocalAdmin -TrustGroups” in PowerView 2.0) cmdlet, which automates all of this for you. It enumerates local administrative results for all machines in a domain, and returns results that are not members of the target machine or machine’s domain, OR domain groups that have a user outside of the machine’s domain. This is can be useful when hopping between trusts.

Get-NetLocalGroup

For some quick review, Get-NetLocalGroup utilizes the Active Directory Service Interfaces WinNT provider to query the members of a local group (default of ‘Administrators’) from a remote machine. We can pull not just group member names, but whether the member is a group or user, whether the account is disabled, the account’s last login time, the account SID, and more. With the SID we can also determine if the result is a local account/group or a domain account as well. And what’s really cool is that we can query all of this information as an unprivileged domain user context (though you do need a domain authenticated account).

This information is great for determining whether you can pass-the-hash to a remote machine, important in the post KB2871997 world. If the local account with a SID ending in -500 is enabled or a domain account is in the machine’s local administrators, you can still pass-the-hash with those credentials. This is what Get-NetLocalGroup was originally built for, but after operating with it for a while, we’ve started to realize other useful cases for this cmdlet. @sixdub‘s post is a great example of unanticipated advantages of having this functionality in your toolbox.

Also note that the old Get-NetLocalGroups function has been depreciated- if you’d like to list the local groups on a machine, use the -ListGroups option. You can also specify the local group you’re querying for with -GroupName, for example Get-NetLocalGroup -GroupName “Remote Desktop Users” WINDOWS1.testlab.local.

Get-NetLocalGroup accepts NetBIOS names, IPs, and fully qualified host names for targets. There’s also an -API flag, which uses the NetLocalGroupGetMembers API call instead of the WinNT service provider. This returns more limited information, but is significantly faster. The Invoke-EnumerateLocalAdmin function (described below) also accepts this -API flag as well.

Parameters

  • <GroupName>
    Specifies the name of the local group to add, expand, or delete. Used without additional parameters, **net localgroup <**GroupName> displays a list of users or global groups in a local group.

  • /comment:»<Text>»
    Adds a comment for a new or existing group. The comment can contain up to 256 characters. Enclose the text in quotation marks.

  • /domain
    Performs the operation on the primary domain controller of the current domain. Otherwise, the operation is performed on the local computer.

  • <Name>
    Lists one or more user names or group names to add or remove from a local group.

  • /add
    Adds a global group name or user name to a local group. You must first establish an account for users or global groups before you can add it to a local group with this command.

  • /delete
    Removes a group name or user name from a local group.

  • net help <Command>
    Displays help for the specified net command.

Parameters

  • <GroupName>
    Specifies the name of the local group to add, expand, or delete. Used without additional parameters, **net localgroup <**GroupName> displays a list of users or global groups in a local group.

  • /comment:»<Text>»
    Adds a comment for a new or existing group. The comment can contain up to 256 characters. Enclose the text in quotation marks.

  • /domain
    Performs the operation on the primary domain controller of the current domain. Otherwise, the operation is performed on the local computer.

  • <Name>
    Lists one or more user names or group names to add or remove from a local group.

  • /add
    Adds a global group name or user name to a local group. You must first establish an account for users or global groups before you can add it to a local group with this command.

  • /delete
    Removes a group name or user name from a local group.

  • net help <Command>
    Displays help for the specified net command.

Remarks

  • Using /domain

    /domain applies only to computers that are members of a domain. By default, server computers perform operations on the primary domain controller.

  • Using Name

    Separate multiple entries with a space. Names can be local users, users on other domains, or global groups, but not other local groups. If a user is from another domain, preface the user name with the domain name (for example, Sales\Ralphr).

  • Grouping users

    Use net localgroup to group users who use the computer or network in the same or similar ways. When you assign rights to a local group, each member of the local group automatically has the same rights.

ManageEngine Desktop Central ^

Yet another option is to use a desktop management tool such as ManageEngine Desktop Central. Of course, if you just want to add one user to a group, you wouldn’t deploy such a tool. However, if you often have similar remote management tasks to do—in particular, if you have to automate such tasks for many computers—you are better off with a GUI tool than with command-line tools or PowerShell; you can automate the task for any number of machines (including those that are currently offline) with just a few clicks and without the need to write a longwinded script. You will hardly find a remote management task that you can’t automate with Desktop Central.

ManageEngine Desktop Central

Desktop Central requires you to install an agent on the remote machine, which you can easily do from the Desktop Central console. Once the agent is running on the remote machine, you have to add a Group Management Configuration. Under Step 2 — Define Configuration, you click Modify Group and then enter Administrators in the Group Name field. Under Add Members, you select Domain User and then enter the user name. Finally, in Step 3 – Define Target, you add the computer name.

Add user to the local Administrators group with Desktop Central

You also have to configure Windows Firewall so Desktop Central can work properly. You can find more information about the ports you have to open .

The downside of using a desktop management tool is, of course, that you have to buy it. Desktop Central is free for 25 devices.

Get-NetLocalGroup – New Developments

We started using this function more and more to target specific servers beyond just domain controllers. One of the issues we ran into is that any domain results for a server are preserved in NT4 “shortname” domain syntax, which can sometimes complicate later enumeration. This was recently fixed by adapting some of Bill Stewart’s code that utilizes the NameTranslate COM object to transform domain names between various formats (in our case, NT4 to canonical). This gives us nice new results like the screenshot at the top of the post.

With the full canonical domain name, we can also now easily recursively resolve any domain group results down to their user members. The new -Recurse flag for Get-NetLocalGroup does just this, returning an effective set of domain user/groups that can access a particular server with administrative rights:

This has greatly sped up user hunting engagements with complex, nested group relationships. This functionality was also recently added to Invoke-UserHunter and Invoke-UserHunter -Stealth (formerly Invoke-StealthUserHunter), with the -TargetServer <SERVER> argument. This will perform a recursive Get-NetLocalGroup <SERVER> -Recurse enumeration of a target server, and hunt for where any of these users are logged in on the network:

Remarks

  • Using /domain

    /domain applies only to computers that are members of a domain. By default, server computers perform operations on the primary domain controller.

  • Using Name

    Separate multiple entries with a space. Names can be local users, users on other domains, or global groups, but not other local groups. If a user is from another domain, preface the user name with the domain name (for example, Sales\Ralphr).

  • Grouping users

    Use net localgroup to group users who use the computer or network in the same or similar ways. When you assign rights to a local group, each member of the local group automatically has the same rights.

Комментарии

При вызове этой функции на контроллере домена, работающем под управлением Active Directory, доступ разрешен или запрещен на основе списка управления доступом (ACL) для защищаемого объекта. Список ACL по умолчанию позволяет всем пользователям, прошедшим проверку подлинности, и членам группы «Доступ, совместимый с Пред Windows 2000», просматривать сведения. При вызове этой функции на рядовом сервере или рабочей станции все пользователи, прошедшие проверку подлинности, могут просматривать сведения. Сведения об анонимном доступе и ограничении анонимного доступа на этих платформах см. в разделе «Требования к безопасности» для функций управления сетями. Дополнительные сведения о списках управления доступом, ACE и маркерах доступа см. в разделе контроль доступа Model.

Функция возвращает только сведения, к которым вызывающий объект имеет доступ на чтение. Вызывающий объект должен иметь доступ к объекту domain contents и перечислить весь доступ к домену SAM на объекте СЕРВЕРА SAM, расположенном в контейнере System.

Чтобы определить точное общее количество локальных групп, необходимо перечислить все дерево, которое может быть дорогостоящей операцией. Чтобы перечислить все дерево, используйте параметр resumehandle для продолжения перечисления для последовательных вызовов и используйте параметр entriesread для накопления общего числа локальных групп. Если приложение взаимодействует с контроллером домена, рекомендуется использовать поставщик LDAP ADSI для более эффективного получения данных этого типа. Поставщик LDAP ADSI реализует набор объектов ADSI, поддерживающих различные интерфейсы ADSI. Дополнительные сведения см. в разделе «Поставщики услуг ADSI».

Имена учетных записей пользователей ограничены 20 символами, а имена групп ограничены 256 символами. Кроме того, имена учетных записей не могут быть прерваны точкой, и они не могут содержать запятые или любые из следующих печатных символов: «, /, , :, |, <, , + >, =, ;, ?, *. Имена также не могут содержать символы в диапазоне 1–31, которые не могут быть отпечатаны.

При программировании для Active Directory можно вызвать определенные методы интерфейса службы Active Directory (ADSI) для достижения тех же функций, которые можно достичь, вызвав функции локальной группы управления сетью. Дополнительные сведения см. в разделе IADsGroup.

PowerShell ^

Of course, you can also use PowerShell to accomplish the task. The little script below demonstrates how you can add a user to the local Administrators group with PowerShell:

$DomainName = Read-Host "Domain name:"
$ComputerName = Read-Host "Computer name:"
$UserName = Read-Host "User name:"
$AdminGroup = "WinNT://$ComputerName/Administrators,group"
$User = "WinNT://$DomainName/$UserName,user"
$AdminGroup.Add($User.Path)

The first three lines are just for prompting you to input the domain, computer, and user names. In line 4, the script creates the reference object for the local Administrators group of the remote computer using the type adapter. Line 5 creates the corresponding reference to the user, and the last line adds the user to the Administrators group.

For this method to work, we need another firewall setting as with the Computer Management solution. You have to enable the Group Policy Allow inbound file and printer sharing exception. The policy is also located in Computer Configuration > Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile.

Allow inbound file and printer sharing exception

Note that this policy is also sufficient for the PsExec method described above.

If you want to add a user to multiple computers, you should check out Jaap Brasser’s PowerShell script. The script can load a list of computers from a text file and allows you to work with parameters on the PowerShell console.

Computer Management ^

The easier way to add a user to the local Administrators group is to use the Computer Management app. You can connect to the remote computer via Remote Desktop, press SHIFT-R, and then enter compmgmt.msc. However, a faster way is to launch Computer Management on your own computer and establish a remote connection to the user’s computer. To do so, right-click the Computer Management icon, select Connect to another computer, and then enter the computer name of the machine you want to manage.

Computer Management — Connect to another computer

Note: You can also right-click the corresponding computer name and then select Manage in Active Directory Users and Computers.

If you are logged in to an Active Directory domain, and if you have sufficient privileges to manage the remote machine, the connection should be established without the need to provide credentials. You can then navigate to Local Users and Groups and add the user to the Administrators group.

Add user to the local Administrators group in Computer Management

A problem with this method is that it will only work if the Windows Firewall on the remote desktop is configured to allow remote administration. If not, you will get an error message that the computer cannot be connected.

Hence, if you want to manage remote computers with Computer Management, you have to enable the Group Policy setting Allow inbound remote administration exception for the Windows Firewall. You can find the policy in Computer Configuration > Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile.

Allow inbound remote administration exception

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Работатека
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: