Windows domain enumeration команда

Enumerating Domain Controllers

In earlier versions of Windows, an application could only obtain a single domain controller in a domain by calling DsGetDcName. There was no way to predict which domain controller would be retrieved or to obtain a list of the domain controllers. Windows enables an application to enumerate the domain controllers in a domain by using the DsGetDcOpen, DsGetDcNext, and DsGetDcClose functions.

To enumerate a domain controller, call DsGetDcOpen. This function takes parameters that define the domain to enumerate and other enumeration options. DsGetDcOpen provides a domain enumeration context handle that is used to identify the enumeration operation when DsGetDcNext and DsGetDcClose are called.

The DsGetDcNext function is called with the domain enumeration context handle to retrieve the next domain controller in the enumeration. The first time this function is called, the first domain controller in the enumeration is retrieved. The second time this function is called, the second domain controller in the enumeration is retrieved. This process is repeated until DsGetDcNext returns ERROR_NO_MORE_ITEMS, that indicates the end of the enumeration.

The DsGetDcNext function will enumerate the domain controllers in two groups. The first group contains the domain controllers that cover the site of the computer where the function is executed and the second group contains the domain controllers that do not cover the site of the computer where the function is executed. If the DS_NOTIFY_AFTER_SITE_RECORDS flag is specified in the OptionFlags parameter in DsGetDcOpen, the DsGetDcNext function will return ERROR_FILEMARK_DETECTED after all of the site-specific domain controllers have been retrieved. DsGetDcNext will then begin enumerating the second group, which contains all domain controllers in the domain, including the site-specific domain controllers contained in the first group.

Domain controllers that handle the site of the computer where the function is executed are enumerated first followed by the domain controllers that do not cover the site of the computer where the function is executed. A domain controller is said to cover a site if the domain controller is configured to reside in that site or if the domain controller resides in a site that is nearest to the site in question in terms of the configured inter-site link cost. If there are any domain controllers in both the group of domain controllers that cover and the group of domain controllers that do not cover the computer site, domain controllers are returned within the group in order of their configured priorities and weights that are specified in DNS. Domain controllers that have lower numeric priority are returned within a group first. If within a site-related group there is a subgroup of several domain controllers with the same priority, domain controllers are returned in a weighted random order where domain controllers with higher weight have more probability to be returned first. The sites, priorities, and weights are configured by the domain administrator to achieve effective performance and load balancing among multiple domain controllers available in the domain. Because of this, applications that use the DsGetDcOpen/DsGetDcNext/DsGetDcClose functions automatically take advantage of these optimizations.

Читайте также:  Выполнить синхронизацию времени windows

When the enumeration is complete or is no longer required, the enumeration must be closed by calling DsGetDcClose with the domain enumeration context handle.

To reset the enumeration, it is necessary to close the current enumeration by calling DsGetDcClose and then reopen the enumeration by calling DsGetDcOpen again.

Example

The following code example shows how to use these functions to enumerate the domain controllers in the local domain.

its-a-feature / Domain Enumeration Commands

Domain: TEST.local
User Enumeration:
Windows:
net user
net user /domain
net user [username]
net user [username] /domain
wmic useraccount
Mac:
dscl . ls /Users
dscl . read /Users/[username]
dscl «/Active Directory/TEST/All Domains» ls /Users
dscl «/Active Directory/TEST/All Domains» read /Users/[username]
dscacheutil -q user
LDAP:
ldapsearch -H ldap://test.local -b DC=test,DC=local «(objectclass=user)»
ldapsearch -H ldap://test.local -b DC=test,DC=local «(&(objectclass=user)(name=[username]))»
Computer Enumeration:
Windows:
net group «Domain Computers» /domain
net group «Domain Controllers» /domain
Mac:
dscl «/Active Directory/TEST/All Domains» ls /Computers
dscl «/Active Directory/TEST/All Domains» read «/Computers/[compname]$»
LDAP:
ldapsearch -H ldap://test.local -b DC=test,DC=local «(objectclass=computer)»
ldapsearch -H ldap://test.local -b DC=test,DC=local «(&(objectclass=computer)(name=[computername]))»
Group Enumeration:
Windows:
net localgroup
net group /domain
net localgroup [groupname]
net group [groupname] /domain
wmic group
Mac:
dscl . ls /Groups
dscl . read «/Groups/[groupname]»
dscl «/Active Directory/TEST/All Domains» ls /Groups
dscl «/Active Directory/TEST/All Domains» read «/Groups/[groupname]»
LDAP:
ldapsearch -H ldap://test.local -b DC=test,DC=local «(objectclass=group)»
ldapsearch -H ldap://test.local -b DC=test,DC=local «(&(objectclass=group)(name=[groupname]))»
ldapsearch -H ldap://test.local -b DC=test,DC=local «(&(objectclass=group)(name=*admin*))»
Domain Information:
Windows:
wmic ntdomain
ipconfig /all
Mac:
dsconfigad -show
LDAP:
ldapsearch -H ldap://test.local -b DC=test,DC=local «(objectclass=trusteddomain)»

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Заметки сисадмина о интересных вещах из мира IT, инструкции и рецензии. Настраиваем Компьютеры/Сервера/1С/SIP-телефонию в Москве

