Go programming language secure coding practices guide

Overview

You can download this book in the following formats: PDF, Mobi and ePub.

Introduction

Go Language - Web Application Secure Coding Practices is a guide written for anyone who is using the Go Programming Language and aims to use it for web development.

This book is collaborative effort of Checkmarx Security Research Team and it follows the OWASP Secure Coding Practices - Quick Reference Guide v2 (stable) release.

The main goal of this book is to help developers avoid common mistakes while at the same time, learning a new programming language through a "hands-on approach". This book provides a good level of detail on "how to do it securely" showing what kind of security problems could arise during development.

The Audience for this Book

The primary audience of the Go Secure Coding Practices Guide is developers, particularly the ones with previous experience with other programming languages.

The book is also a great reference to those learning programming for the first time, who have already finish the Go tour.

What You Will Learn

This book covers the OWASP Secure Coding Practices Guide topic-by-topic, providing examples and recommendations using Go, to help developers avoid common mistakes and pitfalls.

After reading this book, you'll be more confident you're developing secure Go applications.

About OWASP Secure Coding Practices

This book was adapted for Go Language from The Secure Coding Practices Quick Reference Guide, an OWASP - Open Web Application Security Project. It is a "technology agnostic set of general software security coding practices, in a comprehensive checklist format, that can be integrated into the development lifecycle" (source).

OWASP itself is "an open community dedicated to enabling organizations to conceive, develop, acquire, operate, and maintain applications that can be trusted. All of the OWASP tools, documents, forums, and chapters are free and open to anyone interested in improving application security" (source).

How to Contribute

This book was created using a few open source tools. If you're curious about how we built it from scratch, read the How To contribute section.

License

This document is released under the Creative Commons Attribution-ShareAlike 4.0 International license (CC BY-SA 4.0). For any reuse or distribution, you must make clear to others the license terms of this work. https://creativecommons.org/licenses/by-sa/4.0/

