Easily create custom SAST guardrails with human language and Semgrep Assistant (AI)

Tell Semgrep Assistant about any organizational coding standards or best practices you want developers to implement - generated guidance will take this into account!

Nitin Nayar
October 9th, 2024
Share

Overview: Secure Guardrails 

Semgrep’s approach to SAST is two-pronged: make it easy for any developer to fix existing security issues today, and leverage secure guardrails to prevent new issues tomorrow. 

Guardrails gently nudge developers towards secure coding practices during development. With guardrails, developers don’t need extensive security expertise to write secure code, allowing them to concentrate more on building features and less on fixing recurring vulnerabilities.

Guardrails are very impactful for AppSec teams as well, greatly lowering the number of issues they need to triage (and even eliminating entire classes of vulnerabilities all together). 

For a deeper dive into Secure Guardrails, check out this technical blog by Isaac Evans, our CEO.

Overview: Semgrep Assistant & Assistant Memories 

Semgrep Assistant helps AppSec engineers and developers make faster, more accurate security decisions with less cognitive effort. By leveraging GPT-4’s understanding of code and Semgrep rules, it recommends autofix solutions for vulnerabilities, enabling quicker remediation.

The new Assistant Memories capability further enhances this by allowing organizations to customize remediation guidance to align with their specific coding standards. With Assistant Memories, you can save custom instructions on a per-project or per-rule basis, ensuring developers receive guidance that fits your internal security requirements.

So how does Assistant Memories work? Every organization has secure coding guidelines tailored to its business and technical needs. By default, Semgrep Assistant provides developers with AI-generated, tailored step-by-step instructions to quickly resolve issues. However, AppSec teams sometimes need to provide more specific guidance beyond the default Assistant recommendations. Assistant Memories allows AppSec teams to fine-tune AI-based remediation advice to align with their organization's specific guidelines. Let's look at this in action in the following real-world example.

Real-world example: securing Flask cookies

To better understand how Assistant Memories works, let’s explore a practical example with a Python Flask application.

Scenario: In Flask, the SESSION_COOKIE_SECURE flag controls whether cookies should only be sent over HTTPS. By default, it is set to False, making cookies vulnerable in production environments. Developers should always set this to True for enhanced security in production.

Imagine a developer pushes code without setting the secure cookie flag to True:

1from flask import Flask
2
3# Creating App
4
5app = Flask(__name__)
6
7@app.route('/setcookie', methods = ['POST', 'GET'])
8def setcookie():
9   resp = flask.make_response(render_template("index.html", input="View function called"))
10
11   # Here the Dev has set secure=False
12   resp.set_cookie('userID', user,  secure=False)
13
14   return resp

Semgrep will catch this issue as part of the PR scanning and provide devs with very helpful & tailored guidance to quickly fix the issue (as shown in the screenshots below).

Assistant tailored guidance

While the approach above is good, from an AppSec perspective, a more scalable solution would be to use middleware to enforce secure cookie settings across the entire application. We want the devs to use a centralized security approach using a custom response class MiddlewareSecureCookieResponse that you provide to all developers through your AcmeSecurityArch library. 

1class MiddlewareSecureCookieResponse(Response):
2    def set_cookie(self, key, value='', max_age=None, expires=None,   
3                   path='/', domain=None, secure=True, httponly=True, 
4                   samesite='Strict', **kwargs):
5        """Set cookie with secure flags."""
6        super().set_cookie(key, value, max_age=max_age, expires=expires, 
7                           path=path, domain=domain, secure=secure, 
8                           httponly=httponly, samesite=samesite, **kwargs)

This centralized approach ensures that all outgoing cookies, including those sent by clients or other parts of the application, follow secure best practices.

Leveraging Assistant Memories for Enhanced Remediation Guidance

Using Assistant Memories, you can tailor Semgrep’s remediation guidance to reflect the best practices of your organization. As we see in the example below, we can instruct the Assistant to recommend the middleware approach as the preferred solution.

By saving these instructions in Assistant Memories, developers are guided to use the custom MiddlewareSecureCookieResponse class from the AcmeSecurityArch library, ensuring security rules for cookies are consistently applied across all responses.


Here is an example of a memory an AppSec engineer could add in this case:

"Can we recommend an approach that uses middleware to automatically apply the secure cookie settings to every outgoing response, so you don't need to modify individual responses.

We have an internal custom response class MiddlewareSecureCookieResponse that the devs can import from the AcmeSecurityArch library.


Also, make sure to set MiddlewareSecureCookieResponse as the default response class for the app. So that from now on, every response will use this class to enforce the security rules for cookies.

And finally, register the middleware function to be called after every request is processed"


Now that we have provided additional instructions via Assistant Memories, let’s open a new PR with the same code and look at the guidance that Assistant gives to devs.

Assistant step-by-step instructions

This ensures the middleware automatically applies secure settings to every response, reducing the risk of human error and improving scalability. As we can see, in this case the Assistant guidance is tailored to use the secure guardrails and security best practices for your organization.

To summarize, Assistant Memories plays a key role in reinforcing Secure Guardrails. Every organization has unique secure coding guidelines, and a successful secure guardrails program must align with these practices. Generic & unhelpful remediation advice from SAST scans creates developer friction and causes developers to disengage. This makes it essential for SAST tools to offer customizable rules and guidance that adapt to an organization’s specific needs. The Assistant Memories feature is a powerful capability that enables you to add and save context-specific instructions, ensuring that Semgrep Assistant provides tailored remediation aligned with your internal policies. It not only strengthens secure guardrails but also streamlines secure development by reducing cognitive load and automating security best practices.

We’re excited to see how you use Assistant Memories to improve your organization’s security posture. Try it out and share your feedback!

About

Semgrep lets security teams partner with developers and shift left organically, without introducing friction. Semgrep gives security teams confidence that they are only surfacing true, actionable issues to developers, and makes it easy for developers to fix these issues in their existing environments.