Переименование домена Windows 2008

Недавно я уже публиковал статью, посвященную переимнованию контроллера домена Windows Server 2008. Сегодня я собираюсь опубликовать связанную, но совершенно другую задачу – переимнование домена. Переименование домена это процедура, которую выполняют очень редко в реальном окружении, если вообще когда либо выполняют. Однако например в тестовом окружении это бывает полезно, да и просто для широты кругозора это не помешает знать.

У Microsoft имеется много информации в документации, посвященной переименованию домена и я рекомендую использовать её(ссылка будет в конце статьи), особенно если дело касается домена в промышленной среде. Однако шаги ниже впринципе вполне полностью описывают процедуру переименования и достаточны для тестовых целей. Для начала опишем первоначальные требования к переименованию домена в среде с одним доменом в лесу:

  • У вас должны быть права Enterprise Administrator.
  • Домен должен функционировать в нормальном режиме, не должно быть ни каких ошибок.
  • Функциональный уровень леса должен быть Windows Server 2003 или 2008, и все контроллеры домена должны быть под управлением как минимум Server 2003.
  • Должна существовать DNS зона для нового домена.
  • На рядовой сервер необходимо скопировать утилиты Rendom и Gpfixup для выполнения операции переименование. Данная операция не может быть выполнена с контроллера домена.
  • Дополнительные требования выдвигаются к DFS, перемещаемым профилям, центру сертификации и серверу Exchange. По этим вопросам посмотрите ссылку на документацию на TechNet, которая будет в конце статьи.
Читайте также:  Partition manager linux swap

Переименование домена выполняется утилитой Rendom, которая устанавливается вместе с Active Directory при запуске dcpromo. Далее выполняем следующие шаги.

  1. Выполните команду“rendom /list” для генерации файла Domainlist.xml, содержащего текущую конфигурацию леса.
  2. Отредактируйте полученный файл, заменив значения полей и на новое имя домена.
  3. Выполните команду“rendom /showforest” для отображения потенциальный изменений. Этот шаг не делает никаких реальных изменений.
  4. Выполните команду “rendom /upload” для загрузки инструкции переименования на контроллер домена с ролью domain naming operations master. Данная инструкция будет реплицирована на все другие контроллеры в лесу. После репликации на все контроллеры инструкция будет готова к применению. Вы можете ускорить репликацию запустив команду “repadmin /syncall”.
  5. Выполните команду “rendom /prepare” для проверки готовности всех контроллеров домена в лесу к процедуре переименования. Все контроллеры должны сообщить о готовности и не должно быть никаких ошибок.
  6. Выполните команду “rendom /do” для проверки готовности всех контроллеров, затем будет запущена процедура переименования для каждого контроллера. На период выполнения будет прерывания работы домена. После окончания процедуры контроллеры будут перезагружены. Если в период выполнения процедуры произойдет ошибка будет выполнен откат изменений. Поэтому любой контроллер домена, который завершил процедуру переименования с ошибкой должен быть понижен до рядового сервера.
  7. Выполните команду “gpfixup” для обновления всех ссылок на групповые политики.
  8. Дважды перегрузите все клиентские компьютеры и рядовые сервера для получения нового доменного имени. Так как при процедуре переименования GUID домена остается старый, членство в домене не затрагивается. DNS суффикс на клиентских машинах будет обновлен автоматически если установлена опция “Change primary DNS suffix when domain membership changes”.
  9. Выполните команду “rendom /clean” для удаления ссылок на устаревшее имя домена из Active Directory.
  10. Выполните команду “rendom /end” для прекращения заморозки конфигурации леса и разрешения дальнейших изменений.