Issues
  • Missing develop branch

    Missing develop branch

    Hi,

    I'd like to submit a pull request but, according to your "How to contribute" guide, I should submit it to the develop branch:

    Once you're ready to merge your work with others, you should go to main repository and open a Pull Request to the develop branch.

    However, there is no such a branch in your repository. Could you create it or can I submit the pull request to the master branch?

    Thanks,

    Kevin

    enhancement question 
    opened by gilliek 9
  • Place older

    Place older "?" is true for mysql, not for postgresql

    https://github.com/Checkmarx/Go-SCP/blob/master/src/output-encoding/sql-injection.md

    It could be specified that postgresql use $1, $2, $2... and that mysql use ?, ?...

    customerId := r.URL.Query().Get("id")
    query := "SELECT number, expireDate, cvv FROM creditcards WHERE customerId = ?"
    
    stmt, _ := db.Query(query, customerId)
    Notice the placeholder1 ? and how your query is:
    
    question 
    opened by nicobouliane 7
  • suggestion: incorrect handling of database connections

    suggestion: incorrect handling of database connections

    On page:

    https://github.com/Checkmarx/Go-SCP/blob/c3471ef24a7c2ca6a769457783f43c60712f087a/database-security/connections.md

    sql.Open returns a database pool (not a connection). This can be closed just before the application exists, but databases will determine that the connections are closed when the OS terminates the network connections when the executable closes.

    Your example code (while won't compile as is), shows db.QueryRow. QueryRow does not need to be manually closed; it will be closed after a Scan. Furthermore throughout I highly recommend you use the Context variants, especially with a web application. When the context is canceled, a Tx will be rolled back if not committed, a Rows (from QueryContext) will be closed, and any resources will be returned. It is important to commit/rollback a Transaction or Close a Rows either explicitly or by canceling the context. However, the example Go code does not demonstrate this.

    enhancement 
    opened by kardianos 7
  • Gorilla Toolkit - vulnerable or not?

    Gorilla Toolkit - vulnerable or not?

    The portion about Input Validation, and specifically sanitation of the URL request path mentions a third party package called Gorilla Toolkit, but it does not specify whether this package is also vulnerable to path traversal attacks or whether it's preferred to use because perhaps it doesn't have this vulnerability.

    Can someone please advise on whether this package is also vulnerable so we can update this section to indicate that?

    opened by aaron-junot 6
  • Question about logging chapter

    Question about logging chapter

    Hi, I am a little bit don't understand the following paragraph on the logging chapter:

    ... Another issue with the native logger is that there is no way to turn logging on or off on a per-package basis.

    What do you mean about no way to turn logging on or off on a per-package basis. ?

    As I know, you can use log.SetOutput(ioutil.Discard) to disable logging output. The example code is following:

    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"log"
    )
    
    func main() {
    	fmt.Println("Hello, World.")
    	log.SetOutput(ioutil.Discard)
    	log.Print("Hello from log")
    }
    
    

    Or you mean this functionality does not contain inside the log package, which means you have to import io/ioutil package to achieve it ?

    Thanks.

    question 
    opened by kevingo 5
  • Somehow avoid passing nonce to decryption method

    Somehow avoid passing nonce to decryption method

    Hi,

    Thanks for this piece of work. The enc/dec example here requires the nonce to be known by both methods. Is there a way to avoid passing to dec method? Similar to this. See example below - same one from the doc but split into enc and dec methods.

    Thanks

    package main
    
    import (
    	"crypto/aes"
    	"crypto/cipher"
    	"crypto/rand"
    	"encoding/hex"
    	"fmt"
    )
    
    func main() {
    	msg := []byte("Hello World!")
    	key := []byte("a6df723a921fccda52bdc4ca50851559")
    
    	nonce := make([]byte, 12)
    	if _, err := rand.Read(nonce); err != nil {
    		panic(err.Error())
    	}
    	fmt.Println("NONCE:", hex.EncodeToString(nonce))
    
    	enc := enc(msg, key, nonce)
    	fmt.Println("ENC:", hex.EncodeToString(enc))
    
    	dec := dec(enc, key, nonce)
    	fmt.Println("DEC:", string(dec))
    }
    
    func enc(data, key, nonce []byte) []byte {
    	block, err := aes.NewCipher(key)
    	if err != nil {
    		panic(err.Error())
    	}
    
    	aesgcm, err := cipher.NewGCM(block)
    	if err != nil {
    		panic(err.Error())
    	}
    
    	return aesgcm.Seal(nil, nonce, data, nil)
    }
    
    // Somehow this method should avoid requiring `nonce`.
    func dec(enc, key, nonce []byte) []byte  {
    	block, err := aes.NewCipher(key)
    	if err != nil {
    		panic(err.Error())
    	}
    
    	aesgcm, err := cipher.NewGCM(block)
    	if err != nil {
    		panic(err.Error())
    	}
    
    	decrypted_data, err := aesgcm.Open(nil, nonce, enc, nil)
    	if err != nil {
    		panic(err.Error())
    	}
    
    	return decrypted_data
    }
    
    enhancement 
    opened by bentcoder 4
  • Needs more information on CSRF

    Needs more information on CSRF

    It feels like CSRF deserves more mention in this book. There's a brief note about it in the section on websockets and the sample HTML form in "Communicating authentication data" contains a CSRF token form field, but that's it.

    There's never a definition of CSRF, let alone strategies for managing or validating CSRF tokens.

    enhancement 
    opened by edsrzf 4
  • suggestion: be more precise in hashing language

    suggestion: be more precise in hashing language

    On page https://github.com/Checkmarx/Go-SCP/blob/b6faece923bfdccfcc04de1b3994752721ef1ce3/docs/cryptographic-practices/README.md

    both MD5 and SHA256 are discussed. SHA256 is stated to be "stronger".

    It may be more precise to say that "MD5 and SHA1 may be susceptible to hash collision attacks (making the same hash from different content), while SHA256 is not known to be susceptible to such collisions."

    opened by kardianos 4
  • License

    License

    Hi there,

    This looks like a great book, but you seem to have selected the GPL license for it. I'm not sure I understand how the GPL (which is a software license) would apply to a book. Perhaps you might like to consider one of the Creative Commons licenses instead?

    question 
    opened by mrpotes 3
  • Vague code description in system configuration section

    Vague code description in system configuration section

    In the system configuration section, the sample code demonstrate disable directory listing as follows:

    type justFilesFilesystem struct {
        fs http.FileSystem
    }
    
    func (fs justFilesFilesystem) Open(name string) (http.File, error) {
        f, err := fs.fs.Open(name)
        if err != nil {
            return nil, err
        }
        return neuteredReaddirFile{f}, nil
    }
    

    However, it does not provide neuteredReaddirFile type here, which only show in the files directory.

    How about describe neuteredReaddirFile type here that reader can easily copy&paste the sample code when reading the content here?

    If you feel ok, I can open a pull request to add it to the sample code.

    Thank you.

    enhancement 
    opened by kevingo 3
  • suggestion: do not demonstrate storing a password in plain text

    suggestion: do not demonstrate storing a password in plain text

    Examples should often take extra steps to be correct. When demonstrating how to display an error message to the user: https://github.com/Checkmarx/Go-SCP/blob/c3471ef24a7c2ca6a769457783f43c60712f087a/authentication-password-management/communicating-authentication-data.md

    The password check is apparently stored in plain text. I would recommend returning fields called PasswordHash and Salt then doing some fake calls to verify that against the given password in the example.

    enhancement 
    opened by kardianos 3
  • SHA256 for pass hashing?

    SHA256 for pass hashing?

    Should we remove the 1st example here in case someone doesn't read the rest of the page? https://github.com/OWASP/Go-SCP/blob/master/src/authentication-password-management/validation-and-storage.md

    opened by gsmcnamara-okta 0
  • Source for this?

    Source for this?

    "sequential authentication implementations (like Google does nowadays)" in https://github.com/OWASP/Go-SCP/blob/master/src/authentication-password-management/validation-and-storage.md

    opened by gsmcnamara-okta 0
  • Wrong reference links for hashing algorithms in validation-and-storage.md

    Wrong reference links for hashing algorithms in validation-and-storage.md

    In " Go-SCP/src/authentication-password-management/validation-and-storage.md " LINK the reference links for hashing functions are wrong.

    It should be something similar to:

    In the case of password storage, the hashing algorithms recommended by
    [OWASP][2] are [`bcrypt`][3], [`PDKDF2`][4], [`Argon2`][5] and [`scrypt`][6].
    
    [1]: ../cryptographic-practices/pseudo-random-generators.md
    [2]: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
    [3]: https://godoc.org/golang.org/x/crypto/bcrypt
    [4]: https://godoc.org/golang.org/x/crypto/pbkdf2
    [5]: https://github.com/p-h-c/phc-winner-argon2
    [6]: https://pkg.go.dev/golang.org/x/crypto/scrypt
    [7]: https://github.com/ermites-io/passwd
    
    bug 
    opened by xmpf 1
  • Incorrect Cryptography recommendations

    Incorrect Cryptography recommendations

    In the Cryptography Practices section we say the following:

    MD5 is the most popular hashing algorithm, but securitywise BLAKE2 is considered the strongest and most flexible.

    and

    To fight back, the hashing function should be inherently slow, using at least 10,000 iterations.

    MD5 is deprecated and insecure; we should never list it as a compliant sample. Additionally, iterated hashing is incorrect, and. we should recommend key stretching or some other mechanism for handling these scenarios. Lastly, there are no mentions of HMACs, which are the correct solution to authentication issues.

    I can help massage these sections with some input from our cryptographers.

    Additionally, we say:

    Please not that slowness is something desired on a cryptographic hashing algorithm.

    Which should be "Please note..."

    opened by lojikil 1
  • SQLi and templates

    SQLi and templates

    Most of the non-compliant Go SQL code I see is actually abuse of templates, rather than string joins. We should show non-compliance via templating as well, so that developers do not think that templating can necessarily save them here.

    enhancement 
    opened by lojikil 1
