<?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 Tarik Yegen on Medium]]></title>
        <description><![CDATA[Stories by Tarik Yegen on Medium]]></description>
        <link>https://medium.com/@tarikyegen35?source=rss-e407fde46ec5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yyE0-OXb6Fj3yNPAlXGr0g@2x.jpeg</url>
            <title>Stories by Tarik Yegen on Medium</title>
            <link>https://medium.com/@tarikyegen35?source=rss-e407fde46ec5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:34:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tarikyegen35/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[Conscious Delivery With DevSecOps]]></title>
            <link>https://medium.com/@tarikyegen35/conscious-delivery-with-devsecops-5b6fa65535ec?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b6fa65535ec</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[conscious-delivery]]></category>
            <category><![CDATA[cloud-security]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 22:35:00 GMT</pubDate>
            <atom:updated>2024-09-30T05:35:19.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGa_uEQCsnP1kccTrSxzbw.png" /></figure><p>Let’s think about the classical DevOps concept first. The main purpose of DevOps was to remove the wall between software development and IT operations and to ensure that these two functions work more closely and harmoniously.</p><p>In the increasingly competitive digital world, companies had to quickly release new features and products. Traditional development and operations processes were slowing down the distribution of software and limited flexibility.</p><p>DevOps encouraged practices such as continuous integration (CI) and continuous delivery (CD), allowing software to be released more quickly and seamlessly. In this way, companies could enter the market faster.</p><p>However, security best practices were often overlooked or deprioritized in favor of speed. Over time, many companies, including large companies, started to pay compensation due to security vulnerabilities.</p><p>Governments continue to make legal regulations to protect personal data. This means that protecting PII and other sensitive data will become more important than ever. Companies that fail to do this may lose their credibility due to the security breaches they have caused and the compensation they have paid.</p><p>Today, the attack surface is much wider than before. Because it is no longer monolithic, we use modern applications in microservice architecture and run them in the Cloud environment.</p><p>Some organizations think they are protected because they use the Cloud infrastructure, but they are wrong. Security and Compliance is a shared responsibility between Cloud Providers and customers.</p><p><strong>And just as Security and Compliance is a shared responsibility between Cloud Providers and customers, security should be a shared responsibility among employees within the organization. That means that security shouldn’t be a dedicated job that only security team should deal with anymore. Developers should also have a security-first mindset while writing code.</strong></p><p>This is where the DevSecOps concept comes into play. Implementations of security controls carried out by security engineers right before releasing new features to the production environment slows down the classical DevOps cycle. We should remove that bottleneck. <strong>To that end, we integrate security throughout the entire SDLC starting from the earliest stage of the CI/CD pipeline.</strong></p><p><strong>With this DevSecOps concept, rapid deployment is not only maximized, but we also send feedback to the developer much earlier.</strong> With tools like Gitleaks, we move the classic DevOps after code commit paradigm further to the left and reach the pre-commit paradigm of DevSecOps. In other words, we make <strong>Conscious Delivery</strong>.</p><p><strong>Therefore, today organizations — in Thomas Kuhn’s terms — have to experience their own gestalt switches and they should be able to see the paradigm shift.</strong> <strong>This is essential for their credibility and their ability to stand out in the market.</strong></p><p>So, what should the roles be in the new, DevSecOps paradigm?</p><p><strong>Security Engineers;</strong></p><ul><li>Should provide guidance for employees in the organization and <strong>train</strong> them.</li><li>This type of training should include <strong>Threat Modeling</strong> and <strong>how to behave in daily life</strong>. Since threat modeling makes us systematically identify and mitigate potential risks, it will promote security-first mindset across the organization. As for daily life, bad people may sneak up on our employees pretending to be an ordinary person by dragging them into seemingly a normal conversation in order to gather sensitive data. By collecting PII about our employees, they may create phishing attacks based on that data. As we know, <strong>the more the attacker knows about you, the more convincing the phishing attack will be. We must not forget that attackers primarily target the accounts of employees within an organization.</strong></li><li>Create policies and select automation tools so that DevSecOps Engineers can implement them.</li></ul><p>As an architect of DevSecOps processes, <strong>DevSecOps Engineer;</strong></p><ul><li>Plays an intermediary role between different teams by bridging the gap between dev, ops and sec teams.</li><li>Doesn’t just build a bridge; he/she also create strong collaboration between these teams.</li><li>Provides guidance on secure coding standards, perform code reviews.</li><li>Takes business requirements and translate it into an action plan.</li><li>Facilitates knowledge sharing.</li><li>Makes security posture visible for development team.</li><li>Establishes mechanisms for continuous monitoring, threat detection and vulnerability scanning.</li><li>Has a broader approach by integrating security into the entire DevOps process, whereas sec engineers focus on securing systems, networks and infrastructure.</li><li><strong>Becomes an advocate for writing clean code.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b6fa65535ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Application Security Testing (DAST)]]></title>
            <link>https://medium.com/@tarikyegen35/dynamic-application-security-testing-dast-2f9d33fb10d0?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f9d33fb10d0</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[zed-attack-proxy]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 11:15:37 GMT</pubDate>
            <atom:updated>2024-09-03T11:44:02.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*M15hLVHp3mi2O_glLth4Bg.png" /></figure><p><strong>Dynamic Application Security Testing (DAST)</strong> involves evaluating the security of an application while it is running by simulating real-world attack scenarios. DAST mimics the behavior of a malicious external attacker, testing the application’s responses to various inputs and interactions.</p><p>However, unlike actual attacks, the primary goal of DAST is not to break into the system or cause disruption, but rather to identify vulnerabilities that could be exploited.</p><p>These tests are performed from an external perspective, focusing on how the application behaves in a live environment, detecting issues such as input validation flaws, security misconfigurations, and other runtime vulnerabilities.</p><p>Unlike Static Application Security Testing (SAST), it is a black box testing since there are no insights of application code.</p><p>It should be implemented in pre-production environments. We may automate this test in Continuous Delivery section in pipelines. In our example we use Zed Attack Proxy.</p><p><strong>Zed Attack Proxy (ZAP)</strong> is a free, open-source penetration testing tool. It is the world’s most widely used web app scanner. It is designed specifically for testing web applications.</p><p>There are two types of ZAP scans that we use: <strong>Baseline</strong> and <strong>Full Scan</strong>.</p><p>Upon deploying the app into test environment, we add following job to use ZAP Baseline Scan:</p><pre>zap_baseline:<br>  stage: deploy-test<br>  needs: [&quot;deploy_test&quot;]<br>  image: ghcr.io/zaproxy/zaproxy:stable<br>  variables:<br>    ZAP_TARGET: &quot;http://98.81.170.203:3000&quot;<br>  before_script:<br>    - mkdir -p /zap/wrk<br>  script:<br>    - zap-baseline.py -t $ZAP_TARGET -g gen.conf -I -x baseline.xml<br>    - cp /zap/wrk/baseline.xml baseline.xml<br>  artifacts:<br>    when: always<br>    paths:<br>      - baseline.xml</pre><p>In this job, we write the scan report to a file named baseline.xml and create an artifact. In this way, we can upload this file to vulnerability management tools such as <a href="https://medium.com/@tarikyegen35/defectdojo-for-devsecops-1e1b34ee42f4">DefectDojo</a> and get better visualization.</p><p><strong>The IP address defined in the ZAP_TARGET variable is the IP address of the host on which the app we deployed in the test environment is running.</strong></p><p>You can see what the parameters in the script section mean in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*aGHgKxqC3UXYyRSZ9MSm0Q.png" /></figure><p>The ZAP Baseline scan is a script that is available in the ZAP <a href="https://www.zaproxy.org/docs/docker/about/">Docker</a> images.</p><p><strong>It runs the ZAP spider against the specified target for (by default) 1 minute and then waits for the passive scanning to complete before reporting the results.</strong></p><p>This means that the script doesn’t perform any actual ‘attacks’ and will run for a relatively short period of time. It is better for release pipelines in terms of fast delivery of new codes.<br> <br>After running the job, sample output becomes as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy42TpHrxXvIoOHJV0TXJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N50p6Bm9evMUesBBEji1hg.png" /></figure><p>There are seven Warns in the logs and developers should handle that by fixing related parts of app code.</p><p>As for ZAP Full Scan, we add the job as follows:</p><pre>zap_full:<br>  stage: deploy-test<br>  needs: [&quot;deploy_test&quot;]<br>  image: ghcr.io/zaproxy/zaproxy:stable<br>  variables:<br>    ZAP_TARGET: &quot;http://98.81.170.203:3000&quot;<br>  before_script:<br>    - mkdir -p /zap/wrk<br>  script:<br>    - zap-full-scan.py -t $ZAP_TARGET -g gen.conf -I -x zap.xml<br>    - cp /zap/wrk/zap.xml zap.xml<br>  artifacts:<br>    when: always<br>    paths:<br>      - zap.xml</pre><p><strong>It runs the ZAP spider against the specified target (by default with no time limit) followed by an optional ajax spider scan and then a full active scan before reporting the results.</strong></p><p>This means that the script does perform actual ‘attacks’ and can potentially run for a long period of time. <strong>However, there is a risk of affecting app’s behaviour. It should be implemented in its own, dedicated pipeline for comprehensive tests.</strong></p><p><strong>To inspect full pipeline:</strong><br><a href="https://gitlab.com/tariksk355/juice-shop-app/-/blob/feature/dast/.gitlab-ci.yml?ref_type=heads">https://gitlab.com/tariksk355/juice-shop-app/-/blob/feature/dast/.gitlab-ci.yml?ref_type=heads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f9d33fb10d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secrets Management in Kubernetes]]></title>
            <link>https://medium.com/@tarikyegen35/secrets-management-in-kubernetes-7db1371d110e?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db1371d110e</guid>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes-secret]]></category>
            <category><![CDATA[external-secrets-operator]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 13:49:26 GMT</pubDate>
            <atom:updated>2024-08-25T13:49:26.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvZeb4D5OwYCQrERSrzIpg.png" /></figure><p>Since we need to use automated workflow in the DevOps approach and we provide deployment with the GitOps approach, we cannot put the manifest files containing our credentials in Git repo. That is, we cannot commit Secret manifests.</p><p>CI/CD platforms like GitLab are not secret stores as well. Secrets should not be stored in pipeline settings as there is an increased risk of being exposed.<br>Moreover, local computers of users are not secure to store secrets. We shouldn’t allow them to keep secrets locally.</p><p>So, how can we store secrets securely if the Secret Object in Kubernetes doesn’t provide encryption? This component only offers encoding with base64. However, base64 encoded credentials can easily be decoded. <strong>We need to encrypt the data.</strong></p><p>That’s where the <strong>External Secrets Operator (ESO)</strong> comes in. It is a Kubernetes operator that integrates external secret management systems like <strong>AWS Secrets Manager, HashiCorp Vault </strong>and<strong> </strong>so on. The operator reads information from external APIs and automatically injects the values into a Kubernetes Secret (1)</p><p>ESO is a collection of CRDs such as <strong>ExternalSecret, SecretStore </strong>and <strong>ClusterSecretStore</strong>. In our case, we use ClusterSecretStore and ExternalSecret.</p><p>Secret Management tools (AWS Secrets Manager, HashiCorp Vault etc.) and Credentials are defined in ClusterSecretStore CRD. It provides a central gateway to your secret provider and can be referenced by all namespaces.</p><pre>apiVersion: external-secrets.io/v1beta1<br>kind: ClusterSecretStore<br>metadata:<br>  name: aws-secret-store<br>spec:<br>  provider:<br>    aws:<br>      service: SecretsManager<br>      region: us-east-1<br>      auth:<br>        jwt:<br>          serviceAccountRef:<br>            name: externalsecrets-sa<br>            namespace: online-boutique</pre><p>In terms of secret backend we use AWS Secrets Manager. It offers;</p><p>· Encryption at rest and in transit</p><p>· Storing secrets centrally</p><p>· Fine-grained Access control</p><p>· Audit and Compliances</p><p><strong>AWS Secrets Manager makes the encryption of data with the help of AWS Key Management Service (KMS).</strong></p><p>In order to fetch secrets from AWS Secrets Manager, we need to create <strong>ServiceAccount</strong> and <strong>IAM Role</strong>. After that, <strong>we should map that K8s component to IAM Role. IAM Role should only have read-only policy.</strong></p><pre># role to access AWS secrets manager<br>resource &quot;aws_iam_role&quot; &quot;externalsecrets-role&quot; {<br>  name = &quot;externalsecrets_sa_role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = [&quot;sts:AssumeRoleWithWebIdentity&quot;]<br>        Effect = &quot;Allow&quot;<br>        Sid    = &quot;&quot;<br>        // all services within EKS can assume this role<br>        Principal = {<br>          Federated = module.eks.oidc_provider_arn<br>        }<br>      },<br>    ]<br>  })<br><br>  inline_policy {<br>    name = &quot;externalsecrets_sa_policy&quot;<br><br>    policy = jsonencode({<br>      Version = &quot;2012-10-17&quot;<br>      Statement = [<br>        {<br>         // Read access to all secrets in the secrets manager<br>          Effect   = &quot;Allow&quot;<br>          Resource = &quot;*&quot;<br>          Action   = [<br>           &quot;secretsmanager:GetRandomPassword&quot;,<br>      &quot;secretsmanager:GetResourcePolicy&quot;,<br>       &quot;secretsmanager:GetSecretValue&quot;,<br>       &quot;secretsmanager:DescribeSecret&quot;,<br>       &quot;secretsmanager:ListSecretVersionIds&quot;,<br>       &quot;secretsmanager:ListSecrets&quot;,<br>       &quot;secretsmanager:BatchGetSecretValue&quot;<br>         ]<br>        },<br>      ]<br>    })<br>  }<br>}</pre><p><strong>AWS does not recognize EKS’s K8s components. Therefore, components such as ServiceAccount can AssumeRole via EKS’s OIDC. That is, EKS becomes an intermediary between K8s and AWS.</strong></p><pre># service account that can assume aws externalsecrets-role<br>resource &quot;kubernetes_service_account&quot; &quot;externalsecrets-sa&quot; {<br>  depends_on = [ aws_iam_role.externalsecrets-role ]<br>  metadata {<br>    name = &quot;externalsecrets-sa&quot;<br>    namespace = &quot;online-boutique&quot;<br><br>    annotations = {<br>      &quot;eks.amazonaws.com/role-arn&quot; = aws_iam_role.externalsecrets-role.arn<br>    }<br>  }<br>}</pre><p>As for ExternalSecret, it specifies what secret to fetch. It references ClusterSecretStore. <strong>The External Secrets Operator uses ExternalSecret CRD in order to create secrets.</strong></p><pre>apiVersion: external-secrets.io/v1beta1<br>kind: ExternalSecret<br>metadata:<br>  name: stripe-api-secret<br>spec:<br>  refreshInterval: &quot;10m&quot;<br>  secretStoreRef:<br>    name: aws-secret-store<br>    kind: ClusterSecretStore<br>  <br>  target:<br>    name: stripe-api-key<br><br>  data:<br>  - remoteRef:<br>      key: stripe-api-key<br>      property: stripe-key<br>    secretKey: stripe-key</pre><p>I want to draw your attention to the <strong>refreshInterval: “10m”</strong> line above. In this scenario, K8s will check the secret stored in AWS Secrets Manager every 10 minutes. If it detects an update in the value, it will fetch that data and apply it in Secret object accordingly.</p><p>In our example, we create a stripe API key for the payment service and define a value. (Stripe is used to accept payments online and in person.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfGA6R7z8mpefb76692fLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCLqIK_tsp7p4K4f0F-Ltg.png" /></figure><p>We reference that secret (stored in AWS Secrets Manager) in the env section of Deployment object of payment service (2)</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: paymentservice<br>spec:<br>  selector:<br>    matchLabels:<br>      app: paymentservice<br>  template:<br>    metadata:<br>      labels:<br>        app: paymentservice<br>    spec:<br>      serviceAccountName: default<br>      terminationGracePeriodSeconds: 5<br>      securityContext:<br>        fsGroup: 1000<br>        runAsGroup: 1000<br>        runAsNonRoot: true<br>        runAsUser: 1000<br>      containers:<br>      - name: server<br>        securityContext:<br>          allowPrivilegeEscalation: false<br>          capabilities:<br>            drop:<br>              - ALL<br>          privileged: false<br>          readOnlyRootFilesystem: true<br>        image: gcr-paymentservice<br>        ports:<br>        - containerPort: 50051<br>        env:<br>        - name: PORT<br>          value: &quot;50051&quot;<br>        - name: DISABLE_PROFILER<br>          value: &quot;1&quot;<br>        - name: STRIPE_SECRET_AWS<br>          valueFrom:<br>            secretKeyRef:<br>              name: stripe-api-key<br>              key: stripe-key<br>        readinessProbe:<br>          grpc:<br>            port: 50051<br>        livenessProbe:<br>          grpc:<br>            port: 50051<br>        resources:<br>         requests:<br>           cpu: 100m<br>           memory: 64Mi<br>         limits:<br>           cpu: 200m<br>           memory: 128Mi</pre><p>Upon triggering the pipeline, ArgoCD detects the changes in the GitOps repo and applies them to K8s cluster and our Secret object gets created as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cF8Dqnw__uyoZyO0PoBTtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*5rDEvKzZsNc7DWHCLH1gZw.png" /></figure><p><strong>Notes:</strong></p><p><strong>(1) </strong><a href="https://external-secrets.io/latest/"><strong>https://external-secrets.io/latest/</strong></a></p><p><strong>(2) </strong><a href="https://gitlab.com/tariksk355/online-boutique-gitops/-/blob/main/base/paymentservice.yaml?ref_type=heads"><strong>https://gitlab.com/tariksk355/online-boutique-gitops/-/blob/main/base/paymentservice.yaml?ref_type=heads</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db1371d110e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy as Code: OPA Gatekeeper]]></title>
            <link>https://medium.com/@tarikyegen35/policy-as-code-opa-gatekeeper-1142dd33d077?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1142dd33d077</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <category><![CDATA[open-policy-agent]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 22:21:13 GMT</pubDate>
            <atom:updated>2024-08-18T22:21:13.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*4B92kqwXwqz4QFUV26fjFQ.png" /></figure><p>In software development, some developers may not know the security best practices, especially when preparing Kubernetes manifest files. For example, despite using tools like Trivy to detect security vulnerabilities in the Docker image during the CI phase, they may overwrite the image in the manifest files, granting root permissions to the container. So, misconfigured manifest files may still be committed and automatically pulled by ArgoCD. However, K8s admins want to prevent product teams from pushing misconfigurations.</p><p>With <strong>Policy as Code</strong>, it is possible to prevent them from doing this. With this approach, we can apply organization-specific security policies. However, doing these security checks manually is not possible, it takes too much time and burden. It is important to automate this, just as we automate it in DevOps. This is where <strong>Open Policy Agent (OPA)</strong> and <strong>Gatekeeper</strong> come into play.</p><p>Gatekeeper is a customizable admission webhook for Kubernetes that enforces policies executed by the Open Policy Agent (OPA), a policy engine for Cloud Native environments hosted by CNCF.</p><p>Normally, OPA and Gatekeeper are different tools, but both were developed by the same engineers and do the same thing. <strong>Gatekeeper is K8s specific, whereas OPA is general-purposed.</strong> In this article, we will see how to use Gatekeeper.</p><p>Gatekeeper enables us to validate K8s manifest files before deployment. It is a K8s-native admission controller. It has two main components: Controller Manager (Admission Controller) and Audit. <strong>Admission controller intercepts requests to the K8s API Server and can allow or reject the request based on some criteria.</strong></p><p>During the installation of Gatekeeper, it creates several <strong>CRDs</strong>. This makes us use two components to enforce policies: <strong>Constraint Template</strong> and<strong> Constraint</strong>.</p><p>In our case, it is enough to use a <strong>helm_release</strong> resource in Terraform by creating a separate configuration file in order to install Gatekeeper:</p><pre>resource &quot;helm_release&quot; &quot;gatekeeper&quot; {<br>  name                 = &quot;openpolicyagent&quot;<br>  namespace            = &quot;openpolicyagent&quot;<br>  repository           = &quot;https://open-policy-agent.github.io/gatekeeper/charts&quot;<br>  chart                = &quot;gatekeeper&quot;<br>  version              = &quot;3.15.0&quot;<br>  create_namespace     = true<br>  depends_on           = [ module.eks, module.vpc ]<br>}</pre><p>Let’s say that we want to define a policy that prevents the use of NodePort service type and giving root priviliges to containers, which is a bad practice that should be avoided in terms of internal services in K8s. To do this, we first need to create a <strong>Constraint Template</strong> and define the policy in the <strong>Rego</strong> section. Rego is from the Golang language family. This is the main section of the Constraint Template. We can use the <strong>Gatekeeper library</strong> while defining a policy. There are ready-made policies there. <strong>(1)</strong></p><p>In order to block NodePort usage:</p><pre>apiVersion: templates.gatekeeper.sh/v1<br>kind: ConstraintTemplate<br>metadata:<br>  name: k8sblocknodeport<br>  annotations:<br>    metadata.gatekeeper.sh/title: &quot;Block NodePort&quot;<br>    metadata.gatekeeper.sh/version: 1.0.0<br>    description: &gt;-<br>      Disallows all Services with type NodePort.<br><br>      https://kubernetes.io/docs/concepts/services-networking/service/#nodeport<br>spec:<br>  crd:<br>    spec:<br>      names:<br>        kind: K8sBlockNodePort<br>  targets:<br>    - target: admission.k8s.gatekeeper.sh<br>      rego: |<br>        package k8sblocknodeport<br><br>        violation[{&quot;msg&quot;: msg}] {<br>          input.review.kind.kind == &quot;Service&quot;<br>          input.review.object.spec.type == &quot;NodePort&quot;<br>          msg := &quot;User is not allowed to create service of type NodePort&quot;<br>        }</pre><p>In order to prevent the creation of containers with root priviliges:</p><pre>apiVersion: templates.gatekeeper.sh/v1<br>kind: ConstraintTemplate<br>metadata:<br>  name: k8spspprivilegedcontainer<br>  annotations:<br>    metadata.gatekeeper.sh/title: &quot;Privileged Container&quot;<br>    metadata.gatekeeper.sh/version: 1.0.1<br>    description: &gt;-<br>      Controls the ability of any container to enable privileged mode.<br>      Corresponds to the `privileged` field in a PodSecurityPolicy. For more<br>      information, see<br>      https://kubernetes.io/docs/concepts/policy/pod-security-policy/#privileged<br>spec:<br>  crd:<br>    spec:<br>      names:<br>        kind: K8sPSPPrivilegedContainer<br>      validation:<br>        openAPIV3Schema:<br>          type: object<br>          description: &gt;-<br>            Controls the ability of any container to enable privileged mode.<br>            Corresponds to the `privileged` field in a PodSecurityPolicy. For more<br>            information, see<br>            https://kubernetes.io/docs/concepts/policy/pod-security-policy/#privileged<br>          properties:<br>            exemptImages:<br>              description: &gt;-<br>                Any container that uses an image that matches an entry in this list will be excluded<br>                from enforcement. Prefix-matching can be signified with `*`. For example: `my-image-*`.<br><br>                It is recommended that users use the fully-qualified Docker image name (e.g. start with a domain name)<br>                in order to avoid unexpectedly exempting images from an untrusted repository.<br>              type: array<br>              items:<br>                type: string<br>  targets:<br>    - target: admission.k8s.gatekeeper.sh<br>      rego: |<br>        package k8spspprivileged<br><br>        import data.lib.exclude_update.is_update<br>        import data.lib.exempt_container.is_exempt<br><br>        violation[{&quot;msg&quot;: msg, &quot;details&quot;: {}}] {<br>            # spec.containers.privileged field is immutable.<br>            not is_update(input.review)<br><br>            c := input_containers[_]<br>            not is_exempt(c)<br>            c.securityContext.privileged<br>            msg := sprintf(&quot;Privileged container is not allowed: %v, securityContext: %v&quot;, [c.name, c.securityContext])<br>        }<br><br>        input_containers[c] {<br>            c := input.review.object.spec.containers[_]<br>        }<br><br>        input_containers[c] {<br>            c := input.review.object.spec.initContainers[_]<br>        }<br><br>        input_containers[c] {<br>            c := input.review.object.spec.ephemeralContainers[_]<br>        }<br>      libs:<br>        - |<br>          package lib.exclude_update<br><br>          is_update(review) {<br>              review.operation == &quot;UPDATE&quot;<br>          }<br>        - |<br>          package lib.exempt_container<br><br>          is_exempt(container) {<br>              exempt_images := object.get(object.get(input, &quot;parameters&quot;, {}), &quot;exemptImages&quot;, [])<br>              img := container.image<br>              exemption := exempt_images[_]<br>              _matches_exemption(img, exemption)<br>          }<br><br>          _matches_exemption(img, exemption) {<br>              not endswith(exemption, &quot;*&quot;)<br>              exemption == img<br>          }<br><br>          _matches_exemption(img, exemption) {<br>              endswith(exemption, &quot;*&quot;)<br>              prefix := trim_suffix(exemption, &quot;*&quot;)<br>              startswith(img, prefix)<br>          }</pre><p>After this process, we need to create a <strong>Constraint </strong>file and reference the Constraint Template. Because the policy we define in the Constraint Template can only be enforced with a Constraint. <strong>For this, the kind section in the Constraint file must match the kind attribute in the spec section in the Constraint Template.</strong></p><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: K8sBlockNodePort<br>metadata:<br>  name: block-node-port<br>spec:<br>  match:<br>    kinds:<br>      - apiGroups: [&quot;&quot;]<br>        kinds: [&quot;Service&quot;]</pre><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: K8sPSPPrivilegedContainer<br>metadata:<br>  name: psp-privileged-container<br>spec:<br>  match:<br>    kinds:<br>      - apiGroups: [&quot;&quot;]<br>        kinds: [&quot;Pod&quot;]<br>    excludedNamespaces: [&quot;kube-system&quot;]</pre><p>After preparing these two files, you should send them to the GitOps repository and prepare the kustomization.yaml files and make the necessary adjustments accordingly.</p><p><strong>If we deploy the Constraint Template and Constraint CRDs at the same time via ArgoCD, we will get an error, because we have to deploy the Constraint Template first and then the Constraint.</strong></p><p>In the GitOps repository, we created a separate folder named platform for the administrative operator and added these two files to it. We also prepared another file named <strong>platform-argo-app.yaml</strong> to be visible in the ArgoCD UI:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: platform<br>  namespace: argocd<br>spec:<br>  project: default<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: default<br>  source:<br>    repoURL: https://gitlab.com/tariksk355/online-boutique-gitops.git<br>    path: platform<br>    targetRevision: main<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true<br>    syncOptions:<br>    - CreateNamespace=true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEgcoGXnGjZJ8qlRfSjMPw.png" /></figure><p>After applying Constraint Templates, we can observe that necessary <strong>CRDs</strong> are automatically created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZW4oVu6IPO1vpXFIM0YTg.png" /></figure><p>Now, let’s update the attribute to NodePort in a service (adservice) and see how Argo CD behaves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-NqgNiRQ9KlvHrvpF6X8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyKjwWnsJBaSqzbmcXnynQ.png" /></figure><p>As you can see, the policy we enforce does not allow the NodePort service type to deploy, and we automated this process. Here, <strong>Gatekeeper makes the decision, K8s enforces that decision.</strong> And the <strong>Out of Sync</strong> section tells us that the desire state and the actual state don’t match.</p><p>If you want to enforce other policies, for example, if you want to enforce setting resource limits for containers, you can find ready-made policies for that in the Gatekeeper library.</p><p><strong>Note:</strong></p><p><strong>(1) </strong><a href="https://open-policy-agent.github.io/gatekeeper-library/website/validation/block-nodeport-services"><strong>https://open-policy-agent.github.io/gatekeeper-library/website/validation/block-nodeport-services</strong></a></p><p><a href="https://open-policy-agent.github.io/gatekeeper-library/website/validation/privileged-containers"><strong>https://open-policy-agent.github.io/gatekeeper-library/website/validation/privileged-containers</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1142dd33d077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Deployment With ArgoCD]]></title>
            <link>https://medium.com/@tarikyegen35/secure-deployment-with-argocd-2ad775380057?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad775380057</guid>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[devsecops]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 01:38:34 GMT</pubDate>
            <atom:updated>2024-08-12T01:39:07.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wjpejewh4EgxEUUMNiFMg.png" /></figure><p>Argo CD is a declarative, GitOps continuous delivery tool for Kubernetes. It follows the <strong>GitOps</strong> pattern of using Git repositories as the source of truth for defining the desired application state.</p><p>In deployments made with the classical method (Jenkins etc.) without ArgoCD, it is necessary to install tools such as kubectl and helm. However, this is not required in deployments made using ArgoCD. Because while the classical method is push-based, <strong>ArgoCd is pull-based</strong>. With the help of its agent, it monitors the changes in the GitOps repo and applies to the K8s cluster automatically. That is, it compares the desired configuration in Git repo with the actual state in the cluster and makes them stay in sync.</p><p>In addition, in order to authenticate with cluster and cloud platforms in the classical method, it is necessary to give the relevant credentials to automation tools such as Jenkins, which creates both additional workload for configuration and a security vulnerability.</p><p>On the other hand, tools such as Jenkins do not provide visibility into the deployment status. They do not provide information about application health. However, <strong>ArgoCD comes with a fully-loaded web UI</strong> providing real-time view of application activity.</p><p>So, why do we still need Jenkins or GitLab? It seems like ArgoCD can easily replace them? Maybe, you started thinking like that. But… We still need CI part. ArgoCD can be used only CD part. So that’s why we still need other tools and platforms.</p><p>Now, let’s see how to set up and use ArgoCD:</p><p>First of all, as a best practice, it is necessary to keep the application source code and K8s manifest files in separate repositories. This is called separation of concerns.</p><p>ArgoCD deployed in the cluster should monitor the GitOps repo, that is, the repo where the K8s manifest files are located. The repo name where the application files are located is “online-boutique” in our example. The GitOps repo name is “online-boutique-gitops”. (1)</p><p>To deploy ArgoCD into the cluster, we created a <strong>helm-release</strong> in the configuration file named <strong>argocd.tf</strong> in the repo named “infra-automation-eks” (2)</p><pre>provider &quot;helm&quot; {<br>  kubernetes {<br>    host = module.eks.cluster_endpoint<br>    cluster_ca_certificate = base64decode(module.eks.cluster_certificate_authority_data)<br><br>    exec {<br>      api_version = &quot;client.authentication.k8s.io/v1beta1&quot;<br>      command = &quot;aws&quot;<br>      args = [&quot;eks&quot;, &quot;get-token&quot;, &quot;--cluster-name&quot;, module.eks.cluster_name]<br>    }<br>  }<br>}<br><br>resource &quot;helm_release&quot; &quot;argocd&quot; {<br>  name             = &quot;argocd&quot;<br>  repository       = &quot;https://argoproj.github.io/argo-helm&quot;<br>  chart            = &quot;argo-cd&quot;<br>  version          = &quot;6.4.0&quot;<br>  namespace        = &quot;argocd&quot;<br>  create_namespace = true<br>  depends_on       = [<br>    module.eks<br>  ]<br>}<br><br>resource &quot;kubernetes_secret&quot; &quot;argocd_gitops_repo&quot; {<br>  depends_on = [<br>    helm_release.argocd<br>  ]<br><br>  metadata {<br>    name = &quot;gitops-k8s-repo&quot;<br>    namespace = &quot;argocd&quot;<br>    labels = {<br>      &quot;argocd.argoproj.io/secret-type&quot; = &quot;repository&quot;<br>    }<br>  }<br><br>  data = {<br>    type: &quot;git&quot;<br>    url: var.gitops_url<br>    username: var.gitops_username<br>    password: var.gitops_password<br>  }<br><br>  type = &quot;Opaque&quot;<br>}</pre><p>ArgoCD needs to authenticate to be able to connect to the Git repo on GitLab platform. So, we need to create a K8s Secret object so that it holds repo credentials. For that, we use deploy token and define necessary variables in the Settings-CI/CD section of the project by using “TF_VAR_” prefix for three variables. When creating deploy token in GitLab, we should only give “read_repository” permission in order to comply with least privilege principle.</p><p>After deploying ArgoCD, we need to create <strong>Application CRD</strong>. The Application CRD is the Kubernetes resource object representing a deployed application instance in an environment. With that object, we will be able to define destination (GitOps repo) and see the app health and sync status in the UI. In the “online-boutique-argo-app.yaml” we defined CRD:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: online-boutique<br>  namespace: argocd<br>spec:<br>  project: default<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: default<br>  source:<br>    repoURL: https://gitlab.com/tariksk355/online-boutique-gitops.git<br>    path: overlays/dev<br>    targetRevision: main<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true<br>    syncOptions:<br>    - CreateNamespace=true</pre><p>When we connect to the cluster and enter the <em>kubectl get po -n argocd</em> command, we can access the UI via the argocd-server pod. Before that, we need to obtain the password we will use in the UI by entering the following command:</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p>To temporarily expose internal services and access the UI, port-forwarding should be used. Because <strong>ArgoCD is not accessible from outside</strong>. It is deployed with <strong>ClusterIP</strong> service.</p><p>For access management, port-forwarding permission should be given to the user using RBAC and broader permissions should be avoided. Even if they are admins, they should only have read-only permissions in the cluster and should not be able to make changes manually. Because changes in the cluster are only made automatically by ArgoCD. It should not be forgotten that <strong>DevOps is all about automation</strong>.</p><pre>kubectl port-forward -n argocd pods/argocd-server-697cb9d986-lxzh9 8080:8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCoMclJBw2bFYeFqPqzglg.png" /></figure><p>Use <strong>localhost:8080</strong> to see the UI. Username is “admin” and the password is what the relevant command returned in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtdfxE7dRyBXoVEl2yOGMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWsNPcGgDooQrERl9qJziw.png" /></figure><p>As you can see, we did not have to give any credentials to an external service like Jenkins. When we make any changes to the application, it is enough to push new codes to the “online-boutique” repo, which is the CI part, with the relevant git commands.</p><p>The CI pipeline, which is the trigger, triggers the CD pipeline in the “online-boutique-gitops” repo and updates this GitOps repo by transferring the necessary changes.</p><p>For the “online-boutique-gitops” project, we create a Project Access Token that we only give the write_repository permission. It should not be forgotten that creating separate tokens for each project/repo in GitLab is very important for security.</p><p>Using Kustomize in the GitOps repo, relevant customizations can be made without touching the original YAML files. So, no manual action is required. The ArgoCD agent deployed in the cluster notices the changes made in this repo and compares the desired state with the actual state, pulls the changes and applies them to the cluster. <strong>It uses K8s controllers for monitoring and comparing actual and desired states.</strong></p><p>With the help of its UI, we can observe the network of the created resources as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJDGvZlWBjQNcg8GbOJO9w.png" /></figure><p><strong>Notes:</strong></p><p>(1) <a href="https://gitlab.com/tariksk355/online-boutique-gitops">https://gitlab.com/tariksk355/online-boutique-gitops</a></p><p>(2) <a href="https://gitlab.com/tariksk355/infra-automation-eks/-/tree/feature/ArgoCD?ref_type=heads">https://gitlab.com/tariksk355/infra-automation-eks/-/tree/feature/ArgoCD?ref_type=heads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad775380057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Docker Security Best Practices]]></title>
            <link>https://medium.com/@tarikyegen35/implementing-docker-security-best-practices-c2e91b9e0006?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e91b9e0006</guid>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[trivy]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 02:05:31 GMT</pubDate>
            <atom:updated>2024-02-26T03:22:59.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xG1UXti_gtcYvSQt53BXLg.png" /></figure><p>Security is layered. It is not centralized. Security issues can arise at any stage of the Software Development Life Cycle (SDLC), making exploitation possible at all levels.</p><p>Let’s say you carried out static application security tests and software composition analysis in the CI part of a DevSecOps pipeline and you are sure that your application code is secure after remediations. You want to build your image and deploy it. Can you confirm that your secure application’s runtime environment (container) is secure enough?</p><p>For implementing security best practices, you should configure Dockerfile as follows:</p><p>· Use specific version of a base image instead of using the latest version. Latest version may cause unexpected behaviour.</p><p>· Choose small sized, official base image, not a full-blown OS image. This is not only about storage or the speeding up of pull-push purposes, but also reducing the attack surface. Full-blown OS images have more security vulnerabilities. You may consider using alpine image as it is security-oriented and small-sized.</p><p>· Create a dedicated user and a group instead of using root user (default) permissions to follow the least privilege principle.</p><p>· Consider using multi-stage image builds. It is like sending a spacecraft to the moon. A spacecraft is thick while taking off. Because it needs certain tools wrapping it to take off. After a while, it releases them and becomes leaner. Same thing happens while implementing multi-stage builds. This will make the image small sized and reduce the attack surface. Separate the Dockerfile into two stages: Build stage and runtime stage.</p><p>· Create <strong>.dockerignore</strong> to explicitly exclude unnecessary files and folders. It has the same logic with .gitignore file. This will reduce the size of the image and prevent unintended secrets exposure. We don’t need everything inside the Docker image.</p><p>Upon building the Docker image, pushing it to DockerHub is an option. However, it will only provide one security layer for the image. Because, login to DockerHub account and repository are the same.</p><h3><strong>Defence in Depth</strong></h3><p>Unlike DockerHub, AWS ECR and Container Registry (CR) of GitLab offer two security layers. You first need to authenticate with AWS and then ECR service.</p><p>As for GitLab CR, after authenticating with GitLab account, you may consider using predefined variables to authenticate with CR. They will offer short-lived access to the registry, which is awesome from security perspective.</p><p>In the meantime, we need to continuously scan the Docker images in the container image repository. The image may be secure when scanned initially, but it could become unsafe after a few days. AWS ECR offers that feature.</p><p>However, we may add third security layer by adding an image scanning job to our CI/CD pipeline using <strong>Trivy</strong> tool. Trivy is the most popular open-source security scanner, reliable, fast, and easy to use. Use Trivy to find vulnerabilities &amp; IaC misconfigurations, SBOM discovery, Cloud scanning, Kubernetes security risks, and more. (1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnDtpAl91kBD-kajmahBwg.png" /></figure><p>In the image above, the logs of Trivy job are shown. As you see, fixed version of the base image is not available. So, you can not fix that security vulnerability by trying to update/upgrade its version. (Note that fixing security breaches is not a zero-sum game.)</p><p>One of the most important principles of software security is that <strong>no</strong> application or system is totally 100% guaranteed to be secure from all attacks. This may seem an unusually pessimistic starting point but it is merely acknowledging the real world; given enough time and enough resources any system can be compromised. The goal of software security is not ‘100% secure’ but to make it hard enough and the rewards small enough that malicious actors look elsewhere for systems to exploit. (2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTsvXAUX5o3PN8MfW5d9iA.png" /></figure><p>Just as I tried to draw attention to in Software Composition Analysis before, even if a library has a fixed version as shown in the image above, updating it may disrupt the general structure of the application. Therefore, this decision should be made by the developers.</p><p>Notes:</p><p>(1) <a href="https://trivy.dev/">https://trivy.dev/</a></p><p>(2) <a href="https://owasp.org/www-project-developer-guide/draft/foundations/security_principles/">https://owasp.org/www-project-developer-guide/draft/foundations/security_principles/</a></p><p>(3) To inspect my pipeline with Trivy:</p><p><a href="https://gitlab.com/tariksk355/juice-shop-app/-/tree/image_scan?ref_type=heads">https://gitlab.com/tariksk355/juice-shop-app/-/tree/image_scan?ref_type=heads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e91b9e0006" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Software Composition Analysis]]></title>
            <link>https://medium.com/@tarikyegen35/automated-software-composition-analysis-8e7a0b275fb9?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7a0b275fb9</guid>
            <category><![CDATA[retirejs]]></category>
            <category><![CDATA[vulnerability-management]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[defectdojo]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 23:33:27 GMT</pubDate>
            <atom:updated>2024-02-09T00:17:10.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aC6K6fZXrNbhDj8iNnv_RA.png" /></figure><p>Developers use many 3rd party dependencies during the application development phase. Therefore, the primary components of the completed application code consist of third-party open-source elements from external sources.</p><p>Since these dependencies are written by library developers, we cannot be sure that they are secure. The vulnerabilities in those libraries now become the vulnerabilities of our application. That’s why we also conduct a vulnerability scan for these libraries. For this, we use SCA tools, not SAST tools. (1)</p><p>There are various tools available per language. For JavaScript, for example, <em>npm audit</em> and <em>retire.js</em> are used. Retire.js is a popular open source scanner and maintains database of known vulnerabilities. It scans code of libraries in the node_modules folder. We will use <em>retire.js</em> in our example.</p><p>On the DefectDojo page where the Prototype pollution vulnerability, one of the retire.js findings, is located, it is shown which dependency is vulnerable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb8GfNEzlI1hxk8P6arn9g.png" /></figure><p>lodash.js is an indirect (transitive) dependency here, that is, it depends on another dependency. That dependency is sanitize-html. It is one of the direct dependencies under <em>package.json</em> file. (In JavaScript apps, dependencies are defined in that file.)</p><p><strong>Remediation</strong></p><p>One of the ways to fix a security vulnerability in a library is to update its version. However, it is the developer’s job to decide this, as alternative methods can also be used. Because updating 3rd party dependencies may break the application. Developers may need to update the actual code, and not just update the version. They need to test application after library upgrade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NF5Xwx4NH4wcAq_eV7D6TA.png" /></figure><p>In the References section, there are links containing information about which versions are vulnerable and which are safe. Updating indirect dependencies is done by updating the direct dependencies to which it depends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imeRot53f9iVZeE8cENN8w.png" /></figure><p>Libraries are frequently used by many companies and projects, which allows them to be constantly scanned for security vulnerabilities. This data is then stored in publicly accessible vulnerability databases. However, it should not be forgotten that these CVE (Common Vulnerabilities and Exposures) databases are also open to attackers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH7_NdcsqrDHD8BRTJ5SSA.png" /></figure><p>Additionally, a dependency that has been updated after remediation or a dependency that is not vulnerable today may be found to have a security vulnerability in the future. That’s why it is necessary to constantly stay up to date.</p><p>Notes:</p><p>(1) SAST tools scan your code for vulnerabilities, while SCA tools scan for vulnerabilities in your dependencies.</p><p>(2) To inspect my CI pipeline with SCA tool (retire.js) combined with SAST tools:</p><p><a href="https://gitlab.com/tariksk355/juice-shop-app/-/tree/feature/SCA_Scan?ref_type=heads">https://gitlab.com/tariksk355/juice-shop-app/-/tree/feature/SCA_Scan?ref_type=heads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7a0b275fb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DefectDojo for DevSecOps]]></title>
            <link>https://medium.com/@tarikyegen35/defectdojo-for-devsecops-1e1b34ee42f4?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1b34ee42f4</guid>
            <category><![CDATA[vulnerability-management]]></category>
            <category><![CDATA[defectdojo]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[application-security]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 01:31:25 GMT</pubDate>
            <atom:updated>2024-01-31T11:00:25.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZ64cpdrxh_9RmNx47ltmw.jpeg" /></figure><p>When we automate the security scanning of an application, the security tools we use can provide us with different findings. Therefore, for example, when performing security scanning of repositories and source codes written in Javascript, it is not enough to use only <em>GitLeaks</em> and <em>njsscan</em> tools; they should be combined with popular tools such as <em>semgrep</em> so that other tools can find the vulnerabilities that they cannot find. However, on DevSecOps platforms such as GitLab, the findings of these tools are not suitable for human consumption in job logs, they may look complicated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKTR0jf4DOyJCncf8JDgmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XR9NqBgPJw3wBw1nzo5ZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3quij8LBK432DRraOYdEg.png" /></figure><p>And here DefectDojo comes in. DefectDojo is a tool that will make all these security findings human readable and centralize them. By showing the location of the security breaches it helps us fix the problems in the app code.</p><p>Try out the demo server at <a href="https://demo.defectdojo.org/">demo.defectdojo.org</a></p><p>Log in with admin / 1Defectdojo@demo#appsec. Please note that the demo is publicly accessable and regularly reset. Do not put sensitive data in the demo.</p><p>DefectDojo is a security program and vulnerability management tool. It offers a UI. Thanks to its API, uploading of security findings can be automated by sending HTTP requests. Python script can be used to automatically upload the artifacts (in which the findings are recorded) to DefectDojo.</p><p>In our example, a token is used in the Python script as the API Authorization Header value. We can obtain the token from the <em>API v2 Key</em> section by clicking on the profile section at the top right of the page.</p><p>At the same time, it is necessary to create <em>Product </em>and <em>CI/CD Engagement</em> in the left-hand menu. Engagement ID is obtained from the url and entered into the python script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujeS04ovmaXDQsxSJHcjzA.png" /></figure><p>Python script for automation:</p><pre>import requests<br>import sys<br><br>file_name = sys.argv[1]<br>scan_type = &#39;&#39;<br><br>if file_name == &#39;gitleaks.json&#39;:<br>    scan_type = &#39;Gitleaks Scan&#39;<br>elif file_name == &#39;njsscan.sarif&#39;:<br>    scan_type = &#39;SARIF&#39;<br>elif file_name == &#39;semgrep.json&#39;:<br>    scan_type = &#39;Semgrep JSON Report&#39;<br><br><br>headers = {<br>    &#39;Authorization&#39;: &#39;Token dffc1eedf13c655522703607c556f1ead41c8448&#39;<br>}<br><br>url = &#39;https://demo.defectdojo.org/api/v2/import-scan/&#39;<br><br>data = {<br>    &#39;active&#39;: True,<br>    &#39;verified&#39;: True,<br>    &#39;scan_type&#39;: scan_type,<br>    &#39;minimum_severity&#39;: &#39;Low&#39;,<br>    &#39;engagement&#39;: 19<br>}<br><br>files = {<br>    &#39;file&#39;: open(file_name, &#39;rb&#39;)<br>}<br><br>response = requests.post(url, headers=headers, data=data, files=files)<br><br>if response.status_code == 201:<br>    print(&#39;Scan results imported successfully&#39;)<br>else:<br>    print(f&#39;Failed to import scan results: {response.content}&#39;)</pre><p>Thanks to DefectDojo, it is also possible to see the severity level of the security vulnerability. It shows us what kind of problem exists on which page and on which line. CWE (Common Weakness Enumeration) numbers correspond to elaboration of the most critical security issues in the OWASP Top Ten list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gi7gYOBGVNFxJvLoTc9khg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQHWA7goGEfjZMTPAX9QGQ.png" /></figure><p>In our example, after replacing the md5 in Gruntfile.js with sha256 and remediating the application against the SQL injection attack by using a placeholder instead of the relevant variable in the dbSchemaChallenge_3.ts file, we run the pipeline again and see a decrease in the findings as in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tt1ykvMF7BcsRHnRbdjA7Q.png" /></figure><p>Notes:</p><ul><li>In order to install DefectDojo: <a href="https://hub.docker.com/r/defectdojo/defectdojo-django">https://hub.docker.com/r/defectdojo/defectdojo-django</a></li><li>To inspect my pipeline: <br><a href="https://gitlab.com/tariksk355/juice-shop-app/-/tree/feature/upload-reports?ref_type=heads">https://gitlab.com/tariksk355/juice-shop-app/-/tree/feature/upload-reports?ref_type=heads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1b34ee42f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLeaks: A Secret Scanner Tool]]></title>
            <link>https://medium.com/@tarikyegen35/gitleaks-a-secret-scanner-tool-5cd9b6f1d367?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd9b6f1d367</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[gitleaks]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 23:27:49 GMT</pubDate>
            <atom:updated>2024-01-02T08:22:30.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9ef27h1g4FnlunOSKtmog.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/mohamed_hassan-5229782/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3671982">Mohamed Hassan</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3671982">Pixabay</a></figcaption></figure><p>In DevOps processes, automating the delivery of code changes and new features to end user seamlessly and frequently, with CI process where testing and build processes are carried out, and then the CD process where the deployment process is performed, has provided many advantages, but what about security?</p><p>“I wonder if I applied security best practice?” Isn’t that question a source of concern for many people in the field? If this isn’t a concern, it should be.</p><p>Because attacks on applications cause great financial and reputational damage to companies, and the number and type of attacks are increasing every day. And companies have realized that their expenses for application security are much less compared to the compensation they pay after attacks.</p><p>Here is the top ten of OWASP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arqkzAlo2p1nrAHHV9tjYA.png" /></figure><p>Isn’t performing security checks at the last stage of the application development process a step that both slows things down and is late? It would make more sense to implement security checks at every stage in the SDLC and automate them in the CI/CD pipeline.</p><p>In fact, it is already possible to take the DevOps process, which starts after the code commit, to the pre-commit stage with DevSecOps. Let’s briefly look at how this is done with <em>GitLeaks </em>tool, one of the secret scanning tools that scans source code and detects hard-coded secrets. <em>GitLeaks</em> is a fast, light-weight, portable, and open-source secret scanner for git repositories, files, and directories.</p><p>First of all, it is necessary to install <em>GitLeaks</em>, but thanks to Docker, we will avoid installing it manually depending on the OS. We are cloning OWASP’s Juice Shop application (1) in an Ubuntu EC2 instance with Docker installed.</p><p>Then create a file called <em>pre-commit</em> in the <em>hooks</em> folder in <em>.git</em> (hidden folder) and enter the following commands into it:</p><pre>docker pull zricethezav/gitleaks:latest<br>export path_to_host_folder_to_scan=/home/ubuntu/juice-shop<br>docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest detect --source=&quot;/path&quot; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SynkG08vO57L7UC096r9bQ.png" /></figure><p>Details of the above commands are available in the documentation of the <em>zricethezav/gitleaks</em> image on dockerhub. With the <em>detect</em> command, hard-coded secrets in the application at the<em> /home/ubuntu/juice-shop</em> path can be detected right before being pushed to the remote repository by the developer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58gJkmomkkn2oL-ZEQLuwQ.png" /></figure><p>( If you use — verbose, you will get detailed output. However, the output above is deliberately simplified, I did not use — verbose for simplicity)</p><p>If you see that output you can be sure that you could not git push your code changes. Fine…</p><p>But of course, you should not rely on developer. It is necessary to automate this work as a DevSecOps engineer and reflect it in the pipeline:</p><pre>variables:<br>    IMAGE_NAME: tariksk/demo-app<br>    IMAGE_TAG: juice-shop-1.1<br><br>stages:<br>    - cache<br>    - test<br>    - build<br><br>create_cache:<br>    stage: cache<br>    image: node:18-bullseye<br>    script:<br>        - yarn install<br>    cache: <br>        key: <br>            files:<br>                - yarn.lock<br>        paths:<br>            - node_modules/<br>            - yarn.lock<br>            - .yarn<br>        policy: pull-push<br>        <br>yarn_test:<br>    image: node:18-bullseye<br>    stage: test<br>    script:<br>        - yarn install<br>        - yarn test<br>    cache: <br>        key: <br>            files:<br>                - yarn.lock<br>        paths:<br>            - node_modules/<br>            - yarn.lock<br>            - .yarn<br>        policy: pull<br><br>gitleaks:<br>    stage: test<br>    image:<br>        name: zricethezav/gitleaks<br>        entrypoint: [&quot;&quot;]<br>    script:<br>        - gitleaks detect --verbose --source .<br><br><br>build_image:<br>    stage: build<br>    image: docker:24<br>    services:<br>        - docker:24-dind<br>    before_script:<br>        - echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin<br>    script:<br>        - docker build -t $IMAGE_NAME:$IMAGE_TAG .<br>        - docker push $IMAGE_NAME:$IMAGE_TAG</pre><p>According to this pipeline (.gitlab-ci.yml), if <em>GitLeaks </em>detects a secret in the source code, the pipeline will fail and the docker image cannot be built (next job will be skipped).</p><p>But the important point is this: The <em>Gitleaks </em>job which is performed in the pipeline takes place after the code commit, that is, after the developer pushes the relevant codes to the remote repository, that is, after it is too late!</p><p>Why is it late? Because even if you remove sensitive data later, the history in the repository remains intact! Therefore, using pre-commit hook is a more secure option.</p><p>Notes:</p><p>(1) <a href="https://owasp.org/www-project-juice-shop/">OWASP Juice Shop</a> is probably the most modern and sophisticated insecure web application! It can be used in security trainings, awareness demos, CTFs and as a guinea pig for security tools! Juice Shop encompasses vulnerabilities from the entire OWASP Top Ten along with many other security flaws found in real-world applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd9b6f1d367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K8s : Creating a Dedicated User (ServiceAccount) With Restricted Permissions for GitLab]]></title>
            <link>https://medium.com/@tarikyegen35/k8s-creating-a-dedicated-user-serviceaccount-with-restricted-permissions-for-gitlab-ff91c3daa3ce?source=rss-e407fde46ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff91c3daa3ce</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Tarik Yegen]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 20:13:15 GMT</pubDate>
            <atom:updated>2023-12-27T20:25:38.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKcaPIlXBBmpd_QxEGk3bg.png" /></figure><h3>K8s : Creating a Dedicated User (ServiceAccount) With Restricted Permissions for GitLab</h3><p>Is it right to give GitLab admin permission to run kubectl commands in pipelines? Imagine that GitLab has been hacked, with admin permissions, they will be able to do whatever they want within the cluster and cause huge damage. Therefore, for security best practice, it is necessary to restrict the permissions given to Gitlab and grant as many permissions as necessary. Cluster wide permission should not be given to perform limited tasks in a certain namespace.</p><p>So how should we grant these permissions? By creating a role and connecting it to the service account with rolebinding? So how do we attach this serviceaccount to GitLab? Is it necessary to use a token?</p><p>First of all, we need a kubeconfig file for the kubectl commands to work. As we know, kubeconfig is the default way to authenticate to a Kubernetes cluster. We need to restrict the admin privileges in the config file in the .kube folder in our cluster by preparing another config file. Later, we are gonna give that kubeconfig file that we will generate for the ServiceAccount to GitLab.</p><p>We first create a namespace named <em>myns</em> with the following command:</p><pre>kubectl create ns myns</pre><p>Then we create a file named <em>myrole.yaml</em> and write the following content:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: myns<br>  name: myrole<br>rules:<br>- apiGroups: [&quot;&quot;] # indicates the core API group<br>  resources: [&quot;pods&quot;, &quot;services&quot;, &quot;secrets&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;update&quot;, &quot;patch&quot;, &quot;delete&quot;]<br>- apiGroups: [&quot;extensions&quot;, &quot;apps&quot;]<br>  resources: [&quot;deployments&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;update&quot;, &quot;patch&quot;, &quot;delete&quot;]</pre><p>With the following command, we ensure that the role named myrole is created in the myns namespace. With this role, we will give the owner of the role the permission to perform get, list, watch, create, update, patch and delete operations for pod, service, secret and deployment objects.</p><pre>kubectl apply -f myrole.yaml</pre><p>Now it’s time to create a service account named <em>mysa</em>:</p><pre>kubectl create serviceaccount mysa --namespace=myns</pre><p>In order to bind the role and the ServiceAccount together, it is now necessary to create a Rolebinding named <em>myrb</em>:</p><pre>kubectl create rolebinding myrb \<br>  --role=myrole \<br>  --serviceaccount=myns:mysa \<br>  --namespace=myns</pre><p>What we need now is the authentication token for the service account. To do this, we first create a secret called <em>mysa-token</em>:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: mysa-token<br>  namespace: myns<br>  annotations:<br>    kubernetes.io/service-account.name: mysa<br>type: kubernetes.io/service-account-token</pre><pre>kubectl apply -f mysa-token.yaml</pre><p>With the following command, we get an output where we can display the token as follows:</p><pre>kubectl describe secrets mysa-token -n myns</pre><pre>Name:         mysa-token<br>Namespace:    myns<br>Labels:       &lt;none&gt;<br>Annotations:  kubernetes.io/service-account.name: mysa<br>              kubernetes.io/service-account.uid: a3d2579f-483a-4547-8ae9-a1797577fe34<br><br>Type:  kubernetes.io/service-account-token<br><br>Data<br>====<br>ca.crt:     1107 bytes<br>namespace:  4 bytes<br>token:      eyJhbGciOiJSUzXh________fT9qb4Zw</pre><p>To get the value of the service account authentication token in a MacOS, Linux, or Unix environment:</p><pre>TOKEN=`kubectl -n myns get secret mysa-token -o jsonpath=&#39;{.data.token}&#39; | base64 --decode`</pre><p>The following command adds the token of the ServiceAccount named mysa at the bottom of the $HOME/.kube/config file.</p><pre>kubectl config set-credentials mysa --token=$TOKEN</pre><p>Now, we can create a file called <em>gitlab-config.yaml</em>, copy and paste the content of the config file as it is, and return the config file to its previous state and maintain admin privileges on the cluster. The content of the new config file that we will give to GitLab, named gitlab-config.yaml:</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: LS0tLS1CRUdJTi_____DQVRFLS0tLS0K<br>    server: https://172.31.44.11:6443<br>  name: kubernetes<br>contexts:<br>- context:<br>    cluster: kubernetes<br>    user: mysa<br>  name: kubernetes-admin@kubernetes<br>current-context: kubernetes-admin@kubernetes<br>kind: Config<br>preferences: {}<br>users:<br>- name: kubernetes-admin<br>  user:<br>    client-certificate-data: LS0tLSV______tLS0tCg==<br>    client-key-data: LS0tLS_____URSBLRV0tLQo=<br>- name: mysa<br>  user:<br>    token: eyJhbGciOiJSUz_______Xaq8jX-nMfT9qb4Zw</pre><p>(Don’t forget to change the user section in the context section.)</p><p>It’s time to define the KUBECONFIG variable. If the KUBECONFIG environment variable doesn’t exist, kubectl uses the default kubeconfig file, $HOME/.kube/config. If the KUBECONFIG environment variable does exist, kubectl uses an effective configuration that is the result of merging the files listed in the KUBECONFIG environment variable. (1)</p><p>After using the <em>export KUBECONFIG=gitlab-config.yaml</em> command on the master node, try the <em>kubectl get po</em> command.</p><p>If your output is like that:</p><p>“Error from server (Forbidden): pods is forbidden: User “system:serviceaccount:myns:mysa” cannot list resource “pods” in API If you get the output of group “” in the namespace “default”</p><p>and</p><p>if you have no problems with the <em>kubectl get po -n myns</em> command, you are now ready to send the GitLab kubeconfig file by creating a variable named KUBE_CONFIG and putting the content of the config file as value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ux4rM3MoYymdfOy517hFlw.png" /></figure><p>Let’s ask the GitLab to create a secret object in a namespace called <em>my-micro-service</em> and see that the pipeline fails. Thus, we have verified that it cannot create the relevant objects in a namespace other than <em>myns </em>namespace. This is the security best practice…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81NxfrXudTeT4PuU46rtqQ.png" /></figure><p>Notes:</p><p>(1) <a href="https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/">https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff91c3daa3ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>