Если у вас проявились какие либо проблемы с определением клиентскими машинами нового имени домена то вы можете удалить их с помощью команды “netdom remove /Domain: /Force”, затем перегрузить и присоединить к новому домену. После того как переименование завершено, нам остается сделать только одно последнее действие. DNS суффикс контроллера домена не был изменен в ходе процедуры и нам необходимо сделать это вручную.

Для дальнейшего изучения публикую обещанную ссылку на документацию TechNet

Windows domain enumeration команда

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I have been configuring group policy for a test environment I have been designing to improve my Windows Server security skills, and I have stumbled upon a vulnerability in my configuration. I am using Windows Server 2012 R2, all client machines are running Windows 10 Pro and above.

The users in my domain are able to use the «net user» command and can enumerate domain users, groups and pull up detailed information regarding any user on the domain. Thankfully, unprivileged users are not able to change another user’s password using the «net user *» command, as access is denied.

Читайте также:  Realtek audio program windows 10

I would like to restrict the use of administrative commands for unprivileged users, but not disable access to the command line. Is there a way to harden or secure the use of certain commands? I would also like to do the same for PowerShell.

Below are examples of my concerns with the net user command, using an unprivileged user account:

Example 1:
net user /domain (Enumerate all users on the domain)

Example 2:
net user /domain (To pull more detailed information for a specific domain user)

Example 3:
net user /domain * (Changes a domain user’s password, with the correct permissions)

xorrior / wmic_cmds.txt

Host Enumeration:
— OS Specifics —
wmic os LIST Full (* To obtain the OS Name, use the «caption» property)
wmic computersystem LIST full
— Anti-Virus —
wmic /namespace:\\root\securitycenter2 path antivirusproduct
— Peripherals —
wmic path Win32_PnPdevice
— Installed Updates —
wmic qfe list brief
— Directory Listing and File Search —
wmic DATAFILE where «path=’\\Users\\test\\Documents\\'» GET Name,readable,size
wmic DATAFILE where «drive=’C:’ AND Name like ‘%password%'» GET Name,readable,size /VALUE
— Local User Accounts —
wmic USERACCOUNT Get Domain,Name,Sid
Domain Enumeration:
— Domain and DC Info —
wmic NTDOMAIN GET DomainControllerAddress,DomainName,Roles /VALUE
— Domain User Info —
wmic /NAMESPACE:\\root\directory\ldap PATH ds_user where «ds_samaccountname=’testAccount'» GET
— List All Users —
wmic /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_samaccountname
— List All Groups —
wmic /NAMESPACE:\\root\directory\ldap PATH ds_group GET ds_samaccountname
— Members of A Group —
wmic /NAMESPACE:\\root\directory\ldap PATH ds_group where «ds_samaccountname=’Domain Admins'» Get ds_member /Value
wmic path win32_groupuser where (groupcomponent=»win32_group.name=»domain admins»,domain=»YOURDOMAINHERE»»)
— List All Computers —
wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_samaccountname
OR
wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_dnshostname
Misc:
— Execute Remote Command —
wmic process call create «cmd.exe /c calc.exe»
— Enable Remote Desktop —
wmic rdtoggle where AllowTSConnections=»0″ call SetAllowTSConnections «1»
OR
wmic /node:remotehost path Win32_TerminalServiceSetting where AllowTSConnections=»0″ call SetAllowTSConnections «1»

This comment has been minimized.

Copy link Quote reply

vysecurity commented Oct 16, 2017

Should be qfe list brief

This comment has been minimized.

Copy link Quote reply

DanMcInerney commented Jul 13, 2018 •

Domain user information results in «invalid query» with valid user. Need something after GET, like /value.

This comment has been minimized.

Copy link Quote reply

DanMcInerney commented Jul 13, 2018 •

Also should be noted if you’re using wmic for getting domain group membership, you’re going to get only the LDAP results which include the CN, but you’re not going to be returned the actual Windows username. I’m trying to figure out how to do that now. I’ll edit this post if I figure it out.

Got it:
wmic path win32_groupuser where (groupcomponent=»win32_group.name=»domain admins»,domain=»YOURDOMAINHERE»»)

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

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