Owner
OWASP
The OWASP Foundation
OWASP
An open source, online coding platform that offers code practice and tutoring in 50 different programming languages

Exercism Golang En este repositorio voy a subir los ejercicios de la plataforma

Lucas Frontalini 0 Jan 7, 2022
OpenResty Best Practices

OpenResty 最佳实践 我们提供 OpenResty、Apache APISIX 以及 API 网关方面相关的咨询、培训、性能优化、定制开发等商业支持服务,欢迎联系。

WenMing 3.3k Jun 23, 2022
A cookbook with the best practices to working with kubernetes.

A cookbook with the best practices to working with kubernetes.

Diego Lima 1.3k Jun 26, 2022
Easily kick-start your python project with very opinionated best practices.

Pyproject Easily kickstart your Python project with very opionionated best practices. Manage your project using poetry https://python-poetry.org/ Add

Lucifer Chase 1 Jan 24, 2022
Static Analysis with Go - A Practitioner's Guide

Static Analysis with Go - A Practitioner's Guide Hi, and welcome to Static Analysis with Go - A Practitioner's Guide. This is a workshop about writing

Amit Davidson 43 Mar 3, 2022
This is from the udemy course: Go: The Complete Developer's Guide (Golang)

Go Udemy course - "Go: The Complete Developer's Guide (Golang)" How to run the file: go run hello-world.go go run <filename>.go GO CLI commands: go ru

