<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sylia CHIBOUB on Medium]]></title>
        <description><![CDATA[Stories by Sylia CHIBOUB on Medium]]></description>
        <link>https://medium.com/@schh?source=rss-129fe97ed115------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W_FK0IzI5ALTys27WyM_Bg.png</url>
            <title>Stories by Sylia CHIBOUB on Medium</title>
            <link>https://medium.com/@schh?source=rss-129fe97ed115------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:16:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@schh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kubernetes Series: Explaining ConfigMaps with Practical Examples]]></title>
            <link>https://schh.medium.com/kubernetes-series-explaining-configmaps-with-practical-examples-a9eacf77449b?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9eacf77449b</guid>
            <category><![CDATA[ckad]]></category>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[configmap]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 14:12:51 GMT</pubDate>
            <atom:updated>2023-06-13T14:34:59.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyWhG9gVUynqreAa.jpeg" /></figure><h4>Introduction</h4><p>This article aims at explaining the <em>Kubernetes ConfigMap objects </em>through a set of practical examples.</p><h4>ConfigMaps</h4><p>A <em>ConfigMap </em>is an k8s <em>API object</em> used to store <em>non-confidential</em> data in <em>key-value</em> pairs. It aims at making applications easily portable through decoupling their environment-specific configuration. <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxFzj30ftkE3Wvl7oqEnAw.png" /><figcaption>Application Portability with ConfigMaps <a href="https://www.middlewareinventory.com/blog/kubernetes-configmap-examples/">[2]</a></figcaption></figure><p>A <em>ConfigMap </em>has <em>data </em>and <em>binaryData </em>fields. These fields accept <em>key-value pairs </em>as their values. Both the <em>data </em>field and the <em>binaryData </em>are optional.</p><blockquote>The data field is designed to contain UTF-8 strings while the binaryData field is designed to contain binary data as base64-encoded strings.</blockquote><blockquote>The keys stored in data must not overlap with the keys in the binaryData field.</blockquote><p><em>Configmaps </em>can be created:</p><ul><li>From literal value</li><li>From a file</li><li>From a directory of files</li></ul><p>They are used to configure a <em>container </em>inside a <em>Pod </em>in different ways:</p><ul><li>As environment variables for a <em>container</em></li><li>As a file in read-only volume, for the application to read</li></ul><p>A <em>ConfigMap </em>is not designed to hold large chunks of data. The data stored in a <em>ConfigMap </em>cannot exceed 1 MiB. <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></p><blockquote>If you need to store settings that are larger than this limit, you may want to consider mounting a volume <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable"><em>[1]</em></a></blockquote><h4>Practical Examples: Creating ConfigMaps</h4><ol><li><strong>Let’s use </strong><strong>kubectl command to create a </strong><strong>ConfigMap from literal value</strong></li></ol><pre># check how to create a ConfigMap<br>kubectl create configmap -h</pre><pre><br># create a new config map named game-demo with the following key-values: <br># player_initial_lives=&quot;3&quot;<br># ui_properties_file_name=&quot;user-interface.properties&quot;<br><br>kubectl create configmap game-demo \<br>--from-literal=player_initial_lives=&quot;3&quot; \<br>--from-literal=ui_properties_file_name=&quot;user-interface.properties&quot;<br><br># describe the created configmap game-demo<br>kubectl describe configmap game-demo<br><br># OUTPUT: <br>Name:         game-demo          #configmap name<br>Namespace:    default<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br><br>Data                             #configmap data field<br>====<br>player_initial_lives:            #configmap data key <br>----<br>3                                #configmap data value<br>ui_properties_file_name:         #configmap data key<br>----<br>user-interface.properties        #configmap data value<br><br>BinaryData                       #confgimap binarydata field<br>====<br><br>Events:  &lt;none&gt;</pre><p>2.<strong> Let’s use </strong><strong>kubectl command to create a </strong><strong>ConfigMap from a file</strong></p><p>Let’s say we have an alerts.yml file that defines alerts for <a href="https://medium.com/devops-dudes/prometheus-alerting-with-alertmanager-e1bbba8e6a8e">Prometheus</a>.</p><pre># alerts.yml<br>groups:<br>- name: Nodes Alerts<br>  rules:<br><br>  - alert: VM Down<br>    expr: up{job=&quot;node_exporter&quot;} == 0<br>    for: 10m<br>    labels:<br>            severity: &quot;critical&quot;<br>    annotations:<br>            description: &quot; The VM {{ $labels.instance }} has been down for more than 10 minutes.&quot;</pre><p>Let create a ConfigMap that will contain the alerts.yml file. alerts.yml is the ConfigMap key and the alerts.yml file content is the ConfigMap value.</p><pre># create the configmap from file<br>kubectl create configmap prometheus-alerts  --from-file=alerts.yml<br><br># describe the configmap to see its content<br>kubectl describe configmap prometheus-alerts<br><br># OUTPUT<br><br>Name:         prometheus-alerts  #configmap name<br>Namespace:    default<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br><br>Data<br>====<br>alerts.yml:                      #configmap key<br>---- <br>groups:                          #configmap value<br>- name: Nodes Alerts<br>  rules:<br><br>  - alert: VM Down<br>    expr: up{job=&quot;node_exporter&quot;} == 0<br>    for: 10m<br>    labels:<br>            severity: &quot;critical&quot;<br>    annotations:<br>            description: &quot; The VM {{ $labels.instance }} has been down for more than 10 minutes.&quot;<br><br><br>BinaryData<br>====<br><br>Events:  &lt;none&gt;</pre><p>3.<strong> Let’s use </strong><strong>kubectl command to create a </strong><strong>ConfigMap from a folder</strong></p><p>We have a folder named alerts that consists of two files : alert-node.yml and alert-memory.yml :</p><pre># alert-memory.yml<br>groups:<br>- name: Memory Alerts<br>  rules:<br><br>  - alert: High Memory Usage<br>     expr: (node_memory_MemAvailable_bytes * 100) / node_memory_MemTotal_bytes &lt; 15<br>     for: 30m<br>     labels:<br>            severity: warning<br>     annotations:<br>            description: &#39; The memory of the VM: {{ $labels.instance }} is filling up. The available Memory is only {{ $value | printf &quot;%.2f&quot; }} %.&#39;</pre><pre># alert-node.yml<br>- name: Nodes Alerts<br>  rules:<br><br>  - alert: VM Down<br>    expr: up{job=&quot;node_exporter&quot;} == 0<br>    for: 10m<br>    labels:<br>            severity: &quot;critical&quot;<br>    annotations:<br>            description: &quot; The VM {{ $labels.instance }} has been down for more than 10 minutes.&quot;</pre><p>Let create a ConfigMap that will contain the alerts folder content (in our case, both files alert-node.yml and alert-memory.yml). Files names represent the ConfigMap keys whereas files content represent the ConfigMap values.</p><pre># Create a new config map named prometheus-alerts based on folder alerts<br>kubectl create configmap prometheus-alerts --from-file=./alerts/<br><br># Let&#39;s describe the configmap to see its content<br>kubectl describe configmap prometheus-alerts<br><br># OUTPUT:<br><br>Name:         prometheus-alerts #configmap name<br>Namespace:    default<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br><br>Data<br>====<br>alert-memory.yml:               #configmap key<br>----<br>groups:                         #configmap value<br>- name: Memory Alerts<br>  rules:<br><br>  - alert: High Memory Usage<br>     expr: (node_memory_MemAvailable_bytes * 100) / node_memory_MemTotal_bytes &lt; 15<br>     for: 30m<br>     labels:<br>            severity: warning<br>     annotations:<br>            description: &#39; The memory of the VM: {{ $labels.instance }} is filling up. The available Memory is only {{ $value | printf &quot;%.2f&quot; }} %.&#39;<br><br>alert-node.yml:                 #configmap key<br>----<br>groups:                         #configmap value<br>- name: Nodes Alerts<br>  rules:<br><br>  - alert: VM Down<br>    expr: up{job=&quot;node_exporter&quot;} == 0<br>    for: 10m<br>    labels:<br>            severity: &quot;critical&quot;<br>    annotations:<br>            description: &quot; The VM {{ $labels.instance }} has been down for more than 10 minutes.&quot;<br><br><br>BinaryData<br>====<br><br>Events:  &lt;none&gt;</pre><blockquote>Note that this article doesn’t concern Prometheus, thus the way we’re creating alerts using ConfigMaps is not the right way to use for Prometheus, These are just examples.</blockquote><p>4.<strong> Let’s use </strong><strong>kubectl command to create a </strong><strong>ConfigMap from an environment File.</strong></p><p>Let’s say we have the following .env file</p><pre>#.env<br>DATABASEHOST=localhost</pre><p>Let create a ConfigMap that will contain the .env environment file content. DATABASEHOST is the ConfigMap key and the localhost is the ConfigMap value.</p><pre># create the configmap <br>kubectl create configmap database --from-env-file=.env<br><br># describe the created configmap<br>kubectl describe configmap database<br><br># OUTPUT<br>Name:         database   #configmap name<br>Namespace:    default<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br><br>Data<br>====<br>DATABASEHOST:            #configmap key<br>----<br>localhost                #configmap value<br><br>BinaryData<br>====<br><br>Events:  &lt;none&gt;</pre><h4>Practical Examples: Mount ConfigMaps to Containers</h4><ol><li><strong>Mounting the </strong>configmap <strong>as a file (or a set of files) in read-only volume</strong></li></ol><p>Let’s create a pod named nginx to which the configmapnamed prometheus-alerts created previously from a folder will be mounted</p><pre># generate the nginx pod yaml file<br>kubectl run nginx - image=nginx - dry-run=client -o yaml &gt; nginx.yaml</pre><p>Let’s edit the nginx.yamlfile to mount the prometheus-alerts configmap as a file (or a set of files, depending on the configmap available keys) in read-only volume.</p><pre># nginx.yaml<br># data defined in the configmap prometheus-alerts will be mounted as files <br># to the alerts volume mounted under the /alerts path within <br># the nginx container<br><br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  # ------ add this lines------<br>    volumeMounts:<br>    - name: alerts<br>      mountPath: /alerts <br>      readOnly: true <br>  # ---------------------------<br>  volumes:<br>  - name: alerts<br>    configMap:<br>      name: prometheus-alerts<br>  # ---------------------------<br>  restartPolicy: Always</pre><pre># create the nginx pod <br>kubectl apply -f nginx.yaml<br><br># checkout the mounted files<br>kubectl exec -it nginx -- sh -c &quot;ls /alerts/&quot;<br><br># OUTPUT<br>alert-memory.yml  alert-node.yml</pre><p>Instead of mounting all of configmap data, we can mount only specific data based on keys as files within a container as follows:</p><pre># nginx.yaml<br># the value of alert-node.yml key defined in the configmap prometheus-alerts<br># will be mounted as a file named alert-node.yml<br># to the alerts volume mounted under the /alerts path within<br># the nginx container<br><br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  # ------ add this lines------<br>    volumeMounts:<br>    - name: alerts<br>      mountPath: /alerts<br>      readOnly: true<br>  # ---------------------------<br>  volumes:<br>  - name: alerts<br>    configMap:<br>      name: prometheus-alerts<br>      items:<br>        # configmap selected key<br>        - key: alert-node.yml<br>          # how the file will be named<br>          # (the file contains the value of the selected key)<br>          path: alert-node.yml<br>  # ---------------------------<br>  restartPolicy: Always</pre><pre># create the nginx pod <br>kubectl apply -f nginx.yaml<br><br># checkout the mounted files<br>kubectl exec -it nginx -- sh -c &quot;ls /alerts/&quot;<br><br># OUTPUT<br>alert-node.yml</pre><p>2.<strong> Mounting the </strong>configmap <strong>as environment variables for a container</strong></p><p>Let’s create a pod named nginx to which the configmapnamed database created previously from an environment file will be mounted.</p><pre># generate the nginx pod yaml file<br>kubectl run nginx - image=nginx - dry-run=client -o yaml &gt; nginx.yaml</pre><pre># nginx.yaml<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>    # add these lines ---------<br>    env:<br>    - name: databaseName<br>      valueFrom:<br>        configMapKeyRef:<br>          name: database<br>          key: DATABASEHOST<br>    # --------------------------</pre><pre># create the pod <br>kubectl apply -f nginx.yml<br><br># verify if the env variable has been set for the container nginx<br>kubectl exec -it nginx --sh -c &quot;printenv&quot; <br><br>#OUTPUT<br>..<br>databaseName=localhost</pre><h4><strong>Mounted ConfigMaps are updated automatically</strong></h4><p>When a <em>ConfigMap </em>currently consumed in a volume is updated, projected keys are eventually updated as well. The <em>kubelet </em>checks whether the mounted <em>ConfigMap </em>is fresh on every periodic sync.<a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></p><blockquote>ConfigMaps consumed as environment variables are not updated automatically and require a pod restart <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable"><em>[1]</em></a></blockquote><blockquote>A container using a ConfigMap as a subPath volume mount will not receive ConfigMap updates. <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable"><em>[1]</em></a></blockquote><h4><strong>Immutable ConfigMaps</strong></h4><p>The <em>Kubernetes </em>feature <em>Immutable ConfigMaps </em>provides an option to set individual <em>ConfigMaps </em>as immutable, preventing changes to their data. This option has the following advantages: <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></p><ul><li>Protection against unwanted updates that could cause applications outages <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></li><li>Cluster performance improvement through significantly reducing load on <em>kube-apiserver,</em> by closing watches for <em>ConfigMaps </em>marked as immutable. <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></li></ul><p>An immutable <em>ConfigMap </em>can be created by setting the immutable field to true. For example: <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  ...<br>data:<br>  ...<br>immutable: true</pre><h4>Conclusion</h4><p>The primary goal of this article was to provide a good understanding of <em>ConfigMaps k8s objects </em>. This has been accomplished through a brief explanation and a bunch of practical examples.</p><h4>References</h4><p><a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">[1]</a> <em>Configmaps</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable">https://kubernetes.io/docs/concepts/configuration/configmap/#configmap-immutable</a> (Accessed: 13 June 2023).</p><p><a href="https://www.middlewareinventory.com/blog/kubernetes-configmap-examples/">[2]</a> AK, S. (2023) <em>Kubernetes configmap examples — how to guide: Devops junction</em>, <em>Middleware Inventory</em>. Available at: <a href="https://www.middlewareinventory.com/blog/kubernetes-configmap-examples/">https://www.middlewareinventory.com/blog/kubernetes-configmap-examples/</a> (Accessed: 13 June 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9eacf77449b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Control Pods Traffic with Network Policies]]></title>
            <link>https://medium.com/cloud-native-daily/kubernetes-series-control-pods-traffic-with-network-policies-5b753f2e4b1c?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b753f2e4b1c</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 14:22:41 GMT</pubDate>
            <atom:updated>2023-06-12T13:54:46.597Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explaining k8s <em>NetworkPolicies resources, Pod </em>isolation based on network traffic types, <em>a NetworkPolicy </em>manifest and <em>NetworkPolicy </em>fields with some practical examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f_4E2YuMRQJm8IKq.jpeg" /></figure><h4>Introduction</h4><p>This article covers the k8s <em>Network Policies</em>. Section 1 explains k8s <em>NetworkPolicies resources</em>, Section 2 goes through <em>Pod </em>isolation based on network traffic types. Section 3 illustrates <em>a NetworkPolicy </em>manifest and finally Section 4 details <em>NetworkPolicy </em>fields with some practical examples.</p><h4>1. Network Policies</h4><p><em>NetworkPolicies </em>provide the ability to control <em>Pod</em>s network traffic at the IP address or port level (OSI layer 3 or 4) through specifying how a <em>Pod </em>is allowed (or not) to communicate with other network entities. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woag5hQlEiknYUk2eFC-Ww.png" /><figcaption>OSI Model<a href="https://www.cloudflare.com/learning/ddos/glossary/open-systems-interconnection-model-osi/"> [2]</a></figcaption></figure><blockquote>It is worth noting that NetworkPolicies only apply to Pods and are not relevant to other k8s resources.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1]</em></a><em> </em>They only restrict Pod-to-Pod communication when necessary.</blockquote><p>Entities that a <em>Pod </em>can communicate with are identified through a combination of the following 3 identifiers: <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><ul><li>Other <em>Pods </em>that are allowed (exception: a <em>Pod </em>cannot block access to itself)</li><li><em>Namespaces </em>that are allowed</li><li>IP blocks (exception: traffic to and from the node where a <em>Pod </em>is running is always allowed, regardless of the IP address of the <em>Pod </em>or the node)</li></ul><p><strong>Prerequisites</strong></p><blockquote>NetworkPolicies are implemented by the k8s network plugins such as Calico<em>. </em>To use NetworkPolicies, you must be using a networking solution which supports NetworkPolicy. Creating a NetworkPolicy resource without a controller that implements it will have no effect.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1]</em></a></blockquote><h4>2. Pods Isolation</h4><p>There are two sorts of isolation for a pod:</p><blockquote>Isolation for ingress: ingress refers to inbound traffic received by the <em>Pod.</em></blockquote><blockquote>Isolation for Egress: egress refers to outbound traffic sent by the <em>Pod</em>.</blockquote><p>They are declared independently, and are both relevant for a communication from one <em>Pod </em>to another. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><h4><strong>2.1 Isolation for Ingress</strong></h4><p>By default, a <em>Pod </em>is non-isolated for ingress. All inbound connections <strong>to</strong> the <em>Pod </em>are allowed. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><p>A <em>Pod </em>is isolated for ingress if there is any <em>NetworkPolicy </em>that both selects the <em>Pod </em>and has ingress attribute in its policyTypes (<em>NetworkPolicy </em>Fields are presented later on). <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><p>When a <em>Pod </em>is isolated for ingress, the only allowed connections into the pod are those from the <em>Pod&#39;s</em> node and those allowed by the ingress list of some <em>NetworkPolicy </em>that applies to the <em>Pod </em>for ingress. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><p>For a connection from a source <em>Pod </em>to a destination <em>Pod </em>to be allowed, both the egress policy on the source <em>Pod </em>and the ingress policy on the destination <em>Pod </em>need to allow the connection. If either side does not allow the connection, it will not happen</p><blockquote><strong>Important</strong></blockquote><blockquote>NetworkPolicies do not conflict.They are additive. If any policy or policies apply to a given pod for a given direction, the connections allowed in that direction from that pod is the union of what the applicable policies allow. Thus, order of evaluation does not affect the policy result. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1]</em></a></blockquote><h4>2.2 Isolation for egress</h4><p>By default, a <em>Pod </em>is non-isolated for egress. All outbound connections are allowed. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><p>A <em>Pod </em>is isolated for egress if there is any <em>NetworkPolicy </em>that both selects the <em>Pod </em>and has egress attribute in its policyTypes (<em>NetworkPolicy </em>Fields are presented later on)<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><p>When a <em>Pod </em>is isolated for egress, the only allowed connections <strong>from </strong>the pod are those allowed by the egress list of the <em>NetworkPolicy </em>that applies to the <em>Pod </em>for egress. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a></p><h4>3. The NetworkPolicy YAML Manifest</h4><p>Here’s an example of a <em>NetworkPolicy </em>taken from Kubernetes Official Documentation <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</p><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: test-network-policy<br>  namespace: default<br>spec:<br>  podSelector:<br>    matchLabels:<br>      role: db<br>  policyTypes:<br>    - Ingress<br>    - Egress<br>  ingress:<br>    - from:<br>        - ipBlock:<br>            cidr: 172.17.0.0/16<br>            except:<br>              - 172.17.1.0/24<br>        - namespaceSelector:<br>            matchLabels:<br>              project: myproject<br>        - podSelector:<br>            matchLabels:<br>              role: frontend<br>      ports:<br>        - protocol: TCP<br>          port: 6379<br>  egress:<br>    - to:<br>        - ipBlock:<br>            cidr: 10.0.0.0/24<br>      ports:<br>        - protocol: TCP<br>          port: 5978<br><br></pre><p>The above <em>NetworkPolicy </em>performs the following:</p><ul><li>It isolates <em>Pods </em>with the<em> </em>role=db <em>label</em> in the default <em>namespace </em>for both ingress and egress traffic.</li><li>It defines a set of ingress rules that allow connections <strong>to </strong><em>Pods </em>with the<em> </em>role=db <em>label</em> in the default <em>namespace </em>on TCP port 6379 only from:</li></ul><blockquote>- Any pod in the <em>default</em> namespace with the label <em>role=frontend</em></blockquote><blockquote>- Any pod in a namespace with the label <em>project=myproject</em></blockquote><blockquote>- Entities with IP addresses in the <em>CIDR </em><em>172.17.0.0/16</em> <em>except </em><em>172.17.1.0/24</em></blockquote><ul><li>It defines a set of egress rules that allow connections <strong>from </strong><em>Pods </em>with the<em> </em>role=db <em>label</em> in the defaultto CIDR 10.0.0.0/24 on TCP port 5978 .</li></ul><h4><strong>4. </strong>The NetworkPolicy Fields</h4><ul><li><strong>podSelector </strong>: selects the grouping of <em>Pods </em>based on their <em>Labels </em>in the same <em>namespace </em>as the <em>NetworkPolicy. </em>An empty podSelector selects all pods in the namespace.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre># this pod selector selects all pods having the label role: db<br># in the NetworkPolicy namespace<br><br>...<br>spec:<br>  podSelector:<br>    matchLabels:<br>      role: db<br>...</pre><blockquote><strong>Important</strong></blockquote><pre># this pod selector selects all pods in the NetworkPolicy namespace<br>podSelector: {}</pre><ul><li><strong>policyTypes : </strong>It may include either Ingress, Egress, or both. it indicates whether or not the <em>NetworkPolicy </em>applies to Ingresstraffic <strong>to</strong> selected pod, Egresstraffic <strong>from </strong>selected pods, or both.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre>...<br>policyTypes:<br>    - Ingress<br>    - Egress<br>...</pre><blockquote>Important</blockquote><blockquote>If no policyTypes are specified on a NetworkPolicy then by default Ingress will always be set and Egress will be set if the NetworkPolicy has any Egressrules</blockquote><blockquote>if a <strong>policyTypes</strong> is defined with Ingress or Egress but no <strong>Ingress</strong> or <strong>Egress</strong> fields are specified later then by default Ingress and Egress traffic will be denied. Here’s an example:</blockquote><pre># Deny all ingress traffic: <br># ---------------------------<br><br># This NetworkPolicy selects all pods in the NetworkPolicy namespace<br># but does not allow any ingress traffic to those pods.<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-ingress<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Ingress</pre><pre># Deny all egress traffic: <br># ---------------------------<br><br># This NetworkPolicy selects all pods in the NetworkPolicy namespace<br># but does not allow any egress traffic to those pods.<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-egress<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Egress</pre><pre># Deny all ingress and all egress traffic<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-all<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Ingress<br>  - Egress</pre><ul><li><strong>Ingress : </strong>Includes a list of allowed ingress rules. Each rule allows traffic which matches both the from and ports sections. The example policy contains a singleingress rule, which matches traffic on a single port, from one of three sources: ipBlock, namespaceSelector and podSelector.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre>ingress:<br>    - from:<br>        - ipBlock:<br>            cidr: 172.17.0.0/16<br>            except:<br>              - 172.17.1.0/24<br>        - namespaceSelector:<br>            matchLabels:<br>              project: myproject<br>        - podSelector:<br>            matchLabels:<br>              role: frontend<br>      ports:<br>        - protocol: TCP<br>          port: 6379</pre><blockquote><strong>Important</strong></blockquote><blockquote>If no rule is specified within the <strong>Ingress</strong> as follows. Then, all ingress traffic will be allowed. Here’s an example that allows all incoming ingress traffic to all pods in the NetworkPolicy namespace.</blockquote><pre># Allow all ingress traffic to all pods within the NetworkPolicy namespace<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-all-ingress<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Ingress<br> ingress:<br>  - {}</pre><ul><li><strong>ipBlock </strong>This selects particular IP CIDR ranges to allow as ingress sources or egress destinations. These should be cluster-external IPs, since Pod IPs are ephemeral and unpredictable.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre>...<br>...<br>ingress:<br>    - from:<br>        - ipBlock:<br>            cidr: 172.17.0.0/16<br>            except:<br>              - 172.17.1.0/24</pre><ul><li><strong>namespaceSelector </strong>This selects particular <em>namespaces </em>having specific <em>labels </em>for which all <em>Pods </em>should be allowed as ingress sources or egress destinations.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre># There&#39;s two ways of targeting labeled namespaces:<br><br># OPTION 1: target the namespace labeled project:myproject<br>ingress:<br>    - from:<br>        ...<br>        - namespaceSelector:<br>            matchLabels:<br>              project: myproject<br><br># OPTION 2: target namespaces having project:myproject1 and app:myproject2 labels<br>- namespaceSelector:<br>        matchExpressions:<br>        - key: project<br>          operator: In<br>          values: [&quot;myproject1&quot;, &quot;myproject2&quot;]</pre><blockquote><strong><em>Important</em></strong></blockquote><blockquote><strong>namespaceSelector</strong><em>and</em> <strong>podSelector</strong>: A single to/from entry that specifies both namespaceSelector and podSelector selects particular Pods within particular namespaces. Be careful to use correct YAML syntax. For example:<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1</em></a><em>]</em></blockquote><pre>...<br>  ingress:<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          user: alice<br>      podSelector:<br>        matchLabels:<br>          role: client<br>  ...</pre><blockquote>This policy contains a single from element allowing connections from Pods with the label role=client in namespaces with the label user=alice. <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1</em></a><em>]</em></blockquote><blockquote>But the following policy is different:</blockquote><pre>...<br>  ingress:<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          user: alice<br>    - podSelector:<br>        matchLabels:<br>          role: client<br>  ...</pre><blockquote>It contains two elements in the from array, and allows connections from Pods in the same <em>namespace </em>as the NetworkPolicy having the label role=client, <em>or</em> from any Pod in any namespace labeleduser=alice.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/"><em>[1</em></a><em>]</em></blockquote><ul><li><strong>Port</strong> this field allows Igress or Egress traffic to a specific port or to a range of port. For exampe:</li></ul><pre><br># allow ingress traffic on port 6370<br>...<br>ingress:<br>    - from:<br>       ...<br>      ports:<br>        - protocol: TCP<br>          port: 6379</pre><pre># allow ingress traffic on port range 32000 - 32768<br>...<br>ingress:<br>    - from:<br>       ...<br>      ports:<br>        - protocol: TCP<br>          port: 32000<br>          endPort: 32768</pre><ul><li><strong>Egress : </strong>Each <em>NetworkPolicy </em>may include a list of allowed egress rules. Each rule allows traffic which matches both the to and ports sections. The example policy contains a single rule, which matches traffic on a single port to any destination in 10.0.0.0/24.<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1</a>]</li></ul><pre>egress:<br>    - to:<br>        - ipBlock:<br>            cidr: 10.0.0.0/24<br>      ports:<br>        - protocol: TCP<br>          port: 5978</pre><blockquote><strong>Important</strong></blockquote><blockquote>If no rule is specified within the <strong><em>Egress</em></strong> as follows. Then, all egress traffic will be allowed. Here’s an example that allows all incoming egress traffic to all pods in the NetworkPolicy namespace.</blockquote><pre># Allow all egress traffic <br>---<br><br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-all-egress<br>spec:<br>  podSelector: {}<br>  egress:<br>  - {}<br>  policyTypes:<br>  - Egress</pre><h4>Conclusion</h4><p>The primary goal of this article was to give a deeper understanding of the Kubernetes <em>NetworkPolicy </em>resource through practical examples. This has been accomplished by giving a general overview of the k8s <em>NetworkPolicies and </em>then getting more practical through different examples.</p><h4>References</h4><p><a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">[1]</a> <em>Network policies</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">https://kubernetes.io/docs/concepts/services-networking/network-policies/</a> (Accessed: 08 June 2023).</p><h4>Further Reading:</h4><ul><li><a href="https://gethelios.dev/blog/kubernetes-monitoring-opentelemetry/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Kubernetes Monitoring with OpenTelemetry</a></li><li><a href="https://medium.com/cloud-native-daily/distributed-tracing-a-guide-for-2023-a40a1ee218b5">Distributed Tracing: A Guide for 2023</a></li><li><a href="https://javascript.plainenglish.io/9-best-distributed-tracing-tools-for-developers-185e415b7101">9 Best Distributed Tracing Tools for Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b753f2e4b1c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloud-native-daily/kubernetes-series-control-pods-traffic-with-network-policies-5b753f2e4b1c">Kubernetes Series: Control Pods Traffic with Network Policies</a> was originally published in <a href="https://medium.com/cloud-native-daily">Cloud Native Daily</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Securing Access to the k8s API through RBAC]]></title>
            <link>https://schh.medium.com/kubernetes-series-securing-access-to-the-k8s-api-through-rbac-ff93887874d2?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff93887874d2</guid>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 13:10:29 GMT</pubDate>
            <atom:updated>2023-06-07T14:47:01.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V7MnvYCpAvEikKkk.jpeg" /></figure><h4>Introduction</h4><p>This article covers the k8s <em>Role-based access control (RBAC)</em>. It is a continuation of two previous articles of the k8s series:</p><ul><li><a href="https://medium.com/@schh/kubernetes-series-managing-normal-users-access-to-the-k8s-api-420fe09c34c0">Kubernetes Series: Managing Normal Users Access to the k8s API</a></li><li><a href="https://medium.com/@schh/kubernetes-series-managing-serviceaccounts-access-to-the-k8s-api-5b682741fd91">Managing ServiceAccounts Access to the k8s API</a></li></ul><p>Section 1 explains k8s RBAC <em>resources</em>, Section 2 and 3 describe how to refer to RBAC <em>resources </em>and <em>subjects</em>. Section 4 shows some useful RBAC command line utilities Furthermore, Section 5 and 6 illustrate RBAC usage for normal users and <em>ServiceAccounts</em>. Section 7 explicates <em>Aggregated ClusterRoles</em>. Finally, this article ends with a conclusion</p><h4>1. Role-based access control (RBAC)</h4><p>Role-based access control (RBAC) is a method of regulating access to a system based on the roles of individual users within an organization <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a>.</p><p>RBAC authorization uses the rbac.authorization.k8s.io API group to drive authorization decisions. It allows k8s admins to dynamically configure permissions through the k8s API <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a>.</p><p>As discussed in the previous articles mentioned above, the k8s <em>API Server</em> is responsible for checking authorizations. You can see which authorization mode is enabled on the <em>API Server </em>through the following command.</p><pre>cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep authorization<br><br>#OUTPUT: <br>- --authorization-mode=Node,RBAC</pre><p>The RBAC API declares four kinds of k8s objects: <em>Role</em>, <em>ClusterRole</em>, <em>RoleBinding</em> and <em>ClusterRoleBinding </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a>.</p><h4>1.1 Role and ClusterRole</h4><p>An RBAC <em>Role</em> or <em>ClusterRole</em> contains rules that represent a set of permissions. Permissions are purely additive (there are no “deny” rules).<a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><p>A <em>Role </em>always sets permissions within a particular <em>namespace</em>. When you create a <em>Role</em>, you have to specify the <em>namespace </em>it belongs in. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><p><em>ClusterRole</em>, by contrast, is a <em>non-namespaced</em> (cluster-scoped) resource. It can be used:</p><ul><li>define permissions on <em>namespaced </em>resources and be granted access within individual namespace(s) ( Same as a <em>Role </em>) <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></li><li>define permissions on <em>namespaced </em>resources and be granted access across all namespaces (cluster-scoped) <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></li><li>define permissions on cluster-scoped resources (i.e <em>nodes </em>resources) <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></li></ul><blockquote>If you want to define a set of rules within a namespace, use a Role. If you want to define a set of cluster-wide rules, use a ClusterRole. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"><em>[1]</em></a></blockquote><blockquote>The resources have different names (Role and ClusterRole) because a Kubernetes object always has to be either namespaced or not namespaced (cluster-wide), it can’t be both.<a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"><em>[1]</em></a></blockquote><h4>1.2. RoleBinding and ClusterRoleBinding</h4><p>A <em>RoleBinding </em>grants permissions defined in a <em>Role </em>or <em>ClusterRole </em>to a user or set of users within a specific <em>namespace</em>. It holds: <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><ul><li>A list of <em>subjects </em>: <em>users</em>, <em>groups</em>, or <em>service accounts</em></li><li>A reference to the <em>Role </em>or <em>ClusterRole </em>being granted.</li></ul><blockquote>A RoleBinding may reference any Role in the same namespace. Alternatively, a RoleBinding can reference a ClusterRole and bind that ClusterRole to the namespace of the RoleBinding. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"><em>[1]</em></a></blockquote><p>A <em>ClusterRoleBinding </em>grants permissions defined in a <em>ClusterRole </em>to a user or set of users. It grants cluster-wide access. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Q_Hj_HpSmHgKYzZNVOGJQ.png" /><figcaption>RBAC k8s objects</figcaption></figure><blockquote><strong>Important</strong></blockquote><blockquote>After you create a binding, you cannot change the Role or ClusterRole that it refers to. If you try to change a binding’s roleRef, you get a validation error. If you do want to change the roleRef for a binding, you need to remove the binding object and create a replacement.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"><em>[1]</em></a></blockquote><blockquote>The kubectl auth reconcile command-line utility creates or updates a manifest file containing RBAC objects <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"><em>[1]</em></a></blockquote><h4>2. Referring to resources in RBAC</h4><p>As explained in the <a href="https://medium.com/gitconnected/kubernetes-series-getting-practical-with-the-kubernetes-api-9481d6b176ea">k8s API article</a>, most k8s resources are represented and accessed using a string representation of their object name. For example to access logs of a pod within a particular namespace , you need to follow the underlying structure:</p><pre>GET /api/v1/namespaces/{namespace}/pods/{name}/log</pre><p>In this case, pods is the <em>namespaced </em>resource for <em>Pod </em>resources, and log is a subresource of pods. To represent this in an RBAC <em>role</em>, use a slash (/) to delimit the resource and subresource. To allow a subject to read pods and also access the log subresource for each of those Pods, you write: <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: default<br>  name: read-pods<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods&quot;, &quot;pods/log&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]</pre><p>You can also refer to resources by name for certain requests through the resourceNames list. However, not all verbs can be specified when resourceNamesis used. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: default<br>  name: configmap-reader<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;configmaps&quot;]<br>  resourceNames: [&quot;configmap-test&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjeaOAaMz--_RyqT5tX-pg.png" /><figcaption>RBAC Restriction when using resourceNames attribute<a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"> [1]</a></figcaption></figure><p>Furthermore, rather than referring to individual resources, apiGroups, and verbs, you can use the wildcard * symbol to refer to all objects. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><p>Here is an example that allows performing any action on all k8s resources in the core API group. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: default<br>  name: example.com-superuser # DO NOT USE THIS ROLE, IT IS JUST AN EXAMPLE<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;*&quot;]<br>  verbs: [&quot;*&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8EZD66W0koAOhhA6MggoA.png" /><figcaption>RBAC Recommendation <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></figcaption></figure><h4>3. Referring to subjects in RBAC</h4><p>A <em>RoleBinding </em>or <em>ClusterRoleBinding </em>binds a role to subjects. Subjects can be <em>normal users</em> or <em>ServiceAccounts</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><p>Kubernetes represents normal users usernames as strings. These can be:</p><ul><li><em>Username: a string which identifies the end user. Common values might be </em><em>kube-admin or </em><em>jane@example.com. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>UID: a string which identifies the end user and attempts to be more consistent and unique than username.</em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><p><em>ServiceAccounts </em>have names prefixed with system:serviceaccount:. Their names follow the underlying pattern:</p><pre>system:serviceaccount:namespace:serviceaccountname<br><br># For example, a serviceaccount named prod-sa deployed<br># within the namespace production will be named as follows:<br><br>system:serviceaccount:production:prod-sa</pre><p>The following <em>RoleBinding </em>only show the subjects section for a user named alice that belongs to a group named developers</p><pre>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: alice<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: developers</pre><p>The following <em>RoleBinding </em>only show the subjects section for a <em>ServiceAccount </em>named system:serviceaccount:prod:prod-sa</p><pre>subjects:<br>- kind: ServiceAccount<br>  name: prod-sa<br>  namespace: prod</pre><p>The following <em>RoleBinding </em>only show the subjects section for all authenticated users. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>subjects:<br>- kind: Group<br>  name: system:authenticated<br>  apiGroup: rbac.authorization.k8s.io</pre><p>The following <em>RoleBinding </em>only show the subjects section for all unauthenticated users. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>subjects:<br>- kind: Group<br>  name: system:unauthenticated<br>  apiGroup: rbac.authorization.k8s.io</pre><p>The following <em>RoleBinding </em>only show the subjects section for all users. <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></p><pre>subjects:<br>- kind: Group<br>  name: system:authenticated<br>  apiGroup: rbac.authorization.k8s.io<br>- kind: Group<br>  name: system:unauthenticated<br>  apiGroup: rbac.authorization.k8s.io</pre><h4>4. RBAC Command-line utilities</h4><pre># Creates a Role<br>kubectl create role <br># Creates a ClusterRole <br>kubectl create clusterrole <br># Grants a Rolebinding<br>kubectl create rolebinding <br># Grants a ClusterRolebinding<br>kubectl create clusterrolebinding<br># Creates or updates rbac.authorization.k8s.io/v1 API objects from a manifest file.<br>kubectl auth reconcile <br>    # Example of auth reconcile: <br>    kubectl auth reconcile -f roleA.yaml</pre><h4>5. RBAC Practical Examples for Normal Users</h4><p>Let’s say, following the steps explained in m<a href="https://medium.com/@schh/kubernetes-series-managing-normal-users-access-to-the-k8s-api-420fe09c34c0">anaging Normal Users Access to the k8s API</a> article, we have created a user named Alice.</p><p><strong>Use-Case 1: Usage of a <em>Role </em>with a <em>RoleBinding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dXyAhJ1chAIxO6vvwD-aw.png" /><figcaption>Granting Access to namespaced k8s resources</figcaption></figure><p>Grant read access to pods in the namespace prod to user Alicewithin the developerteam.</p><pre># create a role<br>kubectl create role alice-role --verb=get,list,watch --resource=pods --namespace=prod --dry-run=client -o yaml  &gt; alice-role.yaml<br>kubectl apply -f alice-role.yaml<br><br># OUTPUT <br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: alice-role<br>  namespace: prod<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - get<br>  - list<br>  - watch<br></pre><pre># create a roleBinding<br>kubectl create rolebinding alice-rolebinding --role=alice-role --namespace=prod --user=alice --group=developers --dry-run=client -o yaml &gt; alice-rolebinding.yaml<br>kubectl apply -f alice-rolebinding.yaml<br><br># OUTPUT<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: alice-rolebinding<br>  namespace: prod<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: Role<br>  name: alice-role<br>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: alice<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: developers</pre><pre># When Alice runs the following, she should see only pods within the namespace<br># prod<br><br>kubectl get pods -n prod</pre><p><strong>Use-Case 2: Usage of a <em>ClusterRole </em>with a <em>ClusterRoleBinding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5Jlk2Sk4tPkha9P5XTqjg.png" /><figcaption>Granting access to k8s resources across all namespaces (cluster-scoped)</figcaption></figure><p>Grant read access to pods across all namespaces to Alice</p><pre># create a clusterrole <br> <br>kubectl create clusterrole alice-clusterrole --verb=get,list,watch --resource=pods --dry-run=client -o yaml  &gt; alice-clusterrole.yaml<br>kubectl apply -f alice-clusterrole.yaml<br><br># OUTPUT:<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: alice-clusterrole<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - get<br>  - list<br>  - watch</pre><pre># create a clusterrolebinding  <br><br>kubectl create clusterrolebinding alice-clusterrolebinding --clusterrole=alice-clusterrole --user=alice --group=developers --dry-run=client -o yaml &gt; alice-clusterrolebinding.yaml<br>kubectl apply -f alice-clusterolebinding.yaml<br><br># OUTPUT<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: alice-clusterrolebinding<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: alice-clusterrole<br>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: alice<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: developers</pre><pre># When Alice runs the following, she should see all pods across all namespaces<br><br>kubectl get pods --all-namespaces</pre><p><strong>Use-Case 3: Usage of a <em>ClusterRole </em>with a <em>RoleBinding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TL7QjUwNo3U-VKq9CTK9Kw.png" /><figcaption>Grant access to k8s resources within a specific namespace</figcaption></figure><p>If we take the already created ClusterRole : alice-clusterrole and instead of binding it to a ClusterRoleBinding , we bind it to the previously created RoleBinding: alice-rolebinding as follows:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: alice-clusterrole<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - get<br>  - list<br>  - watch<br><br>---<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: alice-rolebinding<br>  namespace: prod<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: alice-clusterrole<br>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: alice<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: developers</pre><p>This time, if Alice tries to access pods within all namespaces ( cluster scoped), she will get rejected:</p><pre># List all pods across all namespaces<br>kubectl get pods --all-namespaces<br><br><br># OUTPUT:<br>Error from server (Forbidden): pods is forbidden: User &quot;alice&quot; cannot list resource &quot;pods&quot; in API group &quot;&quot; at the cluster scope<br><br></pre><blockquote>This is due to the fact the the ClusterRole has been attached to a RoleBinding. Thus, permissions of a ClusterRole when referenced by a RoleBinding ( or a set of RoleBindings) are applied only to the namespaces of the RoleBindings it is attached to.</blockquote><p><strong>Use-Case 4: Usage </strong>resourceNames<strong> attributes within <em>Role </em>attached to a <em>RoleBinding</em></strong></p><p>Grant read access only to the configmap resource named prod-configmapwithin the namespace prodto the user Alicethat belongs to the developersteam.</p><pre># create a role : same process as use-case 1<br>kubectl create role alice-role --verb=get,list,watch --resource=pods --namespace=prod --dry-run=client -o yaml  &gt; alice-role.yaml</pre><pre># Edit the output <br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: alice-role<br>  namespace: prod<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - configmaps<br>  resourceNames:   # add this line<br>  - prod-configmap # add this line<br>  verbs:<br>  - get<br>  - list<br>  - watch</pre><pre># apply the role yaml file <br>kubectl apply -f alice-role.yaml<br><br># create a roleBinding<br>kubectl create rolebinding alice-rolebinding --role=alice-role --namespace=prod --user=alice --group=developers --dry-run=client -o yaml &gt; alice-rolebinding.yaml<br>kubectl apply -f alice-rolebinding.yaml<br><br># OUTPUT<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: alice-rolebinding<br>  namespace: prod<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: Role<br>  name: alice-role<br>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: alice<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: developers</pre><pre># When Alice runs the following, she should see only prod-configmap <br># within the prod namespace<br><br>kubectl get configmap -n prod</pre><h4>6. RBAC Practical Examples for ServiceAccounts</h4><p>RBAC policies allow to grant particular <em>Roles </em>or <em>ClusterRoles </em>to particular <em>ServiceAccounts</em> as needed.</p><p>Default RBAC policies grant scoped permissions to control-plane components, nodes, and controllers. They can be viewed through the following command:</p><pre>kubectl get clusterrole</pre><p>An example of a default <em>ClusterRole </em>is the<em> </em>view <em>ClusterRole </em>which allows to read k8s <em>resources </em>across all <em>namespaces.</em></p><p><strong>Use Case 1: Grant the default </strong><strong>view <em>ClusterRole </em>to a<em> ServiceAccount </em>within a specific<em> namespace</em></strong></p><p>To grant the<em> </em>view <em>ClusterRole</em> to the appA-sa <em>ServiceAccount </em>within the <em>namespace </em>prod :</p><pre>kubectl create rolebinding rb-sa \<br>  --clusterrole=view \<br>  --serviceaccount=prod:appA-sa \<br>  --namespace=prod</pre><p><strong>Use Case 2: Grant the default </strong><strong>view <em>ClusterRole </em>to all <em>ServiceAccount </em>within a specific<em> namespace</em></strong></p><pre>kubectl create rolebinding rb-sa \<br>  --clusterrole=view \<br>  --groups=system:serviceaccounts:prod \<br>  --namespace=prod</pre><p><strong>Use Case 3: Grant the default </strong><strong>view <em>ClusterRole </em>to all <em>ServiceAccount across all namespaces</em></strong></p><pre>kubectl create rolebinding rb-sa \<br>  --clusterrole=view \<br>  --groups=system:serviceaccounts\<br>  --namespace=prod</pre><p><strong>Use Case 4: Grant super-user access to all service accounts cluster-wide (strongly discouraged)</strong></p><pre>kubectl create clusterrolebinding global\<br>  --clusterrole=cluster-admin \<br>  --group=system:serviceaccounts</pre><blockquote><strong>Important</strong></blockquote><blockquote>It is considered as a good practice to grant a role to an application-specific ServiceAccount. This requires the application to specify a serviceAccountName in its pod spec, and for the service account to be created as explained in the <a href="https://medium.com/@schh/kubernetes-series-managing-serviceaccounts-access-to-the-k8s-api-5b682741fd91">Managing ServiceAccounts Access to the k8s API</a> article.</blockquote><h4>7. Aggregated ClusterRoles</h4><p><em>ClusterRoles </em>can be aggregated into one combined <em>ClusterRole</em>. This can be achieved through the usage of <em>Labels </em>referenced within the aggregationRule attribute.</p><p>A <em>controller</em>, running as part of the <em>cluster control plane</em>, watches for <em>ClusterRole </em>objects with <em>Labels </em>set within the aggregationRule attribute and automatically fills the rules of the <em>Aggregated ClusterRole</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXbi8ld8aN-EG2y-f5KBxA.png" /><figcaption>Kubernetes Caution <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[1]</a></figcaption></figure><p>Let’s say we have two <em>ClusterRoles : Alice-ClusterRole and Bob-ClusterRole</em></p><pre># alice-clusterrole.yaml<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: alice-role<br>  labels:<br>    aggregate-to-global: &quot;true&quot; # it is important to specify a label<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - get<br>  - list<br>  - watch</pre><pre># bob-clusterrole.yaml<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: bob-rules<br>  labels:<br>    aggregate-to-global: &quot;true&quot; # it is important to specify a label<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  - pods/logs<br>  - pods/exec<br>  verbs:<br>  - get<br>  - create<br>  - update<br>  - list<br>  - watch</pre><p>Let’s create an <em>Aggregated ClusterRole</em> that combines both of the above <em>ClusterRoles </em>based on their <em>Labels</em></p><pre># aggregated-clusterrole.yaml<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: aggragated-clusterrole<br>aggregationRule:<br>  clusterRoleSelectors:<br>  - matchLabels:<br>      aggregate-to-global: &quot;true&quot;<br>rules: [] # The controller automatically fills in the rules</pre><pre># create the aggregated clusterrole<br>kubectl apply -f aggregated-clusterrole.yaml</pre><pre># checkout the aggregated clusterrole<br>kubectl get clusterrole aggragated-clusterrole -o yaml<br><br># OUTPUT: we can see that both alice and bob clusterroles have been aggregated<br><br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: aggragated-clusterrole<br>aggregationRule:<br>  clusterRoleSelectors:<br>  - matchLabels:<br>      aggregate-to-global: &quot;true&quot;<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - get<br>  - list<br>  - watch<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  - pods/logs<br>  - pods/exec<br>  verbs:<br>  - get<br>  - create<br>  - update<br>  - list<br>  - watch</pre><h4>Conclusion</h4><p>The primary goal of this article was to give a deeper understanding of the Kubernetes Role Based Access Control (RBAC) through practical examples. This has been accomplished through giving a general overview about the k8s RBAC then getting more practical through different examples.</p><h4>References</h4><p>[1] <em>Using RBAC authorization</em> (2022) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">https://kubernetes.io/docs/reference/access-authn-authz/rbac/</a> (Accessed: 07 June 2023).</p><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a> <em>Authenticating</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">https://kubernetes.io/docs/reference/access-authn-authz/authentication/</a> (Accessed: 07 June 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff93887874d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Managing ServiceAccounts Access to the k8s API]]></title>
            <link>https://schh.medium.com/kubernetes-series-managing-serviceaccounts-access-to-the-k8s-api-5b682741fd91?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b682741fd91</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cka]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 12:54:23 GMT</pubDate>
            <atom:updated>2023-06-07T09:45:42.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yhAH092mxn2hx9hM.jpeg" /></figure><h4>Introduction</h4><p>This article covers the k8s API Access Control . Section 1 gives an overview of the Kubernetes API and Access Control functioning. Section 2 presents the <em>kubeconfig </em>file structure. Furthermore, Section 3 illustrates the creation of <em>serviceAccounts </em>and their<em> </em>associated <em>tokens </em>on k8s. Finally, this article ends with a conclusion.</p><h4>1. API Server Overview</h4><p>Kubernetes (k8s) in an API driven client/server architecture where the <em>API Server</em> exposes an HTTP API that lets users, different parts of the cluster, and external components communicate with one another.<a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/"> [1</a>]</p><blockquote>For a better understanding of this article, basic knowledge of k8s architecture is required.</blockquote><p>It is worth remembering that the <em>API server</em> is the single entry to the k8s cluster. It is the only component responsible for:</p><ul><li>Receiving requests</li><li>Forwarding requests to the rest of k8s components</li><li>Responding to requests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXtWlX4XoURETrdl.png" /><figcaption>Kubernetes Architecture</figcaption></figure><p>All k8s clusters have two categories of users: <em>service accounts </em>managed by k8s, and<em> normal users</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><blockquote>Kubernetes does not have objects which represent normal user accounts. Normal users cannot be added to a cluster through an API call.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><blockquote>In contrast, service accounts are users managed by the Kubernetes API. They are bound to specific namespaces, and created automatically by the API server or manually through API calls. Service accounts are tied to a set of credentials stored as <em>Secrets</em>, which are mounted into pods allowing in-cluster processes to talk to the Kubernetes API.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p>API requests are tied to either a <em>normal user</em> or a <em>service account</em>, or are treated as <em>anonymous requests</em>. This means every process inside or outside the cluster, from a human user typing kubectl on a workstation, to kubelets on nodes, to members of the control plane, must authenticate when making requests to the <em>API server</em>, or be treated as an anonymous user.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><blockquote>Anonymous requests are given a username of <em>system:anonymous</em> and a group of <em>system:unauthenticated</em>.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p>For a communication to be established with the <em>API-server</em>. The <em>API-server </em>performs authentication , authorization and admission control operations for each API request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sx5Al-UmjEd1NkZf.png" /><figcaption>Kubernetes Security <a href="https://kubernetes.io/docs/concepts/security/controlling-access/">[3]</a></figcaption></figure><p><strong>1.1 Authentication</strong></p><p>authentication can be established via multiple methods :<em> bearer tokens</em>, <em>basic credentials</em> (<em>i.e</em> <em>username and password</em>) or <em>certificates</em>. These methods are provided via plugins that try to associate the following attributes with the request:</p><ul><li><em>Username: a string which identifies the end user. Common values might be </em><em>kube-admin or </em><em>jane@example.com. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>UID: a string which identifies the end user and attempts to be more consistent and unique than username.</em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>Groups: a set of strings, each of which indicates the user’s membership in a named logical collection of users. Common values might be </em><em>system:masters or </em><em>devops-team.</em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>Extra fields: a map of strings to list of strings which holds additional information authorizers may find useful. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><p>You can enable multiple authentication methods at once. You should usually use at least two methods: <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><ul><li><em>service account tokens for service accounts</em></li><li><em>at least one other method for user authentication.</em></li></ul><p>For example:</p><ul><li>client certificate authentication method is enabled by passing the --client-ca-file=SOMEFILE option to <em>API server </em>manifest available under /etc/kubernetes/manifests/kube-apiserver.yaml .</li></ul><pre>cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep client-ca<br># OUTPUT:<br>- --client-ca-file=/etc/kubernetes/pki/ca.crt</pre><blockquote>Even though a normal user cannot be added via an API call, any user that presents a valid certificate signed by the cluster’s certificate authority (CA) is considered authenticated. In this configuration, the API Server determines the username from the <em>common name field in the subject of the certificate for example CN=Alice</em> . It determines the group from the <em>organization field of the certificate for example O=developers</em>.From there, the role based access control (RBAC) sub-system would determine whether the user is authorized to perform a specific operation on a resource.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fo_sl40Rit3jKdd0.png" /><figcaption>Kubernetes Caution <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[7]</a></figcaption></figure><p>Kubernetes Caution <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[6]</a></p><ul><li>The API server reads bearer tokens from a file when given the --token-auth-file=SOMEFILE option. When using bearer token authentication from an http client, the API server expects an Authorization header with a value of Bearer &lt;token&gt;.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><blockquote>Currently, tokens last indefinitely, and the token list cannot be changed without restarting the API server. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></blockquote><blockquote>The token file is a csv file with a minimum of 3 columns: token, user name, user uid, followed by optional group names. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></blockquote><pre>token,user,uid,&quot;group1,group2,group3&quot;</pre><ul><li>A <em>service account</em> is an automatically enabled authenticator that uses signed <em>bearer tokens</em> to verify requests. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><blockquote>Service accounts are usually created automatically by the API server and associated with pods running in the cluster through the <em>ServiceAccount</em> Admission Controller. Bearer tokens are mounted into pods at well-known locations, and allow in-cluster processes to talk to the API server. Accounts may be explicitly associated with pods using the <em>serviceAccountName</em> field of a <em>PodSpec</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></blockquote><blockquote>Service account bearer tokens are perfectly valid to use outside the cluster and can be used to create identities for long standing jobs that wish to talk to the Kubernetes API. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></blockquote><p><strong>1.2 Authorization</strong></p><p>authorization is established through RBAC (Role, RoleBinding, ClusterRole, ClusterRoleBinding) that specifies if the user can or cannot perform <em>CRUD operations (verbs)</em> on certain <em>k8s objects</em>.</p><p><strong>1.3 Admission control</strong></p><ul><li>admission control verifies if the CRUD operationperformed by the client on the k8s <em>object </em>is legitimate. For example, when the cluster has a ResourceQuota <em>object </em>that limits the number of podsthat can be created in a namespace dev to 2. If the user tries to create 3d pod then its request will be rejected.</li></ul><h4>2. The kubeconfig File</h4><p>When kubectl is used to communicate with the <em>API Server,</em> It uses a config file that contains <em>normal users</em> certificates and the cluster’s CA.</p><p>This file should be available under $HOME/.kube/config . It is accessible via the following commands: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">[5]</a></p><pre># command 1: <br>cat $HOME/.kube/config<br># command 2: <br>kubectl config view</pre><p>The $HOME/.kube/config file looks as follows:</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: xxxx<br>    server: https://x.x.x.x:6443<br>  name: test-cluster<br>contexts:<br>- context:<br>    cluster: test-cluster<br>    user: k8s-admin<br>  name: k8s-admin@test-cluster<br>current-context: k8s-admin@test-cluster<br>kind: Config<br>users:<br>- name: k8s-admin<br>  user:<br>    client-certificate-data: xx<br>    client-key-data: xxx</pre><p>It consists of the following attributes:</p><ul><li>clusters groups information about clusters. A cluster is defined by its name , its API endpoint (server) and its CA (<em>Certificate Authority</em>) certificate (certificate-authority-data) .</li><li>contexts group context information. A contextis used to group access parameters under a convenient name. Each contexthas three parameters: cluster, namespace, and user .</li></ul><blockquote><em>By default, the </em><em>kubectl command-line tool uses parameters from the </em><em>current contextto communicate with the </em>API Server. <em>current context indicates which </em><em>cluster and </em><em>user to use.</em></blockquote><pre># To choose the current context:<br>kubectl config use-context k8s-admin@dev-cluster</pre><ul><li>users define the clusters users. It defines the user name (name) along with his credentials: certificate (client-certificate-data) and client key (client-key-data) . Clients certificates should be signed by the Cluster CA in order for authentication to be established.</li></ul><h4>3. Service Accounts</h4><p>A <em>service account</em> provides an identity for processes that run in a <em>Pod</em>, and maps to a <em>ServiceAccount object</em>.<a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">[6]</a></p><p><em>ServiceAccounts </em>have names prefixed with system:serviceaccount:, and belong to groups that have names prefixed with system:serviceaccounts:.</p><p><em>ServiceAccounts </em>complete names follow the underlying pattern:</p><pre>system:serviceaccount:namespace:serviceaccountname<br><br># For example, a serviceaccount named prod-sa deployed<br># within the namespace production will be named as follows:<br><br>system:serviceaccount:production:prod-sa</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz6qcYvmiv9daf0QK0bQXA.png" /><figcaption>Kubernetes Note<a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/"> [7]</a></figcaption></figure><p>When <em>Pods </em>contact the <em>API server</em>, <em>Pods </em>authenticate as a particular <em>ServiceAccount.</em><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">[6]</a></p><p>Every Kubernetes <em>namespace </em>contains at least one <em>ServiceAccount.</em>the default <em>ServiceAccount </em>for each namespace is named default.</p><pre># Option 1: List service accounts within the default namespace<br>kubectl get serviceaccounts<br><br># Option 2: List service accounts within the default namespace<br>kubectl get sa <br>#OUTPUT<br>NAME      SECRETS   AGE<br>default   0         1d</pre><blockquote>If you do not specify a ServiceAccount when you create a Pod, Kubernetes automatically assigns the default ServiceAccount to the Pod.</blockquote><pre># create a pod  <br>kubectl run nginx --image=nginx<br><br># checkout the auto assigned service account <br>kubeclt get pod nginx -o yaml  | grep serviceAccount<br>#OUTPUT<br>  serviceAccount: default<br>  serviceAccountName: default<br>      - serviceAccountToken:<br> ...</pre><p>An application running inside a <em>Pod </em>can access the <em>Kubernetes API</em> using automatically mounted <em>service account</em> credentials: mounted into /var/run/secrets/kubernetes.io/serviceaccount/token. Its its level of access however, depends on the <em>RBAC </em>policies set for the cluster.</p><pre># display the nginx auto mounted serviceAccount token <br>kubectl exec -it nginx -- /bin/bash -c &quot;cat /var/run/secrets/kubernetes.io/serviceaccount/token&quot;</pre><p>If you don’t want the <em>kubelet </em>to automatically mount a <em>ServiceAccount’s </em>API credentials, you can specify automountServiceAccountToken: falseon</p><ul><li><em>The Pod’s </em><em>.spec</em></li></ul><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: my-pod<br>spec:<br>  serviceAccountName: build-robot<br>  automountServiceAccountToken: false<br>  ...</pre><ul><li>The <em>ServiceAccount:</em></li></ul><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: build-robot<br>automountServiceAccountToken: false<br>...</pre><blockquote>If both the ServiceAccount and the Pod’s <em>.spec</em> specify a value for <em>automountServiceAccountToken</em>, the Pod spec takes precedence.</blockquote><h4>4. Configure Service Accounts for Pods</h4><h4>4.1 With an auto mounted API Token</h4><p>First, let’s create our <em>ServiceAccount </em>object</p><pre># Create the nginx-sa.yaml file <br>kubectl create sa nginx-sa --dry-run=client -o yaml &gt; nginx-sa.yaml<br><br>#OUTPUT: content of nginx-sa.yaml<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: nginx-sa<br># Apply the yaml file to create the serviceAccount object<br>kubectl apply -f nginx-sa.yaml<br># Check if the serviceAccount has been created<br>kubectl get sa<br>#OUTPUT:<br>NAME       SECRETS   AGE<br>default    0         1d<br>nginx-sa   0         3s</pre><p>Next, let’s create our <em>Pod </em>object</p><pre># Create the nginx-pod.yaml file <br>kubectl run nginx --image=nginx --dry-run=client -o yaml &gt; nginx-pod.yaml<br><br># OUTPUT: content of nginx-pod.yaml<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  restartPolicy: Always</pre><p>Let’s edit the nginx-pod.yamlfile to attach the created<em> </em><em>nginx-saServiceAccount </em>to the nginx <em>Pod</em></p><pre># edit nginx-pod.yaml: add serviceAccountName: nginx-sa<br><br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  serviceAccountName: nginx-sa<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  restartPolicy: Always</pre><p>Let’s create the <em>Pod</em></p><pre>kubectl apply -f nginx-pod.yaml</pre><p>Let’s verify if the <em>ServiceAccount </em>has been attached to the <em>Pod</em></p><pre>kubectl get pod nginx -o yaml | grep serviceAccount<br><br>#OUTPUT:<br>  serviceAccount: nginx-sa<br>  serviceAccountName: nginx-sa<br>      - serviceAccountToken:<br>  ...</pre><p>Let’s display the<em> ServiceAccount </em>token that has been auto mounted to the <em>Pod</em></p><pre># display the auto-mounted serviceAccount token <br>kubectl exec -it nginx -- /bin/bash -c &quot;cat /var/run/secrets/kubernetes.io/serviceaccount/token&quot;</pre><p>Finally, Let’s use this auto-mounted token to communicate with the <em>API Server</em></p><pre># bash into the pod <br>kubectl exec -it nginx -- /bin/bash<br><br># export the token as an environment variable within the pod <br>export token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)<br># curl the api server using the auto mounted token <br>curl -k https://kubernetes.default/api/v1/pods --oauth2-bearer $token<br># OUTPUT <br>{<br>  &quot;kind&quot;: &quot;Status&quot;,<br>  &quot;apiVersion&quot;: &quot;v1&quot;,<br>  &quot;metadata&quot;: {},<br>  &quot;status&quot;: &quot;Failure&quot;,<br>  &quot;message&quot;: &quot;pods is forbidden: User \&quot;system:serviceaccount:default:nginx-sa\&quot; cannot list resource \&quot;pods\&quot; in API group \&quot;\&quot; at the cluster scope&quot;,<br>  &quot;reason&quot;: &quot;Forbidden&quot;,<br>  &quot;details&quot;: {<br>    &quot;kind&quot;: &quot;pods&quot;<br>  },<br>  &quot;code&quot;: 403<br>}</pre><p>We can see from the output error message that the <em>nginx</em> has been successfully authenticated but the authorization operation was not successful because the user <em>nginx Pod</em>, identified as user : <em>system:serviceaccount:default:nginx-sa </em>doesn’t have permissions to query k8s <em>objects. </em>Permissions are managed in k8s using RBAC. They’ll be discussed in the next article.</p><h4>4.2 Without an auto mounted API Token</h4><p>First, let’s create our <em>ServiceAccount </em>object</p><pre># Create the nginx-sa.yaml file <br>kubectl create sa nginx-sa --dry-run=client -o yaml &gt; nginx-sa.yaml<br><br>#OUTPUT: content of nginx-sa.yaml<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: nginx-sa</pre><p>Next, let’s edit <em>nginx-sa.yaml </em>file to add the setting automountServiceAccountToken: false</p><pre>#OUTPUT: content of nginx-sa.yaml<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: nginx-sa<br>automountServiceAccountToken: false</pre><p>Let’s apply the <em>ServiceAccount </em>object</p><pre># Apply the yaml file to create the serviceAccount object<br>kubectl apply -f nginx-sa.yaml<br><br># Check if the serviceAccount has been created<br>kubectl get sa<br>#OUTPUT:<br>NAME       SECRETS   AGE<br>default    0         1d<br>nginx-sa   0         3s</pre><p>Next, let’s create our <em>Pod </em>object</p><pre># Create the nginx-pod.yaml file <br>kubectl run nginx --image=nginx --dry-run=client -o yaml &gt; nginx-pod.yaml<br><br># OUTPUT: content of nginx-pod.yaml<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  restartPolicy: Always</pre><p>Let’s edit the nginx-pod.yamlfile to attach the created<em> </em><em>nginx-saServiceAccount </em>to the nginx <em>Pod</em></p><pre># edit nginx-pod.yaml: add serviceAccountName: nginx-sa<br><br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  serviceAccountName: nginx-sa<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  restartPolicy: Always</pre><p>Let’s create the <em>Pod</em></p><pre>kubectl apply -f nginx-pod.yaml</pre><p>Let’s verify if the <em>ServiceAccount </em>has been attached to the <em>Pod</em></p><pre>kubectl get pod nginx -o yaml | grep serviceAccount<br><br>#OUTPUT:<br>  serviceAccount: nginx-sa<br>  serviceAccountName: nginx-sa<br>      - serviceAccountToken:<br>  ...</pre><p>Let’s display the<em> ServiceAccount </em>token that has been auto mounted to the <em>Pod</em></p><pre># display the auto-mounted serviceAccount token <br>kubectl exec -it nginx -- /bin/bash -c &quot;cat /var/run/secrets/kubernetes.io/serviceaccount/token&quot;<br><br># OUTPUT<br>cat: /var/run/secrets/kubernetes.io/serviceaccount/token: No such file or directory</pre><p>We can see that due to the usage of automountServiceAccountToken: false no token has been created and mounted to the Pod.</p><h4>4.2.1 Manually create an API token for a ServiceAccount</h4><p>Let’s create a time-limited API token for the <em>ServiceAccount </em>nginx-sausing kubectl:</p><pre>kubectl create token nginx-sa --duration 1h</pre><p>This token can be copied and mounted to any pod under /var/run/secrets/kubernetes.io/serviceaccount/token, It will allow the pod to authenticate as nginx-sa <em>ServiceAccount</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTn76pj7EL3hq-n5Yjb-2g.png" /><figcaption>Kubernetes Recommendation <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">[6]</a></figcaption></figure><h4>Conclusion</h4><p>The primary goal of this article was to give a deeper understanding of the Kubernetes API Access Control functioning through practical examples. This has been accomplished through giving a general overview about the k8s API then getting more practical through different examples using the curl and kubectlcommands.</p><h4>References</h4><p><a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">[1</a>] <em>The Kubernetes Api</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">https://kubernetes.io/docs/concepts/overview/kubernetes-api/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a> <em>Authenticating</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">https://kubernetes.io/docs/reference/access-authn-authz/authentication/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/concepts/security/controlling-access/">[3]</a> <em>Controlling access to the Kubernetes Api</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/security/controlling-access/">https://kubernetes.io/docs/concepts/security/controlling-access/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/tasks/administer-cluster/certificates/">[4]</a> <em>Generate certificates manually</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/tasks/administer-cluster/certificates/">https://kubernetes.io/docs/tasks/administer-cluster/certificates/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">[5]</a> <em>Configure access to multiple clusters</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">[6]</a> <em>Configure service accounts for Pods</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/</a> (Accessed: 06 June 2023).</p><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[7] </a><em>Using RBAC authorization</em> (2022) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">https://kubernetes.io/docs/reference/access-authn-authz/rbac/</a> (Accessed: 07 June 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b682741fd91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Managing Normal Users Access to the k8s API]]></title>
            <link>https://schh.medium.com/kubernetes-series-managing-normal-users-access-to-the-k8s-api-420fe09c34c0?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/420fe09c34c0</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ckad]]></category>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 16:16:09 GMT</pubDate>
            <atom:updated>2023-06-07T09:10:49.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HULQWZUZeFqnicn1.jpeg" /></figure><h4>Introduction</h4><p>This article covers the k8s API Access Control . Section 1 gives an overview of the Kubernetes API and Access Control functioning. Section 2 presents the <em>kubeconfig </em>file structure. Furthermore, Section 3 illustrates the creation of normal users on k8s. Finally, this article ends with a conclusion.</p><h4>1. API Server Overview</h4><p>Kubernetes (k8s) in an API driven client/server architecture where the <em>API Server</em> exposes an HTTP API that lets users, different parts of the cluster, and external components communicate with one another.<a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/"> [1</a>]</p><blockquote>For a better understanding of this article, basic knowledge of k8s architecture is required.</blockquote><p>It is worth remembering that the <em>API server</em> is the single entry to the k8s cluster. It is the only component responsible for:</p><ul><li>Receiving requests</li><li>Forwarding requests to the rest of k8s components</li><li>Responding to requests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VR1GG9NbOJOXSv1R.png" /><figcaption>Kubernetes Architecture</figcaption></figure><p>All k8s clusters have two categories of users: <em>service accounts </em>managed by k8s, and<em> normal users</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><blockquote>Kubernetes does not have objects which represent normal user accounts. Normal users cannot be added to a cluster through an API call.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><blockquote>In contrast, service accounts are users managed by the Kubernetes API. They are bound to specific namespaces, and created automatically by the API server or manually through API calls. Service accounts are tied to a set of credentials stored as <em>Secrets</em>, which are mounted into pods allowing in-cluster processes to talk to the Kubernetes API.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p>API requests are tied to either a <em>normal user</em> or a <em>service account</em>, or are treated as <em>anonymous requests</em>. This means every process inside or outside the cluster, from a human user typing kubectl on a workstation, to kubelets on nodes, to members of the control plane, must authenticate when making requests to the <em>API server</em>, or be treated as an anonymous user.<a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><blockquote>Anonymous requests are given a username of <em>system:anonymous</em> and a group of <em>system:unauthenticated</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p>For a communication to be established with the <em>API-server</em>. The <em>API-server </em>performs authentication , authorization and admission control operations for each API request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZdlPvFCSBvoHwxBjflmnA.png" /><figcaption>Kubernetes Security <a href="https://kubernetes.io/docs/concepts/security/controlling-access/">[3]</a></figcaption></figure><p><strong>1.1 Authentication</strong></p><p>authentication can be established via multiple methods :<em> bearer tokens</em>, <em>basic credentials</em> (<em>i.e</em> <em>username and password</em>) or <em>certificates</em>. These methods are provided via plugins that try to associate the following attributes with the request:</p><ul><li><em>Username: a string which identifies the end user. Common values might be </em><em>kube-admin or </em><em>jane@example.com. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>UID: a string which identifies the end user and attempts to be more consistent and unique than username.</em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>Groups: a set of strings, each of which indicates the user’s membership in a named logical collection of users. Common values might be </em><em>system:masters or </em><em>devops-team.</em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li><li><em>Extra fields: a map of strings to list of strings which holds additional information authorizers may find useful. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><p>You can enable multiple authentication methods at once. You should usually use at least two methods: <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><ul><li><em>service account tokens for service accounts</em></li><li><em>at least one other method for user authentication.</em></li></ul><p>For example:</p><ul><li>client certificate authentication method is enabled by passing the --client-ca-file=SOMEFILE option to API server manifest available under /etc/kubernetes/manifests/kube-apiserver.yaml .</li></ul><pre>cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep client-ca<br><br># OUTPUT:<br>- --client-ca-file=/etc/kubernetes/pki/ca.crt</pre><blockquote>Even though a normal user cannot be added via an API call, any user that presents a valid certificate signed by the cluster’s certificate authority (CA) is considered authenticated. In this configuration, the API Server determines the username from the <em>common name field in the subject of the certificate for example CN=Alice</em> . It determines the group from the organization field of the certificate for example O=developers.From there, the role based access control (RBAC) sub-system would determine whether the user is authorized to perform a specific operation on a resource.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB_WLv9ZS9QPgb6O8Q16OA.png" /><figcaption>Kubernetes Caution <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[6]</a></figcaption></figure><ul><li>The API server reads bearer tokens from a file when given the --token-auth-file=SOMEFILE option. When using bearer token authentication from an http client, the API server expects an Authorization header with a value of Bearer &lt;token&gt;.<em> </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><blockquote>Currently, tokens last indefinitely, and the token list cannot be changed without restarting the API server. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p><em>The token file is a csv file with a minimum of 3 columns: token, user name, user uid, followed by optional group names. </em><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></p><pre>token,user,uid,&quot;group1,group2,group3&quot;</pre><ul><li>A service account is an automatically enabled authenticator that uses signed bearer tokens to verify requests. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a></li></ul><blockquote>Service accounts are usually created automatically by the API server and associated with pods running in the cluster through the <em>ServiceAccount</em> Admission Controller. Bearer tokens are mounted into pods at well-known locations, and allow in-cluster processes to talk to the API server. Accounts may be explicitly associated with pods using the <em>serviceAccountName</em> field of a <em>PodSpec</em>. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><blockquote>Service account bearer tokens are perfectly valid to use outside the cluster and can be used to create identities for long standing jobs that wish to talk to the Kubernetes API. <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/"><em>[2]</em></a></blockquote><p><strong>1.2 Authorization</strong></p><p>authorization is established through RBAC (Role, RoleBinding, ClusterRole, ClusterRoleBinding) that specifies if the user can or cannot perform <em>CRUD operations (verbs)</em> on certain <em>k8s objects</em>.</p><p><strong>1.3 Admission control</strong></p><ul><li>admission control verifies if the CRUD operationperformed by the client on the k8s <em>object </em>is legitimate. For example, when the cluster has a ResourceQuota <em>object </em>that limits the number of podsthat can be created in a namespace dev to 2. If the user tries to create 3d pod then its request will be rejected.</li></ul><h4>2. The kubeconfig File</h4><p>When kubectl is used to communicate with the <em>API Server,</em> It uses a config file that contains <em>normal users</em> certificates and the cluster’s CA.</p><p>This file should be available under $HOME/.kube/config . It is accessible via the following commands: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">[5]</a></p><pre># command 1: <br>cat $HOME/.kube/config<br># command 2: <br>kubectl config view</pre><p>The $HOME/.kube/config file looks as follows:</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: xxxx<br>    server: https://x.x.x.x:6443<br>  name: test-cluster<br>contexts:<br>- context:<br>    cluster: test-cluster<br>    user: k8s-admin<br>  name: k8s-admin@test-cluster<br>current-context: k8s-admin@test-cluster<br>kind: Config<br>users:<br>- name: k8s-admin<br>  user:<br>    client-certificate-data: xx<br>    client-key-data: xxx</pre><p>It consists of the following attributes:</p><ul><li>clusters groups information about clusters. A cluster is defined by its name , its API endpoint (server) and its CA (<em>Certificate Authority</em>) certificate (certificate-authority-data) .</li><li>contexts group context information. A contextis used to group access parameters under a convenient name. Each contexthas three parameters: cluster, namespace, and user .</li></ul><blockquote>By default, the kubectl command-line tool uses parameters from the current contextto communicate with the <em>API Server. </em>current context indicates which cluster and user to use.</blockquote><pre># To choose the current context:<br>kubectl config use-context k8s-admin@dev-cluster</pre><ul><li>users define the clusters users. It defines the user name (name) along with his credentials: certificate (client-certificate-data) and client key (client-key-data) . Clients certificates should be signed by the Cluster CA in order for authentication to be established.</li></ul><h4>3. Manage Access to the API Server: Normal Users</h4><p>Let’s create a <em>normal user</em> and grant him access to the k8s <em>API Server</em> <a href="https://kubernetes.io/docs/tasks/administer-cluster/certificates/">[4]</a> <a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">[5]</a></p><pre># login as sudo <br>sudo su<br><br># Let&#39;s create an ubuntu user<br>adduser test<br><br># Generate a private key for test.<br>openssl genrsa -out test.key 2048<br><br># Generate a Certificate Signing Request (CSR) for test<br>openssl req -new -key test.key -out test.csr -subj &quot;/CN=test/O=devops&quot;<br><br># Generate a Certificate signed by the Cluster CA for the user test with a validity period of 30 days<br>openssl x509 -req -in test.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out test.crt -days 30<br><br># Move the generated credentials to test user home<br>mv test.key /home/test/<br>mv test.crt /home/test/<br>chown test:test /home/test/test.crt /home/test/test.key</pre><p><strong>3.1 Curl the API Server</strong></p><blockquote>When <em>curl</em> is used to communicate with the API Server . a user passes his certificates and the cluster’s CA certificate on command line as follows:</blockquote><pre># login as root<br>sudo su<br><br># export the API-Server endpoint<br>export server=https://x.x.x.x:6443<br><br># Curl the API-Server endpoint with test user credentials <br>curl $server/api/v1/pods/ --cacert /etc/kubernetes/pki/ca.crt --cert /home/test/test.crt --key /home/test/test.key<br><br># OUTPUT:<br>{<br>  &quot;kind&quot;: &quot;Status&quot;,<br>  &quot;apiVersion&quot;: &quot;v1&quot;,<br>  &quot;metadata&quot;: {},<br>  &quot;status&quot;: &quot;Failure&quot;,<br>  &quot;message&quot;: &quot;pods is forbidden: User \&quot;test\&quot; cannot list resource \&quot;pods\&quot; in API group \&quot;\&quot; at the cluster scope&quot;,<br>  &quot;reason&quot;: &quot;Forbidden&quot;,<br>  &quot;details&quot;: {<br>    &quot;kind&quot;: &quot;pods&quot;<br>  },<br>  &quot;code&quot;: 403<br>}</pre><p>We can see from the output error message that the user test has been successfully authenticated but the authorization operation was not successful because the user doesn’t have permissions to query <em>k8s objects.</em></p><blockquote>Permissions are managed in k8s using RBAC.</blockquote><p><strong>3.2 Configure the kubeconfig File</strong></p><blockquote>When <em>kubectl</em> is used, It uses a <em>config</em> file which contains user certificates and the cluster’s CA. This file should be available under <em>$HOME/.kube/config</em></blockquote><p>Let’s create a userwithin $HOME/.kube/config file.</p><pre># specify credentials for user test within the config file : users attribute<br><br>kubectl config set-credentials test \<br>--client-certificate=/home/test/test.crt \<br>--client-key=/home/test/test.key</pre><p>Let’s check the configured user lines in $HOME/.kube/config file</p><pre># Since we&#39;re performing operations as root, the file will be located under /root/.kube/config<br><br>apiVersion: v1<br>clusters: null<br>contexts: null<br>current-context: &quot;&quot;<br>kind: Config<br>preferences: {}<br>users:<br>- name: test<br>  user:<br>    client-certificate: /home/test/test.crt<br>    client-key: /home/test/test.key</pre><p>Let’s create a contextwithin $HOME/.kube/config file.</p><pre>kubectl config set-context test@test-cluster \<br>--cluster=test-cluster \<br>--namespace=test \<br>--user=test</pre><p>Let’s check the configured context lines in $HOME/.kube/config file</p><pre># Since we&#39;re performing operations as root, the file will be located under /root/.kube/config<br>apiVersion: v1<br>clusters: null<br>contexts:<br>- context:<br>    cluster: test-cluster<br>    namespace: test<br>    user: test<br>  name: test@test-cluster<br>current-context: &quot;&quot;<br>kind: Config<br>preferences: {}<br>users:<br>- name: test<br>  user:<br>    client-certificate: /home/test/test.crt<br>    client-key: /home/test/test.key</pre><p>Finally, let’s set information about the k8s cluster we want to connect to:</p><pre>kubectl config set-cluster test-cluster \<br>--server=https://x.x.x.x:6443 \<br>--embed-certs \<br>--certificate-authority=/etc/kubernetes/pki/ca.crt</pre><p>Let’s check the configured clusterlines in $HOME/.kube/config file</p><pre># Since we&#39;re performing operations as root, the file will be located under /root/.kube/config<br>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: xxxxx<br>    server: https://x.x.x.x:6443<br>  name: test-cluster<br>contexts:<br>- context:<br>    cluster: test-cluster<br>    namespace: test<br>    user: test<br>  name: test@test-cluster<br>current-context: &quot;&quot;<br>kind: Config<br>preferences: {}<br>users:<br>- name: test<br>  user:<br>    client-certificate: /home/test/test.crt<br>    client-key: /home/test/test.key</pre><p>Let’s Display configured information within the $HOME/.kube/config file</p><pre># move the configured config file under the home of test user<br><br>mv /root/.kube/ /home/test/<br>sudo chown -R test:test /home/test/</pre><pre># login as test user<br>sudo su test<br><br>kubectl config get-contexts<br>kubectl config set current-context &quot;test@test-cluster&quot;<br>kubectl config current-context</pre><p>List pods using kubectl command that uses $HOME/.kube/config file.</p><pre>kubectl --context=test@test-cluster get pod<br><br>#Output: <br>Error from server (Forbidden): pods is forbidden: User &quot;test&quot; cannot list resource &quot;pods&quot; in API group &quot;&quot; in the namespace &quot;test&quot;</pre><p>We can see from the output error message that the user test has been successfully authenticated but the authorization operation was not successful because the user doesn’t have permissions to access pods.</p><p>Permissions are managed in k8s using RBAC.</p><h4>Conclusion</h4><p>The primary goal of this article was to give a deeper understanding of the Kubernetes API Access Control functioning through practical examples. This has been accomplished through giving a general overview about the k8s API then getting more practical through different examples using the curl and kubectlcommands.</p><h4>References</h4><p><a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">[1</a>] <em>The Kubernetes Api</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">https://kubernetes.io/docs/concepts/overview/kubernetes-api/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">[2]</a> <em>Authenticating</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">https://kubernetes.io/docs/reference/access-authn-authz/authentication/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/concepts/security/controlling-access/">[3]</a> <em>Controlling access to the Kubernetes Api</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/concepts/security/controlling-access/">https://kubernetes.io/docs/concepts/security/controlling-access/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/tasks/administer-cluster/certificates/">[4]</a> <em>Generate certificates manually</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/tasks/administer-cluster/certificates/">https://kubernetes.io/docs/tasks/administer-cluster/certificates/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">[5]</a> <em>Configure access to multiple clusters</em> (2023) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/">https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/</a> (Accessed: 05 June 2023).</p><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">[6] </a><em>Using RBAC authorization</em> (2022) <em>Kubernetes</em>. Available at: <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">https://kubernetes.io/docs/reference/access-authn-authz/rbac/</a> (Accessed: 07 June 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420fe09c34c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Getting practical with the Kubernetes API]]></title>
            <link>https://levelup.gitconnected.com/kubernetes-series-getting-practical-with-the-kubernetes-api-9481d6b176ea?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/9481d6b176ea</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ckad]]></category>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 16:59:06 GMT</pubDate>
            <atom:updated>2023-06-09T13:31:48.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6WBuqM6cqO0mJC-NY7aUA.jpeg" /></figure><h4>Introduction</h4><p>This articles explains the structure and the functioning of Kubernetes API. Section 1 gives an overview of the Kubernetes API. Section 2 explains the requirements needed to follow up with this article . Furthermore, Section 3 explains the Kubernetes API terminology. Moreover, Section 4 goes up through some practical examples. Section 5 covers more advanced queries. Finally, this article ends with a conclusion.</p><h4>1. API Overview</h4><p>Kubernetes (k8s) in an API driven client/server architecture where the <em>API Server</em> exposes an HTTP API that lets end users, different parts of your cluster, and external components communicate with one another.<a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/"> [1</a>]</p><blockquote>For a better understanding of this article, basic knowledge of k8s architecture is required.</blockquote><p>It is worth remembering that the <em>API server</em> is the single entry to the k8s cluster. It is the only component responsible for receiving clients queries. and forwarding them to the rest of k8s components then responding to the clients.</p><p>The k8s components that the <em>API server</em> communicates with are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N7oRDhRDhfIFy0PX.png" /><figcaption>Kubernetes Architecture</figcaption></figure><ul><li><em>The Controller-Manager </em>which contains k8s controllers (deployments, statefulsetsetc.) responsible for keeping the current state of k8s <em>objects </em>in sync with the declared desired state.</li><li><em>The etcd </em>a consistent and highly-available b+tree key-value store. that logs the cluster’s state, networking and other important information about the cluster.</li><li><em>The Kube Scheduler </em>which determines based on the information stored in the <em>etcd </em>on which node to schedule a pod.</li></ul><p>k8s clients (users) can query and manipulate the state of API <em>objects </em>in k8s using client libraries, or by making REST requests. For example, the following can be used:</p><ul><li>kubectl is a command line tool provided by k8s. It establishes communication with the <em>API server </em>and makes API calls with it in our behalf so that we can easily access and manage k8s API <em>resources</em>.</li><li>curl is a command line tool designed to exchange data with a server. In k8s, the server is the k8s <em>API server</em>.</li></ul><blockquote>The default serialization for k8s API calls is JSON. Eventhough we tend to use YAML format, It is important to know that YAML is converted to and from JSON.</blockquote><p>For a communication to be established with the <em>API-server</em>. The <em>API-server </em>performs authentication , authorization and admission control operations for each API call.</p><ul><li>authentication is established when a client presents a valid TLS certificate ( a valid TLS certificate is a certificate signed by the cluster’s CA and trusted by the <em>API server</em> ).</li><li>authorization is established through RBAC (Role, RoleBinding, ClusterRole, ClusterRoleBinding) that specifies if the client can or cannot perform <em>CRUD operations (verbs)</em> on certain <em>k8s objects</em>. In this step, the client identity is determined from the common name field in the subject of the certificate for example CN=Alice .</li><li>admission control is established if the CRUD operationperformed by the client on the k8s <em>object </em>is legitimate. For example, when the cluster has a ResourceQuota <em>object </em>that limits the number of podsthat can be created in a namespace dev to 2. If the user tries to create 3d pod then its request will be rejected.</li></ul><blockquote>It is worth noting that k8s does not have objects which represent clients accounts. clients cannot be added to a cluster through an API call.</blockquote><h4>2. Requirements</h4><blockquote><em>When </em><em>curl is used. a client passes its TLS certificates and the cluster’s CA on command line as follows:</em></blockquote><pre>curl $server/api/v1/ --cacert ./ca.crt --cert ./client.crt --key ./client.key</pre><blockquote><em>When </em><em>kubectl is used, It uses a </em><em>config file already configured by </em><em>k8s admin which contains clients TLS certificates and the cluster’s CA. This file should be available under </em><em>$HOME/.kube/config</em></blockquote><pre>cat $HOME/.kube/config</pre><p>For a better understanding of k8s APIs , curl command will be used through out this article.</p><p>For the seek of simplicity and to avoid dealing with HTTPS and TLS certificates for authentication. The kubectl proxy command will be used to create a proxy server.</p><blockquote>The <em>kubectl proxy </em>command creates a proxy server or application-level gateway between localhost and the Kubernetes API server. It also allows serving static content over specified HTTP path. All incoming data enters through one port and gets forwarded to the remote Kubernetes API server port.</blockquote><ul><li>To create a proxy server, simply run:</li></ul><pre>kuebctl proxy</pre><ul><li>To communicate with the API Server, simply run:</li></ul><pre>curl http://127.0.0.1:8001</pre><ul><li>For a better JSON formatting and visualization, the jq command will be used as follows:</li></ul><pre>curl http://127.0.0.1:8001 | jq &#39;.&#39;</pre><h4>3. API terminology</h4><p><strong>3.1. API Resources Types and Objects</strong></p><p>Kubernetes API operates in term of <em>resources. </em>But what is a <em>resource </em>?</p><p>A <em>resource </em>is a unique representation of a k8s<em> object. </em>Each <em>resource </em>has its own representation. This representation is known as a <em>resource type</em> (<em>kind </em>).</p><p>A <em>resource type</em> (<em>kind </em>) can be pods, configmaps, services etc. You can see from the underlying code that <em>resources </em>of different <em>kinds </em>are represented differently.</p><pre># an example of an nginx pod resource<br># kubectl run nginx --image=nginx --dry-run -o yaml &gt; pod.yaml<br># pod.yaml<br><br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  containers:<br>  - image: nginx<br>    name: nginx<br>  restartPolicy: Always</pre><pre># an example of an nginx configmap resource<br># kubectl create configmap nginx --dry-run -o yaml &gt; configmap.yaml<br># configmap.yaml<br><br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: nginx</pre><p>A list of instances of a <em>resource type </em>is known as a <em>collection. </em>Moreover, a single instance of a<em> resource type</em> is called a <em>resource</em>, and also usually represents an <em>object.</em></p><blockquote>All <em>object</em>s created via the API have a unique object name to allow idempotent creation and retrieval.</blockquote><p><strong>3.2. API Resources Verbs</strong></p><p>Different <em>resource types </em>exposes different<em> CRUD verbs</em> (create, read, update,delete) that can be performed on <em>objects</em> they manage. Almost all <em>object resource types</em> support the standard HTTP verbs — GET, POST, PUT, PATCH, and DELETE.</p><p>Kubernetes also uses its own verbs, which are often written lowercase to distinguish them from HTTP verbs:list ,get , watch , create , update , delete , create , patch</p><ul><li>list : returns a collection of resources.</li><li>get : returns a single resource</li><li>watch : continuously list and get resources in real time. It is like the Linux watch command. Thus, when defining RBACverbs, it is worth noting that watch cannot be put alone. It must be put along with get and list verbs. If you sent an HTTP GET request with the ?watch query parameter, k8s calls this a watchand not a get .</li><li>For PUT requests, Kubernetes internally classifies these as either createor updatebased on the state of the existing object.</li></ul><p><strong>3.3. API Groups</strong></p><p>Different <em>resource types </em>belong to different <em>API groups. </em>The <em>API group</em> is specified in a REST path and in the apiVersion field of a serialized <em>object</em>.</p><p>The <em>API groups ca</em>n be classified as either <em>core groups</em> or <em>named groups.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEUm499TFWK4bvoe6_e9qA.png" /><figcaption>k8s API Groups Categories</figcaption></figure><p><strong>3.3.1. The <em>core </em>group</strong></p><p>The <em>core </em>group is found at REST path /api/v1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQnx7f_hgNcFop_YOu1nlg.png" /><figcaption>k8s API Core Group</figcaption></figure><p>The core group is specified as part of the apiVersion field. For example: apiVersion: v1.</p><pre># an example of an nginx configmap resource<br>apiVersion: v1  # here<br>kind: ConfigMap<br>metadata:<br>  name: nginx</pre><p><strong>3.3.2 The <em>named </em>group</strong></p><p>The <em>named </em>groups are at REST path /apis/$GROUP_NAME/$VERSION/$PLURALNAME</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d-DXqrAqFlpS9U23Ya2uA.png" /><figcaption>k8s API Named Group</figcaption></figure><p>The <em>named </em>group is specified as part of the apiVersion field as apiVersion: $GROUP_NAME/$VERSION . For example:apiVersion: batch/v1</p><pre>- apiVersion: batch/v1 #here<br>  kind: CronJob<br>  metadata:</pre><p>Each <em>API group </em>within the<em> named </em>group can have different versions.</p><ul><li>Alpha: (i.e v1alpha1) This version present many bugs as it is not tested yet. it is disabled by default. Alpha features are susceptible to change or disappear at any time.</li><li>Beta: (i.e v1beta1) This is enabled by default as it has been tested. but It still presents some bugs.</li><li>Stable: (i.e v1) This version is stable. It is enabled by default.</li></ul><blockquote>Resources type <em>of the</em> core <em>group are always under the </em>v1 <em>version</em>.</blockquote><blockquote><em>Make sure to always use </em>objects <em>that belong to a </em><em>stable </em>API group<em>. For example:</em></blockquote><blockquote><em>We have an </em>object <em>of </em>resource type <em>CronJob that belongs to the </em>API group <em>batch classified under the </em>named<em> group and available under two version: </em><em>v1 and </em><em>v1beta1 . Make sure, in such case, to always use </em><em>v1 if it is available ( by default, k8s consider </em><em>v1 as its preferred version ).</em></blockquote><pre>- apiVersion: batch/v1        # this is the perefered version<br>  kind: CronJob<br>  metadata:<br><br>... <br>- apiVersion: batch/v1alpha1  # this is an available version but not the most<br>                              # perefered <br>  kind: CronJob<br>  metadata:</pre><h4>4. API Calls Exploration</h4><p>Let’s list the available k8s API in our k8s cluster</p><pre>curl http://127.0.0.1:8001 | jq &#39;.&#39;<br><br># OUTPUT : <br>    &quot;/api&quot;,<br>    &quot;/api/v1&quot;,<br>    &quot;/apis&quot;,<br>    &quot;/apis/&quot;,<br>    &quot;/apis/batch&quot;,<br>    &quot;/apis/batch/v1&quot;,<br>    &quot;/apis/storage.k8s.io&quot;,<br>    &quot;/apis/storage.k8s.io/v1&quot;,<br>    ...<br>    ...<br> <br># REMEMBER :<br># core group:  /api/v1<br># named group: /apis/$GROUP_NAME/$VERSION<br># EXPLANATION : <br># We can see that we have different resource types grouped into different <br># groups, Some of these groups are made available under the core group and <br># others under the named group and are available under a specific version. <br># EXAMPLE : <br># The resource group: batch is available under the named group (apis). it<br># groups a certain resource types of version v1.</pre><p><strong>4.1. The <em>core </em>Group</strong></p><ul><li>Let’s explore an API core group</li></ul><pre>curl http://127.0.0.1:8001/api | jq &#39;.&#39;<br><br># OUTPUT <br>{<br>  &quot;kind&quot;: &quot;APIVersions&quot;,<br>  &quot;versions&quot;: [<br>    &quot;v1&quot;<br>  ],<br>  &quot;serverAddressByClientCIDRs&quot;: [<br>    {<br>      &quot;clientCIDR&quot;: &quot;X.X.X.X/x&quot;,<br>      &quot;serverAddress&quot;: &quot;X.X.X.X/X&quot;<br>    }<br>  ]<br>}<br># EXPLANATION <br># we can see that the only version available for the resource types under<br># this API GROUP is v1. Thus, all resources of these group are of version v1.</pre><ul><li>Let’s list <em>resource-types</em> of version <em>v1</em>under the<em> core API group.</em></li></ul><pre>curl http://127.0.0.1:8001/api/v1 | jq &#39;.resources[].name&#39;<br><br># OUTPUT : <br>...<br>&quot;configmaps&quot;<br>...<br>&quot;pods&quot;<br>&quot;namespaces&quot;<br>...</pre><ul><li>Let’s list <em>collection </em>or<em> objects </em>or<em> resources </em>available under the<em> resource type </em><em>pods</em></li></ul><pre># get pods<br>curl http://127.0.0.1:8001/api/v1/pods | jq  .items[].metadata.name<br><br># get information about a specific pod using its name<br>curl http://127.0.0.1:8001/api/v1/pods/ | jq  &#39;.items[].metadata |  select(.name==&quot;nginx-a1Gv0&quot;)&#39;</pre><ul><li>Let’s list <em>collection </em>or<em> objects </em>or<em> resources </em>available under the<em> resource type </em><em>namespace</em></li></ul><pre># get namespaces<br>curl http://127.0.0.1:8001/api/v1/namespaces | jq  .items[].metadata.name<br><br># get information about a specific namespace using its name<br> curl http://127.0.0.1:8001/api/v1/namespaces/proxy| jq .<br># get a list of existing pods within the selected namespace: proxy<br># you can see that we&#39;ve used a combination of the namespaces and pods resource types<br> curl http://127.0.0.1:8001/api/v1/namespaces/proxy/pods | jq .items[].metadata.name<br># get information of a specific pod within the selected namespace : proxy<br> curl http://127.0.0.1:8001/api/v1/namespaces/proxy/pods | jq  &#39;.items[].metadata |  select(.name==&quot;nginx-a1Gv0&quot;)&#39;</pre><p>You can derive from the above examples that information about the pod nginx-a1Gv0 have been obtained using different REST Paths:</p><pre># get information of a specific pod within the selected namespace : proxy<br>curl http://127.0.0.1:8001/api/v1/namespaces/proxy/pods | jq  &#39;.items[].metadata |  select(.name==&quot;nginx-a1Gv0&quot;)&#39;<br># get information about a specific pod using its name<br>curl http://127.0.0.1:8001/api/v1/pods/ | jq  &#39;.items[].metadata |  select(.name==&quot;nginx-a1Gv0&quot;)&#39;</pre><p><strong>4.2. The <em>named </em>Group</strong></p><ul><li>Let’s list the <em>API groups </em>made available under the <em>named </em>group</li></ul><pre># REMEMBER :<br># core group:  /api/v1<br># named group: /apis/$GROUP_NAME/$VERSION<br># Let&#39;s list the groups available under the named group. <br>curl http://127.0.0.1:8001/apis/| jq .groups[].name<br><br># OUTPUT : <br>...<br>&quot;apps&quot;<br>...<br>&quot;batch&quot;<br>...<br>&quot;storage.k8s.io&quot;<br>...<br># EXPLANATION : <br># We can see that we have different API groups available under the named group.</pre><p><em>API groups</em> are made available under a specific <em>version </em>or under a set of different <em>versions </em>with one specified as the <em>preferred </em>one. Thus, used by default in the apiVersion field of an <em>object. </em>Let’s explore versions of an <em>API group</em></p><pre>curl http://127.0.0.1:8001/apis/batch/ | jq . <br><br># OUTPUT<br>{<br>  &quot;kind&quot;: &quot;APIGroup&quot;,<br>  &quot;apiVersion&quot;: &quot;v1&quot;,<br>  &quot;name&quot;: &quot;batch&quot;,<br>  &quot;versions&quot;: [<br>    {<br>      &quot;groupVersion&quot;: &quot;batch/v1&quot;,<br>      &quot;version&quot;: &quot;v1&quot;<br>    }<br>  ],<br>  &quot;preferredVersion&quot;: {<br>    &quot;groupVersion&quot;: &quot;batch/v1&quot;,<br>    &quot;version&quot;: &quot;v1&quot;<br>  }<br>}<br># EXPLANATION<br># The api group batch avaialble under the named group has version v1 which<br># is also the preferred version. Thus, resources types avaiable under the api<br># Group batch are of version v1.</pre><ul><li>Let’s list the <em>resources types</em> made available under the <em>API group</em> batch of version v1 .</li></ul><pre>curl http://127.0.0.1:8001/apis/batch/v1 | jq .resources[].name<br><br># OUTPUT <br>&quot;cronjobs&quot;<br>&quot;cronjobs/status&quot;<br>&quot;jobs&quot;<br>&quot;jobs/status&quot;<br># EXPLANATION <br># resources types available under the API group batch of type v1 are cronjobs<br># and jobs. These resources can be accessed using their REST PATH /cronjobs<br># and can be explored further using their REST PATH and REST SUBPATH <br># /cronjobs/status</pre><ul><li>Let’s list <em>collections, resources , objects </em>made available under the <em>resources type </em>cronjobsof the <em>API group</em> batch of version v1 .</li></ul><pre>curl http://127.0.0.1:8001/apis/batch/v1/cronjobs | jq .items[].metadata.name<br><br># OUTPUT <br>&quot;daily-cronjob-database-backuper&quot;<br>&quot;...&quot;<br>&quot;...&quot;<br># Explanation <br># These are the list of running cronjobs objects</pre><p><strong>4.3. The <em>resources types </em>definition</strong></p><p>Let’s explore how an API <em>resource type </em>is defined.</p><pre># Let&#39;s explore the api resources type available under the core group<br><br># List the resources type<br> curl http://127.0.0.1:8001/api/v1/| jq .<br># Select only resources of type pods<br> curl http://127.0.0.1:8001/api/v1/ | jq &#39;.resources[] | select(.name==&quot;pods&quot;)&#39;<br># OUTPUT<br>{<br>  &quot;name&quot;: &quot;pods&quot;,<br>  &quot;singularName&quot;: &quot;&quot;,<br>  &quot;namespaced&quot;: true,<br>  &quot;kind&quot;: &quot;Pod&quot;,<br>  &quot;verbs&quot;: [<br>    &quot;create&quot;,<br>    &quot;delete&quot;,<br>    &quot;deletecollection&quot;,<br>    &quot;get&quot;,<br>    &quot;list&quot;,<br>    &quot;patch&quot;,<br>    &quot;update&quot;,<br>    &quot;watch&quot;<br>  ],<br>  &quot;shortNames&quot;: [<br>    &quot;po&quot;<br>  ],<br>  &quot;categories&quot;: [<br>    &quot;all&quot;<br>  ],<br>  &quot;storageVersionHash&quot;: &quot;xxxxxx&quot;<br>}</pre><p>From the above output we can derive that each <em>resource type </em>is defined by :</p><ul><li>a plural name defined in the name field. It is the plural name that is available as an HTTP endpoint. We make API Calls with the available k8s <em>resource types </em>through the use of their plural names .</li><li>a kind defined in the kind field. It defines the <em>resource type’s</em></li><li>a singular name defined in the singularName field.</li><li>a list of verbs defined in the verbsfield. It defines the list of operations that can be performed on <em>collections, objects or resources </em>managed by this<em> resource type .</em></li><li>a list of short namesdefined in the shotNamesfield. It allows to query the<em> resource type </em>using its short name. For example:</li></ul><pre>kubectl get po # instead of: kubectl get pods<br>kubectl get deploy # intead of : kubectl get deployments</pre><p>Finally, the nameSpacedfield defines whether or not the <em>resource type is namespaced </em>or <em>cluster scoped.</em></p><blockquote><em>For example:</em></blockquote><blockquote>objects <em>of </em>resource type <em>pod are </em>namespaced<em>. To create or manage </em><em>pods </em>objects <em>we should specify a </em>namespace <em>otherwise k8s consider them as part of the </em><em>default </em>namespace<em>.</em></blockquote><pre>kubectl get pods -n develop</pre><blockquote>objects <em>of </em>resource type<em> </em><em>pv [persistent storage] are </em>cluster scoped<em>. To create or manage</em><em>pvs we don’t need to specify a </em>namespace<em>. k8s consider them as </em>cluster scoped resources.</blockquote><pre>kubectl get pv</pre><p>A simple way to check for <em>API resources types names, shortnames, version, kind </em>and whether or not they’re<em> namespaced. </em>You can use the following command. It performs API Calls with the<em> API-server </em>on our behalf to get these information.</p><pre>kubectl api-resources<br><br># watch the API Calls the kubectl establish with the API-server<br>kubectl api-resources -v 10</pre><p><strong>5. API Calls Advanced Queries</strong></p><p><strong>5.1 Using </strong><strong>kubectl along with </strong><strong>jsonPath</strong>and <strong>jq </strong><a href="https://kubernetes.io/docs/reference/kubectl/jsonpath/">[5]</a></p><blockquote>Note:</blockquote><pre># Brief Resume of kubectl JsonPath and jq Operators: more can be found in [5]<br><br>- {&quot;\n&quot;}          : the escape sequence<br>- {&quot;\t&quot;}          : the space sequence<br>- range, end      : to iterate a list of elements<br>- [,]             : the union operator. for example, get two elements [a,b]<br>- [start:end:step]: subscript operator<br>- *               : wildcard. Get all objects<br>- ..              : recursive descent<br>- . or []         : child operator <br>- select ()       : to filter elements <br>- keys            : to list json file keys for further queries<br></pre><ul><li>get the possible json attribute to query of the pod k8s resource</li></ul><pre>kubectl get pod -o json | jq &#39;keys&#39;<br><br># OUTPUT<br>[<br>  &quot;apiVersion&quot;,<br>  &quot;items&quot;,<br>  &quot;kind&quot;,<br>  &quot;metadata&quot;<br>]<br># Explanation <br># We can see that we can query the above attributes, for example:<br># If we want to list pods within the default namespace: <br><br>kubectl get pod -o json | jq &#39;.items[]&#39;<br><br># Let&#39;s get the possible attributes to query for each pod within the <br># list of items<br><br>kubectl get pod -o json | jq &#39;.items[]&#39;  | jq &#39;keys&#39;<br>kubectl get pod -o json | jq &#39;.items[].metadata&#39; | jq &#39;keys&#39;<br>kubectl get pod -o json | jq &#39;.items[].metadata.name&#39;</pre><ul><li>get the name of pods within the default namespace</li></ul><pre># option 1<br>kubectl get pod -o=jsonpath=&#39;{.items[*].metadata.name}&#39;<br><br># option 2<br>kubectl get pod -o=jsonpath=&#39;{range .items[*]}{.metadata.name}{&quot;\n&quot;}{end}&#39;</pre><ul><li>get containers and image names of the nginx pod within the default namespace.</li></ul><blockquote>Important</blockquote><blockquote>JSONPath regular expressions are not supported. If you want to match using regular expressions, you can use a tool such as jq.</blockquote><pre> kubectl get pods -o json | jq &#39;.items[] | select (.metadata.name == &quot;nginx&quot;) | [.spec.containers[].name, .spec.containers[].image]&#39;</pre><ul><li>get containers and images names of the pod containing the nginx pattern in their names within the default namespace.</li></ul><pre>kubectl get pods -o json | jq &#39;.items[] | select (.metadata.name | test (&quot;nginx&quot;)) | [.spec.containers[].name, .spec.containers[].image]&#39;</pre><ul><li>get pods names within the default namespaces and their corresponding starting date.</li></ul><pre>kubectl get pod -o json | jq &#39;.items[] | [.metadata.name, .status.startTime]&#39;</pre><ul><li>order pods by their staring time</li></ul><pre>kubectl get pod -o json | jq &#39;.items[] | .status.startTime | sort_by(.startTime)&#39;<br>  <br> # ERROR <br> Cannot iterate over string.<br> <br> # COMMENT<br> The idea here is just to show the sort_by function usage.</pre><ul><li>for every pod within the default namespace, get its name, its requierement in terms of cpu, ram and derive its quality of service (qos)</li></ul><pre>kubectl get pod -o json | jq &#39;.items[] | [.metadata.name, .spec.containers[].resources, .status.qosClass]&#39;</pre><pre># Additional Queries <br><br>kubectl get pod -o json | jq .items[].spec.containers[].resources<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.requests<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.requests.cpu<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.requests.memory<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.limits<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.limits.cpu<br>kubectl get pod -o json | jq .items[].spec.containers[].resources.limits.memory<br>kubectl get pod -o json | jq .items[].status.qosClass</pre><h4><strong>Conclusion</strong></h4><p>The primary goal of this article was to give a deeper understanding of the Kubernetes API functioning through practical examples. This has been accomplished through giving a general overview about the k8s API then getting more practical through different examples using the curl and kubectlcommands.</p><h4>References</h4><p><a href="https://kubernetes.io/docs/concepts/overview/kubernetes-api/">[1] <em>The Kubernetes API</em>. (2022, October 24). Kubernetes. https://kubernetes.io/docs/concepts/overview/kubernetes-api/</a></p><p><a href="https://kubernetes.io/docs/reference/using-api/">[2] <em>API Overview</em>. (n.d.). Kubernetes. https://kubernetes.io/docs/reference/using-api/</a></p><p>[3] <a href="https://kubernetes.io/docs/reference/using-api/api-concepts/"><em>Kubernetes API Concepts</em>. (2022, December 26). Kubernetes. https://kubernetes.io/docs/reference/using-api/api-concepts/</a></p><p><a href="https://www.youtube.com/watch?v=_65Md2qar14">[4] KodeKloud. (2021, October 26). <em>Kubernetes API Fundamentals You Must Know!</em> [Video]. YouTube. https://www.youtube.com/watch?v=_65Md2qar14</a></p><p><a href="https://kubernetes.io/docs/reference/kubectl/jsonpath/">[5] <em>JSONPath Support</em>. (2022, November 4). Kubernetes. https://kubernetes.io/docs/reference/kubectl/jsonpath/</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9481d6b176ea" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/kubernetes-series-getting-practical-with-the-kubernetes-api-9481d6b176ea">Kubernetes Series: Getting practical with the Kubernetes API</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Series: Helm Charts Overview]]></title>
            <link>https://levelup.gitconnected.com/kubernetes-series-helm-charts-overview-40795c79dcf2?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/40795c79dcf2</guid>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 13:44:55 GMT</pubDate>
            <atom:updated>2023-04-06T02:11:06.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6WBuqM6cqO0mJC-NY7aUA.jpeg" /></figure><h3>Introduction</h3><p>This guide walks through the basic concepts of Helm needed to start deploying applications on a Kubernetes cluster. It covers the basic usage patterns of the helm client, including creating, installing, searching, updating, upgrading, rollingback and uninstalling Helm Charts.</p><h3>General Concepts</h3><p>According to <a href="https://helm.sh/docs/">Helm Documentation</a>. Helm is a package manager for Kubernetes. <a href="https://helm.sh/docs/intro/using_helm/">[1]</a></p><blockquote>A package manager is a collection of tools that automates the process of installing, updating, upgrading, configuring and removing software. It allows to easily install an application without having prior knowledge of its setup.</blockquote><p>An application exists in multiple versions, it can run in multiple environments and in Kubernetes, an application is made of several files known as manifests such as : <em>Deployments, Services, ConfigMaps, Ingress etc.</em> Thus, Helm is used to facilitate the installation and management of Kubernetes applications. through the use of three concepts:</p><ul><li>A <em>Chart</em> is a Helm package. It regroups all of the necessary manifests necessary to run an application within the Kubernetes Cluster. <a href="https://helm.sh/docs/intro/using_helm/">[1]</a></li><li>A <a href="https://artifacthub.io/"><em>Repository</em> </a>is the place where charts can be collected and shared. It is like the <a href="https://hub.docker.com/">Docker Hub</a> but for Kubernetes. It can be private or public. <a href="https://helm.sh/docs/intro/using_helm/">[1]</a></li><li>A <em>Release</em> is an instance of a chart running in a Kubernetes cluster. One chart can often be installed many times into the same cluster. And each time it is installed, a new <em>release</em> is created. Consider a MySQL chart. If you want two databases running in your cluster, you can install that chart twice. Each one will have its own <em>release</em>, which will in turn have its own <em>release name </em><a href="https://helm.sh/docs/intro/using_helm/">[1]</a></li></ul><p>With helm, application manifests are packaged into a single <em>Chart</em>. This <em>Chart </em>can be put into a <em>Repository </em>. Users can search that <em>Repository </em>to discover <em>Charts </em>to install (deploy) into their Kubernetes Cluster creating new <em>Release </em>for each installation.</p><h3>Helm Installation</h3><p>Helm can be installed in many ways. One of which is from script<a href="https://helm.sh/docs/intro/install/"> [3]</a></p><pre>$ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3<br>$ chmod 700 get_helm.sh<br>$ ./get_helm.sh</pre><h3>Helm Usage</h3><p>Once helm is installed , the following operations can be performed:</p><h4><strong>1. Create and Install a Helm Chart</strong></h4><p>The following command will create a Chart named postgres.</p><pre>helm create $HOME/postgres</pre><p>To install a Chart ( deploy the defined application into the Kubernetes Cluster) , use the helm install command. At its simplest, it takes two arguments: A release name that you pick, and the chart path you want to install.</p><pre># helm install [RELEASE_NAME] [CHART PATH]<br>helm install my-postgres postgres/</pre><p>If you don’t want to specify a release name, Helm can generate one for you through the following command :</p><pre># helm install [CHART DIR] --generate-name <br>helm install postgres/ --generate-name</pre><p>A chart is organized as a collection of files inside of a directory. The directory name is the name of the chart (without versioning information). Thus, a chart describing postgres would be stored in a $HOME/postgres/ directory.<a href="https://helm.sh/docs/topics/charts/"><em> </em>[2]</a></p><p>Inside of this directory, Helm will expect the underlying structure <a href="https://helm.sh/docs/topics/charts/">[2]</a>:</p><pre>postgres/<br>  Chart.yaml          # A YAML file containing information about the chart<br>  values.yaml         # The default configuration values for this chart<br>  templates/          # A directory of templates that, when combined with values,<br>  charts/             # A directory containing any charts upon which this chart depends.</pre><blockquote><strong><em>The </em></strong><strong><em>Chart.yaml File</em></strong></blockquote><p>The Chart.yaml file is required for a chart. It contains the following fields:</p><pre>apiVersion: The chart API version (required)<br>name: The name of the chart (required)<br>description: A single-sentence description of this project (optional)<br>type: The type of the chart (i.e application) (optional)<br>version: A SemVer 2 version (required)<br>kubeVersion: A SemVer range of compatible Kubernetes versions (optional)<br>appVersion: The version of the app that this contains (optional). Needn&#39;t be SemVer. Quotes recommended.<br>maintainers: # (optional)<br>  - name: The maintainers name (required for each maintainer)<br>    email: The maintainers email (optional for each maintainer)<br>    url: A URL for the maintainer (optional for each maintainer)</pre><p><em>Note : </em><em>SemVemeans </em><a href="https://semver.org/spec/v2.0.0.html"><em>Semantic Versioning</em></a><em>: v.major.minor.patch (i.e v1.25.6)</em></p><ul><li><strong>The </strong><strong>apiVersion Field</strong></li></ul><p>The apiVersion field should be v2 for Helm charts that require at least Helm 3. Charts supporting previous Helm versions have an apiVersion set to v1 and are still installable by Helm 3.</p><ul><li><strong>The </strong><strong>version Field</strong></li></ul><p>Every chart must have a version number. A version must follow the <a href="https://semver.org/spec/v2.0.0.html">SemVer 2</a> standard. For example, an nginx chart whose version field is set to version: 1.2.3 will be named nginx-1.2.3.tgz .</p><ul><li><strong>The </strong><strong>appVersion Field</strong></li></ul><p>Note that the appVersion field is not related to the version field. It is a way of specifying the version of the application. For example, the drupal chart may have an appVersion: &quot;8.2.1&quot;, indicating that the version of Drupal included in the chart (by default) is 8.2.1. This field is informational, and has no impact on chart version calculations.</p><ul><li><strong>The </strong><strong>kubeVersion Field</strong></li></ul><p>The optional kubeVersion field can define semver constraints on supported Kubernetes versions. Helm will validate the version constraints when installing the chart and fail if the cluster runs an unsupported Kubernetes version.</p><blockquote><strong><em>The </em></strong><strong><em>values.yaml File and </em></strong><strong><em>templates/ Folder</em></strong></blockquote><p>Helm Chart templates are written in the <a href="https://golang.org/pkg/text/template/">Go template languag</a>e.</p><p>All template files are stored in a chart’s templates/ folder. When Helm renders the charts, it will pass every file in that directory through the template engine.</p><p>Files inside templates folder are <em>Kubernetes Manifest Yaml Files. </em>For example a service.yaml file.</p><pre># sevice.yaml <br><br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ .Values.serviceName }}<br>  namespace: {{ .Values.nameSpace }}<br>spec:<br>  selector:<br>    app: {{ .Values.appName }}<br>  type: ClusterIP<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080</pre><p>As long as these files are templated, variable files (known as values) should be passed along with these templates files to the template engine for further variable substitution.</p><p>Values for the templates are supplied in three ways :</p><ul><li>Chart developers may supply a file called values.yaml inside of a chart. This file can contain default values. This can be provided on the command line with helm install . This command will automatically look for values in values.yaml file.</li></ul><pre># helm install release-name chart-dir or helm install chart-dir --generate-name<br><br>helm install my-postgres postgres/<br><br># or <br><br>helm install postgres/ --generate-name</pre><ul><li>Chart users may supply a custom YAML file that contains values. This can be provided on the command line with helm install for example if the custom values file is values.prod.yaml . Then , it should be passed with helm install as follows :</li></ul><pre># helm install -f custom-vars-file.yaml release-name chart-dir<br><br>helm install -f postgres/values.prod.yaml my-postgres postgres/<br><br># or <br><br>helm install -f postgres/values.prod.yaml postgres/ --generate-name</pre><ul><li>Chart users may supply custom variables on command line using --set which specifies overrides of the custom values files such asvalues.prod.yaml and the default values.yamlfile.</li></ul><pre># helm install -f custom-vars-file.yaml release-name chart-dir<br><br>helm install --set serviceName=test -f postgres/values.prod.yaml my-postgres postgres/<br><br># or <br><br>helm install --set serviceName=test -f postgres/values.prod.yaml postgres/ --generate-name</pre><p>When a user supplies custom values, these values will override the values in the chart’s values.yaml file. Let’s take an example:</p><pre># values.yaml<br>serviceName: postgres-svc<br>appName: postgres<br>nameSpace: default</pre><pre># values.prod.yaml<br>appName: postgres-prod<br>nameSpace: prod</pre><p>After running:</p><pre>helm install -f postgres/values.prod.yaml my-postgres postgres/</pre><p>The template engine will make the following subtitutions.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: postgres-svc # from values.yaml<br>  namespace: prod # from values.prod.yaml<br>spec:<br>  selector:<br>    app: postgres-prod # from values.prod.yaml<br>  type: ClusterIP<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080</pre><p>To see what options are configurable on a chart (variables of the chart), use helm show values. This command inspects a chart (directory, file, or URL) and displays the contents of the values.yamlfile.</p><pre># helm show values [PATH TO CHART]<br>helm show values postgres/</pre><p>When a user supplies --setin command line values will override the values in the chart’s values.yaml file. and the other custom values file such as values.prod.yaml Let’s take an example:</p><pre>helm install --set serviceName=test -f postgres/values.prod.yaml  my-postgres postgres/ </pre><p>The template engine will make the following subtitutions.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: test # from --set flag<br>  namespace: prod # from values.prod.yaml<br>spec:<br>  selector:<br>    app: postgres-prod # from values.prod.yaml<br>  type: ClusterIP<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080</pre><blockquote><strong><em>The </em></strong><strong><em>charts/ directory</em></strong></blockquote><p>In Helm, one chart may depend on any number of other charts. These dependencies can be dynamically linked using the dependencies field in Chart.yaml or brought in to the charts/ directory and managed manually.</p><p><em>Helm Chart dependencies are out of the scope of this article, you can learn more in the</em><a href="https://helm.sh/docs/topics/charts/#chart-dependencies"><em> Helm Official Documentation</em></a><em> .</em></p><p>Once a chart is created and configured to match your needs, you can :</p><ul><li><strong>Validate your chart</strong> : examine a chart for possible issues</li></ul><pre>helm lint postgres/<br><br># Output: <br>==&gt; Linting postgres<br>[INFO] Chart.yaml: icon is recommended<br><br>1 chart(s) linted, 0 chart(s) failed</pre><ul><li><strong>Package your chart</strong>: package a chart directory into a chart archive</li></ul><pre>helm package postgres/<br><br># Output: <br>Successfully packaged chart and saved it to: $HOME/postgres-0.1.0.tgz<br>Note that 0.1.0 is the version: 0.1.0 specified in Chart.yaml</pre><ul><li><strong>Install your chart</strong>: after a chart has been packaged, it can now be easily be installed (deployed into Kubernetes Cluster) by helm install:</li></ul><pre>helm install my-postgres $HOME/postgres-0.1.0.tgz</pre><p><em>Note that, a Chart can be installed without been packaged as we have seen earlier</em></p><pre>helm install my-postgres postgres/</pre><h4>2. Find, Install and Update a Helm Chart</h4><p>Helm comes with a powerful search command. It can be used to search two different types of source: <a href="https://helm.sh/docs/intro/using_helm/">[4]</a></p><ul><li>helm search hub searches <a href="https://artifacthub.io/">the Artifact Hub</a>, which lists helm charts from dozens of different repositories. <a href="https://helm.sh/docs/intro/using_helm/">[4]</a></li><li>helm search repo searches the repositories that you have added to your local helm client (with helm repo add). This search is done over local data, and no public network connection is needed. <a href="https://helm.sh/docs/intro/using_helm/">[4]</a></li></ul><p>Let’s explore the helm search hub</p><pre># looks for prometheus Charts avaialble in the Public Artifact Hub<br>helm search hub -h <br>helm search hub prometheus<br>helm search hub prometheus -o yaml<br><br># Output: <br><br>- app_version: v2.41.0<br>  description: Prometheus is a monitoring system and time series database.<br>  repository:<br>    name: prometheus-community<br>    url: https://prometheus-community.github.io/helm-charts<br>  url: https://artifacthub.io/packages/helm/prometheus-community/prometheus<br><br>... <br>...<br></pre><p>Let’s explore the helm search repo</p><pre>helm search repo<br><br>#Output: <br><br>This command consists of multiple subcommands to interact with chart repositories.<br><br>It can be used to add, remove, list, and index chart repositories.<br><br>Usage:<br>  helm repo [command]<br><br>Available Commands:<br>  add         add a chart repository<br>  index       generate an index file given a directory containing packaged charts<br>  list        list chart repositories<br>  remove      remove one or more chart repositories<br>  update      update information of available charts locally from chart repositories</pre><p>Let’s add the prometheus-communitychart available on the public repo to our local repo for further manipulation</p><pre>helm search repo<br><br>#Output: Error: no repositories configured</pre><pre># Add a Chart repo to our local helm repo <br><br># helm repo add [CHART-NAME] [CHART-URL]<br><br>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts<br><br>#Output: &quot;prometheus-community&quot; has been added to your repositories</pre><pre># Check if the Chart has been added to our local repo<br><br>helm repo list <br><br># Output: <br>NAME                    URL<br>prometheus-community    https://prometheus-community.github.io/helm-charts</pre><pre># Look for Charts available in repo <br><br>helm search repo</pre><pre># Look for only prometheus-community Charts available in repo <br><br>helm search repo prometheus-community<br><br><br>#Output: <br><br>prometheus/alertmanager                         0.26.0          v0.25.0         The Alertmanager handles alerts sent by client ...<br>prometheus/alertmanager-snmp-notifier           0.1.0           v1.4.0          The SNMP Notifier handles alerts coming from Pr...<br>prometheus/jiralert                             1.2.0           v1.3.0          A Helm chart for Kubernetes to install jiralert<br>...</pre><pre># get the latest information about charts from the respective chart repositories.<br><br>helm repo update </pre><pre># get the latest information about only prometheus-community chart from the respective chart repositories.<br><br>helm repo update prometheus-community </pre><p>Let’s perform some modifications on the prometheus-community chart</p><pre><br># Search of the prometheus-community Chart <br>helm search repo prometheus-community<br><br># Select and Fetch a Helm Chart <br>helm fetch prometheus/prometheus<br><br># Output: prometheus-19.7.2.tgz</pre><pre># Select , Fetch and Untar a Helm Chart<br><br>helm fetch prometheus/prometheus --untar <br><br># Output : prometheus Chart dir available locally</pre><pre>cd $HOME/prometheus<br><br>ls <br><br># Edit Values.yaml <br><br>vim $HOME/prometheus/values.yaml<br><br># Install a release of a Chart<br><br>helm install prom $HOME/prometheus</pre><pre># List avaialable releases<br><br>helm list<br><br># Uninstall the release<br><br>helm uninstall prom<br><br># Remove the Chart from repo<br><br>helm repo remove prometheus</pre><p><em>Note that helm sets an alternative location for storing cached files :</em><em>$HOME/.cache/helm/</em></p><h4>3. Upgrade a Release</h4><p>When a new version of a chart is released, or when you want to change the configuration of your release, you can use the helm upgrade command.</p><p>An upgrade takes an existing release and upgrades it according to the information you provide. Because Kubernetes charts can be large and complex, Helm tries to perform the least invasive upgrade. It will only update things that have changed since the last release.</p><p>For example, if we change the prometheus version in values.yaml file. The following should be performed to upgrade the currently ruuning release in the Kubernetes Cluster.</p><pre>helm upgrade -f values.yaml prom prometheus/prometheus</pre><p>We can use helm get values to see whether that new setting took effect.</p><pre># helm get values [RELEASE]<br><br>helm get values prom</pre><h4>4. Recovering a Release on Failure</h4><p>Now, if something does not go as planned during a release, it is easy to roll back to a previous release using:</p><pre>helm rollback [RELEASE] [REVISION]</pre><p>For example, if the newely upgraded promtheus version doesn’t work properly, we can rollback to the previous one as follows</p><pre> helm rollback prom 1</pre><p>The above rolls back our promrelease to its very first release version. A release version is an incremental revision. Every time an install, upgrade, or rollback happens, the revision number is incremented by 1. The first revision number is always 1. And we can use helm history [RELEASE] to see revision numbers for a certain release.</p><pre># helm history [RELEASE]<br>helm history prom</pre><h4>5. Uninstalling a Chart</h4><p>When it is time to uninstall a release from the cluster, use the helm uninstall command:</p><pre># helm uninstall [RELEASE]<br>helm uninstall prom</pre><p>If you wish to keep a deletion release record, use helm uninstall --keep-history</p><pre># helm uninstall --keep-history [RELEASE]<br>helm uninstall --keep-history prom</pre><p>Using helm list --uninstalled will only show releases that were uninstalled with the --keep-history flag.</p><pre>helm list --uninstalled</pre><p>Using helm listwill only show currently deployed releases in the cluster</p><pre>helm list</pre><p>The helm list --all flag will show you all release records that Helm has retained, including records for failed or deleted items (if --keep-history was specified):</p><pre>helm list --all</pre><h3>Conclusion</h3><p>This chapter has covered the basic usage patterns of the helm client, including creating, installing, searching, updating, upgrading, rollingback and uninstalling Helm Charts.. It has also covered useful utility commands.</p><h3>References</h3><ul><li><a href="https://helm.sh/docs/intro/using_helm/">[1]</a> <em>Using Helm</em> (no date) <em>Helm</em>. Available at: <a href="https://helm.sh/docs/intro/using_helm/">https://helm.sh/docs/intro/using_helm/</a> (Accessed: March 15, 2023).</li><li><a href="https://helm.sh/docs/topics/charts/">[2]</a> <em>Charts</em> (no date) <em>Helm</em>. Available at: <a href="https://helm.sh/docs/topics/charts/">https://helm.sh/docs/topics/charts/</a> (Accessed: March 15, 2023).</li><li><a href="https://helm.sh/docs/intro/install/">[3]</a> <em>Installing Helm</em> (no date) <em>Helm</em>. Available at: <a href="https://helm.sh/docs/intro/install/">https://helm.sh/docs/intro/install/</a> (Accessed: March 15, 2023).</li><li><a href="https://helm.sh/docs/intro/using_helm/">[4]</a> <em>Using Helm</em> (no date) <em>Helm</em>. Available at: <a href="https://helm.sh/docs/intro/using_helm/">https://helm.sh/docs/intro/using_helm/</a> (Accessed: March 15, 2023).</li></ul><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40795c79dcf2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/kubernetes-series-helm-charts-overview-40795c79dcf2">Kubernetes Series: Helm Charts Overview</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptography Part II : Public Key Infrastructure]]></title>
            <link>https://levelup.gitconnected.com/cryptography-part-ii-public-key-infrastructure-6cd9ef868083?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd9ef868083</guid>
            <category><![CDATA[pki]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[asymmetric-encryption]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 14:56:13 GMT</pubDate>
            <atom:updated>2023-04-05T11:32:22.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cryptography Part II : Public Key Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrHwEd__KZixtewnm-D6xw.jpeg" /></figure><h4>Introduction</h4><p>The major difficulty in Public Key Cryptography<em> (known as PKC or Asymmetric Cryptography )</em> is to reliably trust the authenticity of the exchanged encryption information (public key, encryption function etc) . Since these information are typically transmitted over unsecured channels (i.e the internet)<strong> </strong><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a>.</p><ol><li><em>First, In order for the PKC to occur, entities (usually referred to as Alice and Bob) need to exchange their public keys. How can they be confident about the authenticity of the exchanged public keys ? In other words, how can Alice be confident that the received key is Bob’s public key and not Oscar’s </em><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a><em>.</em></li><li><em>Furthermore, entities need to exchange their public keys but also they need to learn each other’s encryption function. However, they cannot simply ask each other because a hacker could impersonate one of the communicants and give a false encryption function whose inverse would be known to the hacker </em><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a><strong> </strong><em>which will allow him for example to derive the private key and intercept communication.</em></li><li><em>Finally, if Bob’s private key get compromised, Alice should no longer use Bob’s public key for encryption. However, there’s no public key revocation process in PKC.</em></li></ol><p>Thus, multiple researchs have been conducted to solve such issues which have led to the creation of a Public Key Infrastructure (PKI).</p><p>This article aims at explaining the PKI. It is a continuation of <a href="https://medium.com/@schh/cryptography-part-i-the-basics-c6a8617bb0b5">Cryptography Part I: The basics. </a>It covers two sections. First, PKI overview, definition, components and architectures. Then, it illustrates how web browsers use PKI to provide secure communication over the internet. It ends with a conclusion.</p><h4>1. Public Key Infrastructure (PKI)</h4><h4>1.1. PKI Overview</h4><p>In 1976, Diffie and Hellman pointed out the problem of authenticating that a Public Key belongs to a real entity through the use of a third party<em> </em>trusted entity known as<em> </em>a<em> Public File</em> <a href="https://dl.acm.org/doi/abs/10.1145/3549993.3550007"><strong>[2]</strong></a>.</p><blockquote>The Public File is a third party entity that serves as a dynamic directory for all of the encryption information in a given system. Each entity registers once (in person) within the Public File before any communication takes place. All entities trust the Public File. <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>The Public File registration (authentication) process involves associating an entity to its corresponding public key and encryption function. In return, each entity receives the encryption function and public key of the Public File.<a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>Thus, In order for an entity Alice to learn the encryption function and public key of an entity Bob for further communication, she would need to first send an encrypted request to the Public File . The Public File encrypts and returns the requested information to Alice. Alice trusts the Public File and does not question the authenticity of Bob’s information.<a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><p>The Public File solved many problems, but:</p><ul><li>It was a Single Point of failure.<a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a></li><li>It had to deal with high workload and latency as all communications was initialized with the Public File.<a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a></li><li>A hacker that had broken to the Public File could authoritatively impersonate any communicant in the system <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a>.</li><li>Securely updating such a large system was difficult and required expensive equipments <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a>.</li></ul><p>Hence, In 1978 Kohnfelder <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[1]</strong></a> proposed a solution by certificates to solve the Public File’s workload and latency issues</p><blockquote>A certificate is a digital file issued by the Public File associating key information to a name (an entity). It is signed by Public File’s private key. <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>New entities had to visit the Public File once (in person) before they can begin communication within the system to be authenticated. They get their certificates along with Public File’s encryption function and public key. <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>There were a certificate for each entity in the system. Each certificate can only be created by the Public File.<em> </em><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>Entities convey their key information to others simply by sending their certificates. No further interaction between the entity and Public File was ever necessary. Entities verified their authenticity through validating the certificate signature using the Public File’s public key. <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><blockquote>The use of certificates allowed key Information to be obtained as reliably as if it were from the Public File without ever making contact with the Public File. <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong><em>[1]</em></strong></a></blockquote><p>Certificates helped the Public File to decrease its load and avoid latency but the previously discussed issues were still present plus:</p><ul><li>There were no way to manage and revoke certificates if they get compromised</li><li>The system were still not adapted for a world wide communication</li></ul><p>In the 1980’s, International Telecommunication Union (ITU) decided to adapt the Public File approach to a world wide communication through building a larger directory to cover people and devices all over the world, so the result was a standard called X.500<strong> [3]</strong> defining all characteristics of that directory.</p><blockquote>An example of entities attributes defined in the X.500 standard can be found in <a href="https://www.ibm.com/docs/en/zos/2.1.0?topic=SSLTBW_2.1.0/com.ibm.tcp.ipsec.ipsec.help.doc/com/ibm/tcp/ipsec/ipsec/LocalInfo_X500.htm">IBM’s documentation</a>.</blockquote><p>Moreover, a standard called X.509 was also released to define the certificate format.</p><blockquote>X.509 provides entities authentication in the X.500 directory.</blockquote><p>The X.500 and X.509 standards are the foundation blocks of the PKI.</p><h4>1.2 PKI Definition</h4><p>A PKI is a framework. It is composed of a set of hardware, software, policies, processes, norms and procedures required to create, manage, distribute, use, store, and revoke X.509 digital certificates. It represents a worldwide trusted authority. <a href="https://cpl.thalesgroup.com/faq/public-key-infrastructure-pki/what-public-key-infrastructure-pki"><strong>[4]</strong></a></p><h4>1.3 PKI Components</h4><p>PKI architecture highly depend on organizations needs and processes. Thus, it should be adapted to organizations requirements. Hence, an operational PKI incorporates the following components: <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><blockquote>PKI is built on client server architecture. the client must send a request for certification to the server (a trusted authority in the PKI framework) in order to be authenticated and receive his certificate.<a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a></blockquote><h4>1.3.1. X509 Certificates</h4><p>In this context, a X509 certificate refers to a Public Key Certificate. It is a digital file that binds an entity to its corresponding encryption information. It stores those information ( name, public key , encryption function etc. ) in a X509 format as described in the underlying Figure. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6QW6hju5Uaq7NKbHWgFSA.png" /><figcaption>Figure 1 X509 version 3 certificate structure <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></figcaption></figure><p>Certificates are issued by a trusted authority known as the Certificate Authority (CA). They are signed using the CA’s private key. The resulting signature is stored in the digital signature field following the X509 format.</p><p>Certificates are distributed publicly over an insecure channel. Thus, the digital signature provides a prove that the certificate has been issued by a trusted CA <em>(authenticity)</em> and has not been altered by a hacker <em>(integrity) .</em></p><blockquote>The CA provides its public key to entities in order for them to prove using the certificate digital signature that a certificate was issued by this CA and that it has not been altered by hacker.</blockquote><h4>1.3.2 Certificate Authority (CA)</h4><p>Also known as Certificate Issuer. It is a worldwide trusted and authorized authority responsible for issuing and signing Public Key Certificates for verified and authenticated entities. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong>[6]</strong></a></p><p>It is also responsible for updating and maintaining a Certificate Revocation List (CRL) which comprise a list of revoked certificates. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong>[6]</strong></a></p><blockquote>Revocation means that the certificate that certifies the key-pair binding of an entity is no longer valid. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong><em>[6]</em></strong></a></blockquote><p>An example of a revoked certificate can be a certificate with a compromised private key or with an expired validity date. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong>[6]</strong></a></p><blockquote>PKI architecture is premised on the quantity of CAs involved. It is the main component that derived the existence of many PKI architectures that will be discussed later on. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong><em>[6]</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vPBRHvBAs15rAE64lZP8Q.png" /><figcaption>Figure 2 A digital certificate issued by DigiCert (CA) to Amazon <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[6]</strong></a></figcaption></figure><h4>1.3.3 Registration Authority (RA)</h4><p>It represents the CA’s secretary. It receives entities certification requests for certificates. It verifies and authenticates entities information. Once the authenticity is established, the RA passes the entity certificate request to the CA.</p><blockquote>An entity must have a unique identity within each CA. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a></blockquote><h4>1.3.4 Certificate Repository (CR)</h4><p>It provides storage mechanism. It stores the issued certificates and CRL information.<a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong>[6]</strong></a></p><h4>1.3.5 Validation Authority (VA)</h4><p>It represents the CA’s secretary. It takes entities requests for certificate revocation and validation. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong>[6]</strong></a></p><blockquote>Validation means that the VA verifies if the certificate is present in the CRL. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong><em>[6]</em></strong></a></blockquote><blockquote>Revocation means that the VA requests the CA to revoke a certificate and update its CRL. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a><a href="https://www.researchgate.net/publication/272955036_Public_Key_Infrastructure_A_Survey#pf7"><strong><em>[6]</em></strong></a></blockquote><p>The following Figure demonstrates an operational PKI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOLbZHPfZW1_YCfYy7AQVQ.png" /><figcaption>Figure 3 An illustration of an operational PKI</figcaption></figure><h4>1.4. PKI Architectures</h4><p>As mentioned earlier, PKI architecture is premised on the quantity of CAs involved. These architectures can be categorized as <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><ul><li>Non Hierarchical</li><li>Hierarchical</li></ul><p><strong>1.4.1. Non-Hierarchical</strong></p><p>It involves only one CA trusted by all entities <em>as described in Figure 3</em>. It can work for small organizations but it becomes completely inadequate in highly distributed systems like the internet as this category suffers from scalability issues and single point of failure. Moreover entities need to trust the same CA to establish trust as there’s no trust between different CAs. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rBZ8hdvm0Pr0NWE9rFjrA.png" /><figcaption>Figure 4 : An illustration of a non-hierarchical PKI.</figcaption></figure><blockquote>Based on Figure 4. Bob trusts CA3 but Alice trusts CA1. Thus, they cannot establish trust as they don’t trust the same CA, therefore, they cannot communicate.</blockquote><p>These limitations motivated the creation of the hierarchical category. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><h4>1.4.2. Hierarchical</h4><blockquote>It is the most common PKI category deployed in today’s organizations and the internet functioning is based on it.</blockquote><p>In such category, trust is established through the cooperation of multiple CAs. It is a tiered construction with subordinate CA relationships in which worldwide entities trust a single root CA <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_igLbT_OYUijf-1gvBMmA.png" /><figcaption>Figure 5: An illustration of certification path of a hierarchical PKI.</figcaption></figure><p>The root CA is responsible for issuing certificates to subordinate CAs only. It hashes subordinates certificates using a hash function and encrypts the obtained hash using its private key to create a digital signature for each issued certificate <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a>.</p><blockquote>The digital signature information is stored in the digital signature field of the issued certificate as shown in Figure1.</blockquote><p>The subordinates CAs can issue certificates to entities (i.e Alice) or other CAs in a lower level of the hierarchy. They use their corresponding hash functions to hash the issued certificates and their private keys to encrypt the obtained hashes to create a digital signature for each issued certificates <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZqEGMwFdxzmOUluJDsSMA.png" /><figcaption>Figure 6 : Certification Path <a href="https://venafi.com/blog/how-does-browser-trust-certificate/"><strong>[7]</strong></a></figcaption></figure><blockquote>Each certificate has its own digital signature and contains the public key and hash function used to obtain its digital signature. A Digital signature allows entities to authenticate each other through proving that the exchanged certificates have been issued by trusted authorities</blockquote><blockquote>If a CA is the entity of a certificate issued by another CA, the certificate is called a cross certificate. In hierarchical model,there are a number of cross certifications. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a></blockquote><blockquote>A list of cross certificates needed to allow trust establishment between two entities is known as a certification path <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a><strong>.</strong></blockquote><blockquote>A certification path is an ordered list of certificates starting with a certificate issued by the root CA and ending with the entity certificate that needs to be validated<em>.</em><a href="https://csrc.nist.gov/CSRC/media/Projects/PKI-Testing/documents/PKITS_v1_0_0.pdf"><em> </em><strong><em>[5][8]</em></strong></a></blockquote><blockquote>Certificate path validations are performed by algorithms known as certification validation algorithms. These algorithms verify that a given certificate path is valid under a given public key infrastructure (PKI). <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a></blockquote><p>The trust relationship is specified in only one direction and every certification path begins with the root CA’s public key. Hence, a direct trust should be established with the root CA in order for trust in the authenticity of a public key to be established. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><blockquote>Direct trust is the highest form of trust and it is obtained when entities<br>acquire public keys of CAs directly from the CA. It is therefore required by all other trust models to initialize trust. This implies that for any kind of architecture or trust model, there must exist some form of direct trust without which no trust can be initialized.<a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong><em>[5]</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*t0e7FnvInkLJYYGjeS3q5g.png" /><figcaption>Figure 7: Certificates Validation (authenticity checks)<strong> </strong><a href="https://venafi.com/blog/how-does-browser-trust-certificate/"><strong>[7]</strong></a></figcaption></figure><p>This arrangement allows a high level of control at all levels of the hierarchical tree. Thus, hierarchical models allow tight control over certificate-based activities. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[5]</strong></a></p><h4>1.5. Web browsers usage of PKI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jga3mDyUss1M7o9wA0OOgA.png" /><figcaption>Figure 8: An illustration of an hierarchical PKI</figcaption></figure><p>Based on Figure 8. Alice wants to access the server google.com :</p><ol><li>She uses its browser to initiate a communication with the server</li><li>The server sends its certificate to Alice’s browser. This certificates contains three embedded certificates: the server’s certificate, the CA1 certificate and the ROOT CA certificate.</li><li>Alice’s browser validates the server’s certification path as follows:</li></ol><ul><li>It checks its trusted store to get the ROOT CA public key (direct trust) and hash function information. It uses this public key to decrypt the digital signature of the received ROOT CA certificate to obtain a hash A. It uses the hash function information to hash the received ROOT CA certificate to obtain a hash B. Finally it compares the hash A and B. A validation is achieved if there’s a match. If no match is obtained, the session between Alice and the server will be terminated.</li><li>Once the ROOT CA certificate is validated and trusted. Its public key will be used to decrypt the digital signature of the received CA1 certificate to obtain a hash A. It uses the ROOT CA hash function information to hash the received CA1 certificate to obtain a hash B. Finally it compares the hash A and B. A validation is achieved if there’s a match. If no match is obtained, the session between Alice and the server will be terminated.</li><li>Once the CA1 certificate is validated and trusted. Its public key will be used to decrypt the digital signature of the server’s certificate to obtain a hash A. It uses the CA1 hash function information to hash the received server’s certificate to obtain a hash B. Finally it compares the hash A and B. A validation is achieved if there’s a match. If no match is obtained, the session between Alice and the server will be terminated.</li></ul><blockquote>Authenticity is verified once all certification paths are validated</blockquote><blockquote>The chain always commences with the certificate that is self-signed by the root CA.</blockquote><p>More information about how web browsers validate and trust certificates can be found here</p><ul><li><a href="https://shagihan.medium.com/what-is-certificate-chain-and-how-to-verify-them-be429a030887">What is Certificate chain? And how to validate Certificate chain</a></li><li><a href="https://venafi.com/blog/how-does-browser-trust-certificate/">How Does a Browser Trust a Certificate?</a></li></ul><h4>Conclusion</h4><p>A vital advantage of public-key cryptography over symmetric key cryptography is that it enables entities to communicate securely without<br>the need for prior introduction between the parties. This is possible because these entities are bound to unique public keys which are used to encrypt messages intended for them. Since trust is a major concern, the binding is done by third parties who are trust worthy or trusted by both sender and recipient. In a world of large population consisting of millions of entities, the most useful way to achieve this is to employ a reasonably small number of authorities trusted by the entire population. Thus, Public Key Infrastructure frameworks are crucial in providing authenticity when communicating over the internet. <a href="https://www.scirp.org/pdf/jis_2020092414573183.pdf"><strong>[6]</strong></a></p><p>To establish a secure communication and exchange data, entities follow a protocol. Protocols are like a common language for computers, similar to how two people from different parts of the world may not understand each other’s native languages, but they can communicate using a shared third language <strong>[9]. </strong>In networking, a protocol is a set of rules for formatting and processing data. It allows computers with different software and hardware to communicate<strong> [9]</strong>. For an end-to-end encrypted communication, The Transport Layer Security Protocol is used. It is impressively well explained in the following resources:</p><ul><li><a href="https://www.youtube.com/watch?v=25_ftpJ-2ME">TLS Handshake Deep Dive and decryption with Wireshark</a></li><li><a href="https://www.davidwong.fr/tls13/">A Readable Specification of TLS 1.3</a></li><li><a href="https://classes.pracnet.net/courses/practical-tls/">Practical TLS Course by Ed Harmoush</a></li></ul><h4>References</h4><ul><li><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1">[1] Kohnfelder, L.M. (1978) Towards a Practical Public Key Cryptosystem. MIT S.B. Thesis, Massachusetts Institute of Technology, Cambridge.</a></li><li><a href="https://dl.acm.org/doi/abs/10.1145/3549993.3550007">[2] Diffie, W. and Hellman, M.E. (1976) New Directions in Cryptography. IEEE Transactions on Information Theory,IT-22, 644–654.</a></li><li>[3] ITU-T (1993) The Directory — Overview of Concepts, Models and Service. X.500 Series of Recommendations, International Telecommunications Union, Geneva</li><li>[<a href="https://cpl.thalesgroup.com/faq/public-key-infrastructure-pki/what-public-key-infrastructure-pki">4] </a><em>What is PKI?</em> (n.d.). <a href="https://cpl.thalesgroup.com/faq/public-key-infrastructure-pki/what-public-key-infrastructure-pki">https://cpl.thalesgroup.com/faq/public-key-infrastructure-pki/what-public-key-infrastructure-pki</a></li><li>[5] Danquah, P., &amp; Kwabena-Adade, H. (2020). Public Key Infrastructure: An Enhanced Validation Framework. <em>Journal of Information Security</em>, <em>11</em>(4), 241–260.</li><li>[6] Albarqi, A., Alzaid, E., Al Ghamdi, F., Asiri, S., &amp; Kar, J. (2014). Public key infrastructure: A survey. <em>Journal of Information Security</em>, <em>6</em>(01), 31.</li><li>[7] V. (n.d.). <em>Browser &amp; Certificate Trust [Certificate Verification] | Venafi</em>. Venafi. <a href="https://venafi.com/blog/how-does-browser-trust-certificate/">https://venafi.com/blog/how-does-browser-trust-certificate/</a></li><li>[8] Adams, C. and Lloyd, S. (2003) Understanding Public-Key Infrastructure. Macmil-lan Technical Pub., Indianapolis</li><li>[9] <em>Just a moment. . .</em> (s. d.). <a href="https://www.cloudflare.com/learning/network-layer/what-is-a-protocol/">https://www.cloudflare.com/learning/network-layer/what-is-a-protocol/</a></li></ul><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd9ef868083" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/cryptography-part-ii-public-key-infrastructure-6cd9ef868083">Cryptography Part II : Public Key Infrastructure</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptography Part I : The Basics]]></title>
            <link>https://levelup.gitconnected.com/cryptography-part-i-the-basics-c6a8617bb0b5?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a8617bb0b5</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[symmetric-encryption]]></category>
            <category><![CDATA[asymmetric-encryption]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 17:46:44 GMT</pubDate>
            <atom:updated>2023-04-05T11:33:01.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cryptography Part I : The Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrHwEd__KZixtewnm-D6xw.jpeg" /></figure><h3>Introduction</h3><p>Entities have a legitimate need to not only encrypt their communication but also, verify the authenticity of individuals they communicate with and ensure the integrity of their exchanged messages. This is achieved through cryptography.</p><h4>1. Cryptography</h4><p>Cryptography is a set of methods with a fundamental objective of enabling two entities usually referred to as Alice and Bob to communicate over an insecure channel (i.e the internet) in such a way that a hacker, Oscar, cannot understand what is being said.</p><blockquote>In cryptography, encryption is the process of converting human-readable plaintext to incomprehensible text (known as ciphertext) <a href="https://www.cloudflare.com/learning/ssl/what-is-encryption/"><strong>[1]</strong></a>.</blockquote><p>The information that Alice wants to send to Bob, which we call plaintext, can be text, numerical data, or anything at all. Alice encrypts the plaintext, using a predetermined key and sends the resulting ciphertext over the insecure channel. Oscar, upon seeing the ciphertext in the channel, he cannot determine what the plaintext was. However, Bob, who knows the encryption key, can decrypt the ciphertext and reconstruct the plaintext<strong> </strong><a href="https://arxiv.org/ftp/math/papers/0510/0510057.pdf"><strong>[2]</strong></a>.</p><p>Within the context of communication over an insecure channel, the following security concepts must be guaranteed<strong> </strong><a href="https://d1wqtxts1xzle7.cloudfront.net/38411944/An_Overview_of_Cryptography.pdf?1438962673=&amp;response-content-disposition=inline%3B+filename%3DAn_Overview_of_Cryptography.pdf&amp;Expires=1676459909&amp;Signature=GAAp3xRuReDiyZ0FZ~bMZkoqoACQmbnsrJgVl~keadQmsAwFDPQLQPe6PvZv3EmNlSKQRHP9NWumFoEEtdc89R5MsIk65TSyvPqfCBMgfP76VTgS2gLhP4yRjHuFxEwp~F-ZzbU8Px68kT8MuhsxV73KKgr0q7VuDorriCD05r-RSIQ7iu3B~gYO4AoSnKwfUMjzpRr8-QlT~BZPJgTvuT2A65xI7lBI8jnzzRVYMCZLt~~fVdayUniJ1fvUHFtJPVdX6gJgKfvGRMZUtR46TVrLGMtkbnbDTvUTSP~9YBzmW5y452g5lKmXADZ1JmoOrXkyKl0ysJ3yuDGmnbA46w__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA"><strong>[3]</strong> </a>:</p><ul><li><strong><em>Authentication </em></strong>which consists of proving identity of entities willing to communicate through the insecure channel.</li><li><strong><em>Privacy / Confidentiality</em></strong><em> </em>which ensures that only the intended receiver can read the message</li><li><strong><em>Integrity </em></strong>which makes sure that the received message has not been altered from the original message</li><li><strong><em>Non-repudiation </em></strong>which proves that the sender really sent the message</li></ul><p>The above requirements are ensured through the use of three cryptographic schemes:</p><ul><li>Secret Key Cryptography (SKC or Symmetric)</li><li>Public Key Cryptography (PKC or Asymmetric)</li><li>Hash Functions (One-way Encryption)</li></ul><h4>1.1. Secret Key Cryptography (Symmetric)</h4><p>In <em>Symmetric Cryptography. </em>A single key is used for both encryption and decryption. Alice uses the key to encrypt the plaintext and sends the ciphertext to Bob. Bob applies the same key to decrypt the ciphertext to get the plaintext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmsSF5AWDVPkesSnZx2dPw.png" /><figcaption>Symmetric Key Cryptography</figcaption></figure><blockquote>At this point, once the plaintext has been received by Bob. How can Bob be certain that the plaintext has not been intercepted by Oscar ?</blockquote><p>It is impossible in this case to ensure <em>Privacy/Confidentiality </em>as any information sent through an insecure channel can be intercepted. This problem has led to the creation of <em>Asymmetric Cryptography</em>.</p><blockquote>It is worth mentioning that symmetric encryption is extremely useful and actually used in today’s cryptographic protocols such as TLS1.3. Details will be discussed in the TLS Article.</blockquote><h4>1.2. Public Key Cryptography (Asymmetric)</h4><p><em>Asymmetric Cryptography </em>is based on the usage of two pair of keys that are mathematically related. However, a knowledge of one key does not determine the other key <a href="https://d1wqtxts1xzle7.cloudfront.net/38411944/An_Overview_of_Cryptography.pdf?1438962673=&amp;response-content-disposition=inline%3B+filename%3DAn_Overview_of_Cryptography.pdf&amp;Expires=1676459909&amp;Signature=GAAp3xRuReDiyZ0FZ~bMZkoqoACQmbnsrJgVl~keadQmsAwFDPQLQPe6PvZv3EmNlSKQRHP9NWumFoEEtdc89R5MsIk65TSyvPqfCBMgfP76VTgS2gLhP4yRjHuFxEwp~F-ZzbU8Px68kT8MuhsxV73KKgr0q7VuDorriCD05r-RSIQ7iu3B~gYO4AoSnKwfUMjzpRr8-QlT~BZPJgTvuT2A65xI7lBI8jnzzRVYMCZLt~~fVdayUniJ1fvUHFtJPVdX6gJgKfvGRMZUtR46TVrLGMtkbnbDTvUTSP~9YBzmW5y452g5lKmXADZ1JmoOrXkyKl0ysJ3yuDGmnbA46w__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA"><strong>[3]</strong></a>. One key is used to encrypt the plaintext and the other one is used to decrypt the ciphertext <a href="https://d1wqtxts1xzle7.cloudfront.net/38411944/An_Overview_of_Cryptography.pdf?1438962673=&amp;response-content-disposition=inline%3B+filename%3DAn_Overview_of_Cryptography.pdf&amp;Expires=1676459909&amp;Signature=GAAp3xRuReDiyZ0FZ~bMZkoqoACQmbnsrJgVl~keadQmsAwFDPQLQPe6PvZv3EmNlSKQRHP9NWumFoEEtdc89R5MsIk65TSyvPqfCBMgfP76VTgS2gLhP4yRjHuFxEwp~F-ZzbU8Px68kT8MuhsxV73KKgr0q7VuDorriCD05r-RSIQ7iu3B~gYO4AoSnKwfUMjzpRr8-QlT~BZPJgTvuT2A65xI7lBI8jnzzRVYMCZLt~~fVdayUniJ1fvUHFtJPVdX6gJgKfvGRMZUtR46TVrLGMtkbnbDTvUTSP~9YBzmW5y452g5lKmXADZ1JmoOrXkyKl0ysJ3yuDGmnbA46w__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA"><strong>[3]</strong></a>.</p><blockquote><strong>Note</strong></blockquote><p><em>It doesn’t matter which key is applied first, but it is crucial to have both keys in order for the process of asymmetric cryptography to work </em><a href="https://d1wqtxts1xzle7.cloudfront.net/38411944/An_Overview_of_Cryptography.pdf?1438962673=&amp;response-content-disposition=inline%3B+filename%3DAn_Overview_of_Cryptography.pdf&amp;Expires=1676459909&amp;Signature=GAAp3xRuReDiyZ0FZ~bMZkoqoACQmbnsrJgVl~keadQmsAwFDPQLQPe6PvZv3EmNlSKQRHP9NWumFoEEtdc89R5MsIk65TSyvPqfCBMgfP76VTgS2gLhP4yRjHuFxEwp~F-ZzbU8Px68kT8MuhsxV73KKgr0q7VuDorriCD05r-RSIQ7iu3B~gYO4AoSnKwfUMjzpRr8-QlT~BZPJgTvuT2A65xI7lBI8jnzzRVYMCZLt~~fVdayUniJ1fvUHFtJPVdX6gJgKfvGRMZUtR46TVrLGMtkbnbDTvUTSP~9YBzmW5y452g5lKmXADZ1JmoOrXkyKl0ysJ3yuDGmnbA46w__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA"><strong><em>[3]</em></strong></a><em>.</em></p><p>The key pair owner should designate one of the keys as a <em>public key. </em>This key can be advertised over the insecure channel to different entities the owner wants to communicate with. The other key should be designated as <em>private key</em> and should be kept secret and never be revealed to other entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96TT-tyaeWCB7QzZf8gQMg.png" /><figcaption>Asymmetric Key Cryptography</figcaption></figure><p>If Alice encrypt a plaintext with Bob’s public key and send the ciphertext to Bob. Bob will use his private key to decrypt Alice’s ciphertext.</p><blockquote>Now, once the plaintext has been received by Bob. How can Bob be certain that the plaintext has not been modified by Oscar ?</blockquote><p>Encryption would be useless if a ciphertext can be decrypted with a public key but it is worth noting that a plaintext encrypted with Alice’s private key can only be decrypted with Alice’s public key.</p><p>The fact that Alice’s ciphertext can be decrypted with Alice’s public key means that it must has been encrypted with Alice’s private private key. This gives Bob a very high confidence that the message was created by Alice (<em>Authenticity</em>), and that the message was not altered in transit (<em>Integrity</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwE9BtTTfPCzn7-CVHh-2Q.png" /><figcaption>An example of proving Authenticity and Integrity</figcaption></figure><blockquote><strong>Important</strong></blockquote><p><em>The PKC complexity and execution time are correlated with the length of the plaintext which means as the plaintext’s length grows, the PKC execution time expands which is useless in today’s word. Moreover, if the length of the plaintext is very short, the encryption methods will be easy to compromise.</em></p><p><em>Thus, it was important to find an alternative for proving integrity in a short amount of time and independently of the plaintext’s length. This problem has led to the creation of Hash Functions.</em></p><h4>1.3. Hash Functions</h4><p>A Hash function is an algorithm that takes a plaintext and converts it into a fixed length hash that makes it impossible to recover either the plaintext or its length.</p><blockquote>It is worth noting that no matter how many characters long the plaintext is, the output length will always remain the same.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBnQ8r8miVR6hs_tNE2ZyA.png" /><figcaption>Cryptographic Hash Functions</figcaption></figure><p>Hash functions are mainly used to provide a <em>digital signatu</em>res which ensure <em>data integrity </em><a href="https://www.youtube.com/watch?v=b4b8ktEV4Bg"><strong>[4]</strong></a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgrdJDRMr59XLdtZ_QlNag.png" /><figcaption>Digital Signature</figcaption></figure><p>Based on the above Figure. Alice performs the following :</p><ul><li>She uses a hash function X to compute a hash of the plaintext she wants to send to Bob.</li><li>She then encrypts the obtained hash with her private key to get a digital signature of the plaintext she wants to send to Bob.</li><li>Furthermore, she encrypts the plaintext with its corresponding digital signature using Bob’s public key and send the obtained ciphertext over an insecure channel to Bob.</li></ul><p>Bob receives Alice’s ciphertext and performs the following:</p><ul><li>He decrypts the ciphertext using Bob’s private key to get the plaintext and the digital signature.</li></ul><p><em>At this stage, the important thing though is to verify the integrity of the plaintext. This is done as follows:</em></p><ul><li>Bob takes Alice’s digital signature and decrypts it using Alice’s public key to get the hash.</li><li>Bob uses the same hash function X as Alice and hashes the received plaintext to get a hash.</li><li>Bob compares the received hash with his locally computed hash to make sure that both hashes match.</li></ul><h3>Conclusion</h3><p>The major difficulty in initiating a public-key communication is reliably determining the correct encryption information to use (public key, encryption function etc) . Since these information are typically transmitted over unsecured channels the origin of encryption key and function transmissions is often questionable <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[6]</strong></a>.</p><ol><li><em>First, In order for the PKC to occur, Entities need to exchange their public keys. How can they be confident about the authenticity of the exchanged public keys ? In other words, how can Alice be confident that the received key is Bob’s public key and not Oscar’s </em><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[6]</strong></a><em>.</em></li><li><em>Furthermore, Entities need to exchange their public keys but also they need to learn each other’s encryption function. However, they cannot simply ask each other because a hacker could impersonate one of the communicants and give a false encryption function whose inverse would be known to the hacker </em><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[6]</strong></a><strong> </strong><em>which will allow him for example to derive the private key and intercept communication.</em></li><li><em>Finally, if Bob’s private key get compromised, Alice should no longer use Bob’s public key for encryption. However, there’s no public key revocation process in PKC.</em></li></ol><p>In order to address the above issues, Diffie and Hellman pointed out the problem of authenticating that a Public Key belongs to a real entity through the use of a<em> </em>trusted entity known as<em> Public File</em> <a href="https://dl.acm.org/doi/abs/10.1145/3549993.3550007"><strong>[5]</strong></a>. Furthermore, Kohnfelder <a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1"><strong>[6]</strong></a><strong> </strong>proposed to improve the <em>Public File </em>functioning through the use of <em>Digital Certificates</em> that authenticate entities. Finally, the International Telecommunication Union (ITU) decided to build a larger directory to cover all people and devices all over the world, so the result was a standard called <strong>X.500</strong> <a href="https://datatracker.ietf.org/doc/html/rfc1487"><strong>[7]</strong> </a>defining all characteristics of that directory. Another standard called <strong>X.509 </strong><a href="https://www.ietf.org/rfc/rfc5280.txt"><strong>[8</strong>]</a> was proposed for certificate to improve authentication.</p><p>Thus, all of these research has led to the creation of a Public Key Infrastructure (PKI) that will be discussed in the next article.</p><h3>References</h3><ul><li><a href="https://www.cloudflare.com/learning/ssl/what-is-encryption/">[1]</a> What is encryption? | Types of encryption</li><li><a href="https://arxiv.org/ftp/math/papers/0510/0510057.pdf">[2]</a> Cryptography and Encryption</li><li><a href="https://d1wqtxts1xzle7.cloudfront.net/38411944/An_Overview_of_Cryptography.pdf?1438962673=&amp;response-content-disposition=inline%3B+filename%3DAn_Overview_of_Cryptography.pdf&amp;Expires=1676459909&amp;Signature=GAAp3xRuReDiyZ0FZ~bMZkoqoACQmbnsrJgVl~keadQmsAwFDPQLQPe6PvZv3EmNlSKQRHP9NWumFoEEtdc89R5MsIk65TSyvPqfCBMgfP76VTgS2gLhP4yRjHuFxEwp~F-ZzbU8Px68kT8MuhsxV73KKgr0q7VuDorriCD05r-RSIQ7iu3B~gYO4AoSnKwfUMjzpRr8-QlT~BZPJgTvuT2A65xI7lBI8jnzzRVYMCZLt~~fVdayUniJ1fvUHFtJPVdX6gJgKfvGRMZUtR46TVrLGMtkbnbDTvUTSP~9YBzmW5y452g5lKmXADZ1JmoOrXkyKl0ysJ3yuDGmnbA46w__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA">[3]</a> An Overview of Cryptography</li><li><a href="https://www.youtube.com/watch?v=b4b8ktEV4Bg">[4]</a> Hashing Algorithms and Security — Computerphile</li><li><a href="https://dl.acm.org/doi/abs/10.1145/3549993.3550007">[5]</a> New Directions in Cryptography</li><li><a href="https://dspace.mit.edu/bitstream/handle/1721.1/15993/07113748.pdf?sequence=1">[6]</a> Towards a Practical Public-key Cryptosystem</li><li><a href="https://datatracker.ietf.org/doc/html/rfc1487">[7]</a><strong> </strong>X.500 Lightweight Directory Access Protocol</li><li><a href="https://www.ietf.org/rfc/rfc5280.txt">[8]</a> Internet X.509 Public Key Infrastructure Certificate</li><li><a href="https://www.youtube.com/watch?v=GSIDS_lvRv4">[9]</a> Public Key Cryptography</li><li>[<a href="https://www.youtube.com/watch?v=b4b8ktEV4Bg">10]</a> Hashing Algorithms and Security</li><li><a href="https://www.youtube.com/watch?v=s22eJ1eVLTU">[11]</a> Digital Signatures</li></ul><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a8617bb0b5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/cryptography-part-i-the-basics-c6a8617bb0b5">Cryptography Part I : The Basics</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus: Continuous Monitoring of SSL Certificates]]></title>
            <link>https://schh.medium.com/prometheus-continuous-monitoring-of-ssl-expiration-8406cf4df5a0?source=rss-129fe97ed115------2</link>
            <guid isPermaLink="false">https://medium.com/p/8406cf4df5a0</guid>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Sylia CHIBOUB]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 18:37:03 GMT</pubDate>
            <atom:updated>2021-09-28T07:19:13.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUlEkBC5obRxHI0mSfAEeA.jpeg" /><figcaption>Photos via <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><h3>Introduction</h3><p>Having a complete continious monitoring solution is crucial as it provides real-time feedback on the overall health of IT infrastructure including networks, applications and services deployed in the cloud or on-premises. Thus, i have covered through my previous articles the basics to get started with prometheus which is actually the most popular open-source monitoring software in the DevOps industry.</p><p><em>Checkout my previous articles in order to get started with prometheus, grafana and alertmanager:</em></p><blockquote><a href="https://medium.com/devops-dudes/install-prometheus-on-ubuntu-18-04-a51602c6256b">Getting Started with Prometheus and Grafana</a></blockquote><blockquote><a href="https://medium.com/devops-dudes/prometheus-alerting-with-alertmanager-e1bbba8e6a8e">Prometheus Alerting with AlertManager</a></blockquote><p>Today’s article expands the monitoring solution to cover not only the IT infrastructure, applications and services, but also SSL certificates.</p><p>Using valid SSL certificates is a must, and since SSL certificates have expiration dates, monitoring them for validity is critical to ensure not ending up with an invalid or expired certificate and consequently an insecure service.</p><p>This article is broken up into 3 separate sections :</p><ul><li>The setup of node-cert-exporter to monitor SSL certificates.</li><li>the setup of grafana dashboard to visualize SSL certificate expirations.</li><li>The setup of alert-manager to raise alerts when SSL certificates are about to expire.</li></ul><p>It is a continuation of the setup explained in my previous articles.</p><h3>The setup of node-cert-exporter</h3><ol><li>Install the node-cert-exporter from <a href="https://github.com/amimof/node-cert-exporter">github</a>,</li></ol><pre>wget https://github.com/amimof/node-cert-exporter/releases/latest/download/node-cert-exporter-linux-amd64</pre><p>2. Make the node-cert-exporter executable</p><pre>sudo mv node-cert-exporter-linux-amd64 /usr/local/bin <br>sudo chmod +x /usr/local/bin/node-cert-exporter-linux-amd64</pre><p>3. Create the node-cert-exporter user</p><pre>sudo useradd -rs /bin/false node-cert-exporter</pre><p>4. Make the node-cert-exporter user the owner of the exporter executable.</p><pre>sudo chown node-cert-exporter:node-cert-exporter /usr/local/bin/node-cert-exporter-linux-amd64</pre><p>5. Configure the node-cert-exporter service</p><pre>cd /lib/systemd/system<br>sudo nano node-cert-exporter.service</pre><p>Then put the following</p><pre>[Unit] <br>Description=Node Cert Exporter <br>Wants=network-online.target <br>After=network-online.target<br>  <br>[Service] <br>Type=simple <br>User=node-cert-exporter <br>Group=node-cert-exporter <br>ExecStart=/usr/local/bin/node-cert-exporter-linux-amd64 --path=&quot;put-here-the-path-to-your-ssl-certificates&quot; --listen your-ip:9117<br>Restart=always</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>6. Enable your service,start it and check its status</p><pre>sudo systemctl enable node-cert-exporter<br>sudo systemctl start node-cert-exporter<br>sudo systemctl status node-cert-exporter</pre><p>7. Checkout if the service works correctly</p><pre>curl http://your-ip:9117/metrics</pre><p>8. Binding the node-cert-exporter to Prometheus</p><p>You need to access to prometheus configuration file</p><pre>cd /etc/prometheus<br>sudo nano prometheus.yml</pre><p>Under the scrape_configs section of your prometheus configuration file, add a new entry for the cert exporter.</p><pre>- job_name: &#39;certs_exporter&#39;</pre><pre>static_configs:</pre><pre>- targets: [&#39;machine-ip:9117&#39;]</pre><p>machine-ip is the IP address of the machine on which the node-cert-exporter is running.</p><p>Restart Prometheus for your changes to be applied.</p><pre>sudo systemctl restart prometheus<br>sudo systemctl status prometheus</pre><h3>The setup of grafana dashboard</h3><p>In order to visualize the expiration dates of SSL certificates on a grafana dashboard, you need to import a <a href="https://grafana.com/grafana/dashboards/9999">pre-configured dashboard</a> to grafana.</p><blockquote>Checkout <a href="https://medium.com/devops-dudes/install-prometheus-on-ubuntu-18-04-a51602c6256b">Getting Started with Prometheus and Grafana</a> for more informations about the configuration of a grafana dashboard.</blockquote><h3>The setup of alert-manager</h3><p>As explained in <a href="https://medium.com/devops-dudes/prometheus-alerting-with-alertmanager-e1bbba8e6a8e">Prometheus Alerting with AlertManager</a>. In order to setup alerts when SSL certificates are about to expire, you need to edit the alert manager rule configuration file</p><pre>nano /etc/prometheus/alert.rules.yml</pre><p>Then add the following rule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s4dbLKC18EoTGrAnDSRJw.png" /></figure><p>The following configuration will fire an alert one month before SSL certificates expiration date.</p><blockquote>Following the configuration in my previous article on AlertManager, you can get alerts through mail, slack or checkout firing alerts directly on your prometheus interface.</blockquote><h3>Reference</h3><ul><li><a href="https://devconnected.com/how-to-check-ssl-certificate-expiration-with-grafana/">How To Check SSL Certificate Expiration with Grafana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8406cf4df5a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>