# Az - Service Bus Privesc

{{#include ../../../banners/hacktricks-training.md}}

## Service Bus

Vir meer inligting, kyk:

{{#ref}}
../az-services/az-servicebus.md
{{#endref}}

### Microsoft.ServiceBus/namespaces/authorizationrules/listKeys/action OF Microsoft.ServiceBus/namespaces/authorizationrules/regenerateKeys/action

Hierdie toestemmings laat jou toe om die sleutels vir plaaslike magtigingsreëls binne 'n Service Bus naamruimte te verkry of te hergenerer. Deur hierdie sleutels te gebruik, is dit moontlik om as die Service Bus naamruimte te autentiseer, wat jou in staat stel om boodskappe na enige wachtrij of onderwerp te stuur, boodskappe van enige wachtrij of subskripsie te ontvang, of moontlik met die stelsel te kommunikeer op maniere wat operasies kan ontwrig, geldige gebruikers kan naboots, of kwaadwillige data in die boodskapwerkvloei kan inspuit.

Let daarop dat die **`RootManageSharedAccessKey` reël standaard volle beheer** oor die Service Bus naamruimte het en dit deur die `az` cli gebruik word, egter kan daar ander reëls met ander sleutelwaardes bestaan.
```bash
# List keys
az servicebus namespace authorization-rule keys list --resource-group <res-group> --namespace-name <namespace-name> --authorization-rule-name RootManageSharedAccessKey [--authorization-rule-name RootManageSharedAccessKey]

# Regenerate keys
az servicebus namespace authorization-rule keys renew --key [PrimaryKey|SecondaryKey] --resource-group <res-group> --namespace-name <namespace-name> [--authorization-rule-name RootManageSharedAccessKey]
```
### Microsoft.ServiceBus/namespaces/AuthorizationRules/write

Met hierdie toestemming is dit moontlik om 'n **nuwe magtigingsreël** te **skep** met alle toestemmings en sy eie sleutels met:
```bash
az servicebus namespace authorization-rule create --authorization-rule-name "myRule" --namespace-name mynamespacespdemo --resource-group Resource_Group_1 --rights Manage Listen Send
```
>[!WARNING]
>Hierdie opdrag antwoord nie met die sleutels nie, so jy moet dit met die vorige opdragte (en toestemmings) kry om voorregte te verhoog.

Boonop, met daardie opdrag (en `Microsoft.ServiceBus/namespaces/authorizationRules/read`) as jy hierdie aksie deur die Azure CLI uitvoer, is dit moontlik om 'n bestaande magtigingsreël op te dateer en dit meer toestemmings te gee (in die geval dit tekortkom) met die volgende opdrag:
```bash
az servicebus namespace authorization-rule update \
--resource-group <MyResourceGroup> \
--namespace-name <MyNamespace> \
--name RootManageSharedAccessKey \
--rights Manage Listen Send
```
### Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/ListKeys/action OF Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/regenerateKeys/action

Spesifieke onderwerpe en rye binne 'n Service Bus-namespace kan hul eie magtigingsreëls hê, wat gebruik kan word om toegang tot die entiteit te beheer. Deur hierdie toestemmings te hê, kan jy **die sleutels vir hierdie plaaslike magtigingsreëls onttrek of hernu**, wat jou in staat stel om as die entiteit te verifieer en moontlik boodskappe te stuur of te ontvang, intekeninge te bestuur, of met die stelsel te kommunikeer op maniere wat operasies kan ontwrig, geldige gebruikers kan naboots, of kwaadwillige data in die boodskapwerkvloei kan inspuit.
```bash
# List keys (topics)
az servicebus topic authorization-rule keys list --resource-group <res-group> --namespace-name <namespace-name> --topic-name <topic-name> --name <auth-rule-name>

# Regenerate keys (topics)
az servicebus topic authorization-rule keys renew --key [PrimaryKey|SecondaryKey] --resource-group <res-group> --namespace-name <namespace-name> --topic-name <topic-name> --name <auth-rule-name>

# List keys (queues)
az servicebus queue authorization-rule keys list --resource-group <res-group> --namespace-name <namespace-name> --queue-name <queue-name> --name <auth-rule-name>

# Regenerate keys (queues)
az servicebus queue authorization-rule keys renew --key [PrimaryKey|SecondaryKey] --resource-group <res-group> --namespace-name <namespace-name> --queue-name <queue-name> --name <auth-rule-name>
```
### Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/write

Met hierdie toestemming is dit moontlik om 'n **nuwe magtigingsreël** te **skep** met alle toestemmings en sy eie sleutels met:
```bash
# In a topic
az servicebus topic authorization-rule create --resource-group <res-group> --namespace-name <namespace-name> --topic-name <topic-name> --name <auth-rule-name> --rights Manage Listen Send

# In a queue
az servicebus queue authorization-rule create --resource-group <res-group> --namespace-name <namespace-name> --queue-name <queue-name> --name <auth-rule-name> --rights Manage Listen Send
```
>[!WARNING]
>Hierdie opdrag antwoord nie met die sleutels nie, so jy moet dit met die vorige opdragte (en toestemmings) kry om voorregte te verhoog.

Boonop, met daardie opdrag (en `Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/read`) as jy hierdie aksie deur die Azure CLI uitvoer, is dit moontlik om 'n bestaande magtigingsreël op te dateer en dit meer toestemmings te gee (in die geval dit tekortkom) met die volgende opdrag:
```bash
# In a topic
az servicebus topic authorization-rule update --resource-group <res-group> --namespace-name <namespace-name> --topic-name <topic-name> --name <auth-rule-name> --rights Manage Listen Send

# In a queue
az servicebus queue authorization-rule update --resource-group <res-group> --namespace-name <namespace-name> --queue-name <queue-name> --name <auth-rule-name> --rights Manage Listen Send
```
### Microsoft.ServiceBus/namespaces/write (& Microsoft.ServiceBus/namespaces/read if az cli is used)

Met hierdie toestemmings **kan 'n aanvaller "lokale outentisering" heraktiveer** met die volgende opdrag en daarom sal al die sleutels van gedeelde beleide werk.
```bash
az servicebus namespace update --disable-local-auth false -n <namespace-name> --resource-group <res-group>
```
### Stuur Berigte met sleutels (Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/ListKeys/action OF Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/regenerateKeys/action)

Jy kan die `PrimaryConnectionString` verkry, wat as 'n geloofsbrief vir die Service Bus-namespace optree. Met hierdie verbindingsstring kan jy ten volle autentiseer as die Service Bus-namespace, wat jou in staat stel om berigte na enige wachtrij of onderwerp te stuur en moontlik met die stelsel te kommunikeer op maniere wat operasies kan ontwrig, geldige gebruikers kan naboots, of kwaadwillige data in die boodskapwerkvloei kan inspuit. Hierdie metode werk as `--disable-local-auth` op vals gestel is (sodat plaaslike autentisering geaktiveer is).
```python
import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
# pip install azure-servicebus

NAMESPACE_CONNECTION_STR = "<PrimaryConnectionString>"
TOPIC_OR_QUEUE_NAME = "<TOPIC_OR_QUEUE_NAME>"

async def send_message():
async with ServiceBusClient.from_connection_string(NAMESPACE_CONNECTION_STR) as client:
async with client.get_topic_sender(topic_name=TOPIC_OR_QUEUE_NAME) as sender:
await sender.send_messages(ServiceBusMessage("Hacktricks-Training: Single Item"))
print("Sent message")

asyncio.run(send_message())
```
Boonop kan jy boodskappe stuur met az rest, in hierdie geval moet jy 'n sas-token genereer om te gebruik.
```python
import time, urllib.parse, hmac, hashlib, base64

def generate_sas_token(uri, key_name, key, expiry_in_seconds=3600):
expiry = int(time.time() + expiry_in_seconds)
string_to_sign = urllib.parse.quote_plus(uri) + "\n" + str(expiry)
signed_hmac_sha256 = hmac.new(key.encode('utf-8'), string_to_sign.encode('utf-8'), hashlib.sha256).digest()
signature = urllib.parse.quote_plus(base64.b64encode(signed_hmac_sha256))
token = f"SharedAccessSignature sr={urllib.parse.quote_plus(uri)}&sig={signature}&se={expiry}&skn={key_name}"
return token

# Replace these with your actual values
resource_uri = "https://<namespace>.servicebus.windows.net/<queue_or_topic>"
key_name = "<SharedKeyName>"
primary_key = "<PrimaryKey>"

sas_token = generate_sas_token(resource_uri, key_name, primary_key)
print(sas_token)
```

```bash
az rest --method post \
--uri "https://<NAMESPACE>.servicebus.windows.net/<queue>/messages" \
--headers "Content-Type=application/atom+xml;type=entry;charset=utf-8" "Authorization=SharedAccessSignature sr=https%3A%2F%2F<NAMESPACE>.servicebus.windows.net%2F<TOPIC_OR_QUEUE_NAME>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>" \
--body "<MESSAGE_BODY>"

```
### Ontvang met sleutels (Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/ListKeys/action OF Microsoft.ServiceBus/namespaces/[queues|topics]/authorizationRules/regenerateKeys/action)

Jy kan die PrimaryConnectionString verkry, wat as 'n geloofsbrief vir die Service Bus naamruimte dien. Met hierdie verbindingsstring kan jy boodskappe van enige wachtrij of subskripsie binne die naamruimte ontvang, wat toegang tot potensieel sensitiewe of kritieke data moontlik maak, data-uitvloeiing moontlik maak, of inmeng met boodskapverwerking en toepassingswerkvloei. Hierdie metode werk as `--disable-local-auth` op vals gestel is.
```python
import asyncio
from azure.servicebus.aio import ServiceBusClient
# pip install azure-servicebus

CONN_STR = "<PrimaryConnectionString>"
QUEUE = "<QUEUE_NAME>"

# For topics/subscriptions, you would use:
# TOPIC = "<TOPIC_NAME>"
# SUBSCRIPTION = "<TOPIC_SUBSCRIPTION_NAME>"

async def receive():
async with ServiceBusClient.from_connection_string(CONN_STR) as client:
# For a queue receiver:
async with client.get_queue_receiver(queue_name=QUEUE, max_wait_time=5) as receiver:
msgs = await receiver.receive_messages(max_wait_time=5, max_message_count=20)
for msg in msgs:
print("Received:", msg)
await receiver.complete_message(msg)

# For a topic/subscription receiver (commented out):
# async with client.get_subscription_receiver(topic_name=TOPIC, subscription_name=SUBSCRIPTION, max_wait_time=5) as receiver:
#     msgs = await receiver.receive_messages(max_wait_time=5, max_message_count=20)
#     for msg in msgs:
#         print("Received:", msg)
#         await receiver.complete_message(msg)

asyncio.run(receive())
print("Done receiving messages")
```
Boonop kan jy boodskappe stuur met az rest, in hierdie geval moet jy 'n sas-token genereer om te gebruik.
```python
import time, urllib.parse, hmac, hashlib, base64

def generate_sas_token(uri, key_name, key, expiry_in_seconds=3600):
expiry = int(time.time() + expiry_in_seconds)
string_to_sign = urllib.parse.quote_plus(uri) + "\n" + str(expiry)
signature = urllib.parse.quote_plus(base64.b64encode(
hmac.new(key.encode('utf-8'), string_to_sign.encode('utf-8'), hashlib.sha256).digest()
))
token = f"SharedAccessSignature sr={urllib.parse.quote_plus(uri)}&sig={signature}&se={expiry}&skn={key_name}"
return token

# Example usage:
resource_uri = "https://<namespace>.servicebus.windows.net/queue"  # For queue
# resource_uri = "https://<namespace>.servicebus.windows.net/<topic>/subscriptions/<subscription>"  # For topic subscription
sas_token = generate_sas_token(resource_uri, "<KEYNAME>", "<PRIMARY_KEY>")
print(sas_token)

```
Vir 'n wachtrij kan jy die boodskap kry of 'n blik daarop neem (om 'n boodskap te kry, sal dit verwyder word, terwyl 'n blik daarop nie sal):
```bash
#Get a message
az rest --method post \
--uri "https://<NAMESPACE>.servicebus.windows.net/<QUEUE>/messages/head?timeout=60" \
--headers "Content-Type=application/atom+xml;type=entry;charset=utf-8" "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"

#Peek a message
az rest --method get \
--uri "https://<NAMESPACE>.servicebus.windows.net/<QUEUE>/messages/head?peekonly=true&timeout=60" \
--headers "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"

#You can select the meesage changing the field PreviousSequenceNumber
az rest --method get \
--uri "https://<NAMESPACE>.servicebus.windows.net/<ENTITY>/messages?timeout=60&PreviousSequenceNumber=<LAST_SEQUENCE_NUMBER>&api-version=2017-04" \
--headers "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"
```
Please provide the text you would like me to translate to Afrikaans.
```bash
#Get a message
az rest --method post \
--uri "https://<NAMESPACE>.servicebus.windows.net/<TOPIC>/subscriptions/<SUBSCRIPTION>/messages/head?timeout=60" \
--headers "Content-Type=application/atom+xml;type=entry;charset=utf-8" "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"

#Peek a message
az rest --method get \
--uri "https://<NAMESPACE>.servicebus.windows.net/<TOPIC>/subscriptions/<SUBSCRIPTION>/messages/head?timeout=60&api-version=2017-04" \
--headers "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"

#You can select the meesage changing the field PreviousSequenceNumber
az rest --method get \
--uri "https://<NAMESPACE>.servicebus.windows.net/<TOPIC>/subscriptions/<SUBSCRIPTION>/messages?timeout=60&PreviousSequenceNumber=<LAST_SEQUENCE_NUMBER>&api-version=2017-04" \
--headers "Authorization=SharedAccessSignature sr=<URI_ENCODED_RESOURCE>&sig=<SIGNATURE>&se=<EXPIRY>&skn=<KEYNAME>"
```
### Stuur Berigte. DataActions: `Microsoft.ServiceBus/namespaces/messages/send/action`

Jy kan hierdie toestemmings gebruik om berigte te stuur, selfs as `--disable-local-auth` op waar is.
```python
import asyncio
from azure.identity.aio import DefaultAzureCredential
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
# pip install azure-servicebus

NS = "<namespace>.servicebus.windows.net"  # Your namespace
QUEUE_OR_TOPIC = "<QUEUE_OR_TOPIC>"        # Your queue name

async def run():
credential = DefaultAzureCredential()
async with ServiceBusClient(fully_qualified_namespace=NS, credential=credential) as client:
#async with client.get_topic_sender(topic_name=TOPIC) as sender: # Use this to send the message to a topic
async with client.get_queue_sender(queue_name=QUEUE) as sender:
await sender.send_messages(ServiceBusMessage("Single Message"))
print("Sent a single message")
await credential.close()

if __name__ == "__main__":
asyncio.run(run())
```
### Ontvang Berigte. DataActions: `Microsoft.ServiceBus/namespaces/messages/receive/action`

Jy kan hierdie toestemmings gebruik om berigte te ontvang, selfs as `--disable-local-auth` op waar is.
```python
import asyncio
from azure.identity.aio import DefaultAzureCredential
from azure.servicebus.aio import ServiceBusClient
# pip install azure-servicebus

NS = "<namespace>.servicebus.windows.net"
QUEUE = "<QUEUE>"

# For a topic subscription, uncomment and set these values:
# TOPIC = "<TOPIC>"
# SUBSCRIPTION = "<SUBSCRIPTION>"

async def run():
credential = DefaultAzureCredential()
async with ServiceBusClient(fully_qualified_namespace=NS, credential=credential) as client:
# Receiving from a queue:
async with client.get_queue_receiver(queue_name=QUEUE, max_wait_time=5) as receiver:
async for msg in receiver:
print("Received from Queue:", msg)
await receiver.complete_message(msg)

# To receive from a topic subscription, uncomment the code below and comment out the queue receiver above:
# async with client.get_subscription_receiver(topic_name=TOPIC, subscription_name=SUBSCRIPTION, max_wait_time=5) as receiver:
#     async for msg in receiver:
#         print("Received from Topic Subscription:", msg)
#         await receiver.complete_message(msg)

await credential.close()

asyncio.run(run())
print("Done receiving messages")
```
## Verwysings

- [https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues](https://learn.microsoft.com/en-us/azure/storage/queues/storage-powershell-how-to-use-queues)
- [https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api](https://learn.microsoft.com/en-us/rest/api/storageservices/queue-service-rest-api)
- [https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes](https://learn.microsoft.com/en-us/azure/storage/queues/queues-auth-abac-attributes)
- [https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless](https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-python-how-to-use-topics-subscriptions?tabs=passwordless)
- [https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/integration#microsoftservicebus)

{{#include ../../../banners/hacktricks-training.md}}