null 1 Oct 22, 2021
📖 A little guide book on Ethereum Development with Go (golang)

?? A little guide book on Ethereum Development with Go (golang)

Miguel Mota 1.4k Jun 25, 2022
Go: The Complete Developer's Guide (Golang) Udemy Course by Stephen Grider

Go-The-Complete-Developers-Guide Go Command line tools 1. go build - compiles a bunch of go source code files go build

PramodRawate 0 Dec 29, 2021
Go-beginners-guide-project - golang beginners project from tutorialedge.net

Go Beginner's Project Running Locally If you want to run this application locally then run the following commands: $ go run cmd/cli/main.go Build Appl

Heriyanto 0 Jan 2, 2022
Practical concurrency guide in Go, communication by channels, patterns

Go Concurrency Guide This guide is built on top of the some examples of the book Go Concurrency in Go and Go Programming Language Race Condition and D

Lucas Alves 1.7k Jun 23, 2022
A repository for showcasing my knowledge of the Google Go (2009) programming language, and continuing to learn the language.

Learning Google Golang (programming language) Not to be confused with the Go! programming language by Francis McCabe I don't know very much about the

Sean P. Myrick V19.1.7.2 1 Nov 26, 2021
A repository for showcasing my knowledge of the Go! (2003) programming language, and continuing to learn the language.

Learning Go! (programming language) Not to be confused with Google Golang (2009) I don't know too much about the Go! programming language, but I know

Sean P. Myrick V19.1.7.2 1 Nov 26, 2021
Live coding a basic Go compiler with LLVM in 20 minutes

go2ll-talk The code presented at Sheffield Go, 7th March. Slides link To run, just say make. To take a look at the output of the program, run go run .

Peter Waller 259 Jun 15, 2022
💯 Materials to help you rock your next coding interview

Tech Interview Handbook Credits: Illustration by @leftaligned Read on the website Black Lives Matter. Support the Equal Justice Initiative What is thi

Yangshun Tay 72.4k Jun 25, 2022
high performance coding with golang(Go 语言高性能编程,Go 语言陷阱,Gotchas,Traps)

Go 语言高性能编程 订阅 最新动态可以关注:知乎 Go语言 或微博 极客兔兔 订阅方式:watch geektutu/blog ,每篇文章都能收到邮件通知,或通过 RSS 订阅。

Dai Jie 3.1k Jun 24, 2022
Coding along the book

Learn Go with Tests Art by Denise Formats Gitbook EPUB or PDF Translations 中文 Português 日本語 한국어 Türkçe Support me I am proud to offer this resource fo

null 0 Oct 30, 2021
Collection of coding examples from "Go In Practice"

Go In Practice Go In Practice 1. Noteworthy aspects of Go 2. A solid foundation 1. Noteworthy aspects of Go Multiple returns Named return values Read

Ignacio Herrera 0 Jan 3, 2022
Cracking the Coding Interview, 6th Ed

Cracking the Coding Interview, 6th Ed. In order to stay sharp, I try to solve a few of these every week. The repository is organized by chapter. Each

S. Elliott Johnson 0 Jan 26, 2022
The Little Go Book is a free introduction to Google's Go programming language

The Little Go Book is a free introduction to Google's Go programming language. It's aimed at developers who might not be quite comfortable with the idea of pointers and static typing. It's longer than the other Little books, but hopefully still captures that little feeling.

Dariush Abbasi 12.4k Jun 24, 2022