SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
13 Go security tips
Karthik Gaekwad - @iteration1
I’m Karthik
@iteration1
I speak
docker
golang
History of Go
• “Go is an open source programming language that makes it
easy to build simple, reliable, and efficient software.”
• Almost 6 years old (November 10th).
• Born after looking at hairy C++ code.
• Current: Go 1.5
• Over 200 companies use go
• ~1200 people @gophercon
• Great for webapps/devops/server mgmt
“Go is awesome”
“Iron.io: How We Went from 30 Servers to 2
with Go”
“Another go at the
Next Big Language”
“CloudFlare blows hole in laws of Web physics with Go and
Railgun”
"I have now completed two projects in Go. I predict that it's
going to be the dominant language for server work."
Source
“Why I went from Python to Go (and not node.js)”
“Why you PHP guys should learn Golang”
"Prediction: Go will become the
dominant language for systems
work in IaaS, Orchestration, and
PaaS in 24 months."
Pwnage?
Does anyone care?
Is there a security policy?
https://golang.org/security#tmp_1
Vulnerability List
https://www.cvedetails.com/vendor/14185/Golang.html
Okay, so it’s not all
bad news…
Features!
Go is strongly-typed
• The type of every object is known at runtime.
• This cannot be changed.
• Pointers exist, but pointer arithmetic does not.
Memory Managed
• Garbage collector FTW.
• Accessing out of bound indexes in arrays ends
with a hard panic.
• Once again, no pointer arithmetic:: can’t create
buffer overflows.
Gofmt
• Source code formatter.
• Spend time writing code, not formatting it.
• Integrated with editors (vim/sublimetext/eclipse etc)
• Untweakable!
Gofmt motivation
• Code Reviews
• A Best Practice but….
• “Too much time lost on
reviewing formatting rather
than code.”
https://talks.go-zh.org/2015/gofmt-en.slide
Other tooling
• golint
• Code linter.
• Finds common lint issues or things that don’t belong to a standard.
• Could add this to your CI pipeline, but is volatile.
• go vet
• Looks for weird constructs in your code.
• Examples: Useless assignments, incorrect printf format, unreachable code
• Good list of tools to review: http://dominik.honnef.co/posts/2014/12/
an_incomplete_list_of_go_tools/
Standard Packages ftw
• Standard libs have pretty good support for most things
you need.
• Don’t have to search for 3rd party libs first…
• All crypto algorithms are in packages under the crypto
package.
• crypto.random uses /dev/urandom by default
• good read: https://leanpub.com/gocrypto (Kyle
Isom)
Single Binary
• Statically linked, so everything you need is in your
binary.
• Helps with product distribution.
• Reduces burden with installation issues on client
host.
App Dependencies
• Package management:
• Keeps team on the same page.
• Reproducible builds.
• Godep:
• Most popular
• Code is vendorized.
• All your dependencies live inside your application.
• Sorta like (java) ant, but with the source.
Web Application Building
• Easy to build your own HTTP/HTTPS server
Web Applications: XSS
• Go Templates- html/template and text/template:
• You want to use html/template for your webapps.
• html/template package escapes all html tags!
(template.HTMLEscape or ExecuteTemplate).
• text/template does not!!
Gorilla toolkit
• Awesome toolkit for writing web applications.
• Assists with writing more secure code when you
don’t know how to code.
• Gorilla toolkit >>> roll your own
• http://www.gorillatoolkit.org/
Gorilla toolkit
• gorilla/securecookie
• Secure cookie: Encodes/Decodes cookie values for you.
• Value is validated with HMAC.
• Add encryption, and content is inaccessible to end user.
• gorilla/sessions
• Simple API for signed (and encrypted) cookies.
• Clean mechanism to rotate session authentication and encryption keys.
• gorilla/mux: Great for routing web apps
• Also gorilla/context, gorilla/websockets and a few others
c’mon man
Secure middleware
• https://github.com/unrolled/secure
• Middleware that helps you with some quick security
wins.
• + XSS Protection headers
• + CSP headers
• + SSL Check/SSL Redirects
Example:
secureMiddleware := secure.New(secure.Options{
AllowedHosts: []string{"example.com", "ssl.example.com"},
SSLRedirect: true,
SSLHost: "ssl.example.com",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
STSSeconds: 315360000,
STSIncludeSubdomains: true,
STSPreload: true,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
ContentSecurityPolicy: "default-src 'self'",
PublicKey: `pin-sha256="base64+primary=="; pin-
sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-
uri="https://www.example.com/hpkp-report"`,
})
CSRF
• nosurf is an HTTP package that helps with
prevention of cross site request forgery.
• https://github.com/justinas/nosurf
nosurf example
var templateString = `
<!doctype html>
<html><body>
{{ if .name }}
<p>Your name: {{ .name }}</p>
{{ end }}
<form action="/" method="POST">
<input type="text" name="name">
<!-- Try removing this or changing its value
and see what happens -->
<input type="hidden" name="csrf_token" value="{{ .token }}">
<input type="submit" value="Send">
</form></body></html>
`
var templ = template.Must(template.New("t1").Parse(templateString))
func myFunc(w http.ResponseWriter, r *http.Request) {
context := make(map[string]string)
context["token"] = nosurf.Token(r)
if r.Method == "POST" {
context["name"] = r.FormValue("name")
}
templ.Execute(w, context)
}
func main() {
myHandler := http.HandlerFunc(myFunc)
fmt.Println("Listening on http://127.0.0.1:8000/")
http.ListenAndServe(":8000", nosurf.New(myHandler))
}
SQL Injections
• Same as other languages…..
username := r.Form.Get("username")
password := r.Form.Get(“password")
// Oh noes!!
sql := "SELECT * FROM user WHERE username='" + username + "' AND password='" + password + “'"
Db.Exec(sql)
// Oh yes!!
sql := "SELECT * FROM user WHERE username=? AND password=?”
Db.Exec(sql, username, password)
SQL Injections
• Limit DB user permissions so that the impact is minimal.
• Sanitize inputs, escape special characters (‘“&*;).
• Use the HTMLEscapeString for this.
• Use parameterized queries!
• Code review DB.exec so that you’re using the parameterized
query interface.
• Or use Query/Prepare instead.
• Run your code against sqlmap or gauntlt.
Friends who Go!
This could be you
More resources
• Austin Golang meetup (@Umbel downtown)
• https://golang.org/doc/
• https://golang.org/doc/code.html
• https://www.digitalocean.com/company/blog/get-your-
development-team-started-with-go/
• https://github.com/astaxie/build-web-application-with-golang
• https://speakerdeck.com/ngalbreath/secure-application-
development-with-golang
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web Apps
James Williams
 

Was ist angesagt? (20)

Optimizing and Profiling Golang Rest Api
Optimizing and Profiling Golang Rest ApiOptimizing and Profiling Golang Rest Api
Optimizing and Profiling Golang Rest Api
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
[INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
 [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
[INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
 
Docker introduction in Hardware Company
Docker introduction in Hardware CompanyDocker introduction in Hardware Company
Docker introduction in Hardware Company
 
はじめての JFrog Artifactory
はじめての JFrog Artifactoryはじめての JFrog Artifactory
はじめての JFrog Artifactory
 
COSCUP 2016: Project 52 每週一個小專案來學習 Golang
COSCUP 2016: Project 52 每週一個小專案來學習 GolangCOSCUP 2016: Project 52 每週一個小專案來學習 Golang
COSCUP 2016: Project 52 每週一個小專案來學習 Golang
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of Golang
 
Golang start and tips
Golang start and tipsGolang start and tips
Golang start and tips
 
Jenkins vs GitLab CI
Jenkins vs GitLab CIJenkins vs GitLab CI
Jenkins vs GitLab CI
 
用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務
 
Gitlab ci, cncf.sk
Gitlab ci, cncf.skGitlab ci, cncf.sk
Gitlab ci, cncf.sk
 
GitLab - Java User Group
GitLab - Java User GroupGitLab - Java User Group
GitLab - Java User Group
 
GitLab for CI/CD process
GitLab for CI/CD processGitLab for CI/CD process
GitLab for CI/CD process
 
Docker Best Practices Workshop
Docker Best Practices WorkshopDocker Best Practices Workshop
Docker Best Practices Workshop
 
Building Command Line Tools with Golang
Building Command Line Tools with GolangBuilding Command Line Tools with Golang
Building Command Line Tools with Golang
 
Writing Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future SelfWriting Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future Self
 
Why golang
Why golangWhy golang
Why golang
 
Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web Apps
 
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
 
Developing Cross Platform Applications with Golang
Developing Cross Platform Applications with GolangDeveloping Cross Platform Applications with Golang
Developing Cross Platform Applications with Golang
 

Andere mochten auch

A Tour of Cryptography Packages in Go - Kyle Isom
A Tour of Cryptography Packages in Go - Kyle IsomA Tour of Cryptography Packages in Go - Kyle Isom
A Tour of Cryptography Packages in Go - Kyle Isom
Hakka Labs
 

Andere mochten auch (20)

Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern
 
A microservice architecture based on golang
A microservice architecture based on golangA microservice architecture based on golang
A microservice architecture based on golang
 
Functional go
Functional goFunctional go
Functional go
 
A Tour of Cryptography Packages in Go - Kyle Isom
A Tour of Cryptography Packages in Go - Kyle IsomA Tour of Cryptography Packages in Go - Kyle Isom
A Tour of Cryptography Packages in Go - Kyle Isom
 
Golang for OO Programmers
Golang for OO ProgrammersGolang for OO Programmers
Golang for OO Programmers
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
Containers and microservices for realists
Containers and microservices for realistsContainers and microservices for realists
Containers and microservices for realists
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using Golang
 
Why to docker
Why to dockerWhy to docker
Why to docker
 
Serverless Security: Doing Security in 100 milliseconds
Serverless Security: Doing Security in 100 millisecondsServerless Security: Doing Security in 100 milliseconds
Serverless Security: Doing Security in 100 milliseconds
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
Epistemological Problem of Application Security
Epistemological Problem of Application SecurityEpistemological Problem of Application Security
Epistemological Problem of Application Security
 
How to Effect Change in the Epistemological Wasteland of Application Security
How to Effect Change in the Epistemological Wasteland of Application SecurityHow to Effect Change in the Epistemological Wasteland of Application Security
How to Effect Change in the Epistemological Wasteland of Application Security
 
Git Flow and JavaScript Coding Style
Git Flow and JavaScript Coding StyleGit Flow and JavaScript Coding Style
Git Flow and JavaScript Coding Style
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript Conference
 
Be Mean To Your Code: Rugged Development & You
Be Mean To Your Code: Rugged Development & YouBe Mean To Your Code: Rugged Development & You
Be Mean To Your Code: Rugged Development & You
 
DevOps for the Discouraged
DevOps for the Discouraged DevOps for the Discouraged
DevOps for the Discouraged
 
Gearman work queue in php
Gearman work queue in phpGearman work queue in php
Gearman work queue in php
 

Ähnlich wie 13 practical tips for writing secure golang applications

Philip Stehlik at TechTalks.ph - Intro to Groovy and Grails
Philip Stehlik at TechTalks.ph - Intro to Groovy and GrailsPhilip Stehlik at TechTalks.ph - Intro to Groovy and Grails
Philip Stehlik at TechTalks.ph - Intro to Groovy and Grails
Philip Stehlik
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
Avi Kedar
 
BinaryPig - Scalable Malware Analytics in Hadoop
BinaryPig - Scalable Malware Analytics in HadoopBinaryPig - Scalable Malware Analytics in Hadoop
BinaryPig - Scalable Malware Analytics in Hadoop
Jason Trost
 
Abusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec gloryAbusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec glory
Priyanka Aash
 

Ähnlich wie 13 practical tips for writing secure golang applications (20)

Programming for the Internet of Things
Programming for the Internet of ThingsProgramming for the Internet of Things
Programming for the Internet of Things
 
Rails security: above and beyond the defaults
Rails security: above and beyond the defaultsRails security: above and beyond the defaults
Rails security: above and beyond the defaults
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript Applications
 
Aleksei Dremin - Application Security Pipeline - phdays9
Aleksei Dremin - Application Security Pipeline - phdays9Aleksei Dremin - Application Security Pipeline - phdays9
Aleksei Dremin - Application Security Pipeline - phdays9
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPL
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventure
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's Rye
 
Philip Stehlik at TechTalks.ph - Intro to Groovy and Grails
Philip Stehlik at TechTalks.ph - Intro to Groovy and GrailsPhilip Stehlik at TechTalks.ph - Intro to Groovy and Grails
Philip Stehlik at TechTalks.ph - Intro to Groovy and Grails
 
Protect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying TechniquesProtect Your Payloads: Modern Keying Techniques
Protect Your Payloads: Modern Keying Techniques
 
Be faster then rabbits
Be faster then rabbitsBe faster then rabbits
Be faster then rabbits
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Docker and serverless Randstad Jan 2019: OpenFaaS Serverless: when functions ...
Docker and serverless Randstad Jan 2019: OpenFaaS Serverless: when functions ...Docker and serverless Randstad Jan 2019: OpenFaaS Serverless: when functions ...
Docker and serverless Randstad Jan 2019: OpenFaaS Serverless: when functions ...
 
Que nos espera a los ALM Dudes para el 2013?
Que nos espera a los ALM Dudes para el 2013?Que nos espera a los ALM Dudes para el 2013?
Que nos espera a los ALM Dudes para el 2013?
 
BinaryPig - Scalable Malware Analytics in Hadoop
BinaryPig - Scalable Malware Analytics in HadoopBinaryPig - Scalable Malware Analytics in Hadoop
BinaryPig - Scalable Malware Analytics in Hadoop
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
Abusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec gloryAbusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec glory
 
cadec-2017-golang
cadec-2017-golangcadec-2017-golang
cadec-2017-golang
 
DevOps-Roadmap
DevOps-RoadmapDevOps-Roadmap
DevOps-Roadmap
 
Analysis of-quality-of-pkgs-in-packagist-univ-20171024
Analysis of-quality-of-pkgs-in-packagist-univ-20171024Analysis of-quality-of-pkgs-in-packagist-univ-20171024
Analysis of-quality-of-pkgs-in-packagist-univ-20171024
 
ShiftGearsWithInformationSecurity.pdf
ShiftGearsWithInformationSecurity.pdfShiftGearsWithInformationSecurity.pdf
ShiftGearsWithInformationSecurity.pdf
 

Mehr von Karthik Gaekwad

Agile 2014- Metrics driven development and devops
Agile 2014- Metrics driven development and devopsAgile 2014- Metrics driven development and devops
Agile 2014- Metrics driven development and devops
Karthik Gaekwad
 

Mehr von Karthik Gaekwad (20)

Why to Cloud Native
Why to Cloud NativeWhy to Cloud Native
Why to Cloud Native
 
DevSecOps in a cloudnative world
DevSecOps in a cloudnative worldDevSecOps in a cloudnative world
DevSecOps in a cloudnative world
 
Mental Health studies and devops
Mental Health studies and devopsMental Health studies and devops
Mental Health studies and devops
 
This is your community
This is your communityThis is your community
This is your community
 
Practical Approaches to Cloud Native Security
Practical Approaches to Cloud Native SecurityPractical Approaches to Cloud Native Security
Practical Approaches to Cloud Native Security
 
10 tips for Cloud Native Security
10 tips for Cloud Native Security10 tips for Cloud Native Security
10 tips for Cloud Native Security
 
Kube Apps in action
Kube Apps in actionKube Apps in action
Kube Apps in action
 
KubeSecOps
KubeSecOpsKubeSecOps
KubeSecOps
 
Kubernetes Security
Kubernetes SecurityKubernetes Security
Kubernetes Security
 
Kubernetes security and you
Kubernetes security and youKubernetes security and you
Kubernetes security and you
 
Kube applications in action
Kube applications in actionKube applications in action
Kube applications in action
 
Devops and Dadops
Devops and DadopsDevops and Dadops
Devops and Dadops
 
Containers, microservices and serverless for realists
Containers, microservices and serverless for realistsContainers, microservices and serverless for realists
Containers, microservices and serverless for realists
 
Docker management
Docker managementDocker management
Docker management
 
Agile 2014- Metrics driven development and devops
Agile 2014- Metrics driven development and devopsAgile 2014- Metrics driven development and devops
Agile 2014- Metrics driven development and devops
 
Devopsdays Austin 2014 Ignite: Keep devops weird
Devopsdays Austin 2014 Ignite: Keep devops weirdDevopsdays Austin 2014 Ignite: Keep devops weird
Devopsdays Austin 2014 Ignite: Keep devops weird
 
Cloud Austin 2013: Conferenced2013
Cloud Austin 2013: Conferenced2013Cloud Austin 2013: Conferenced2013
Cloud Austin 2013: Conferenced2013
 
LASCON 2013 Talk: User Auth for Winners, how to get it right the first time!
LASCON 2013 Talk: User Auth for Winners, how to get it right the first time!LASCON 2013 Talk: User Auth for Winners, how to get it right the first time!
LASCON 2013 Talk: User Auth for Winners, how to get it right the first time!
 
Agile 2013 Talk: How DevOps Changes Everything
Agile 2013 Talk: How DevOps Changes EverythingAgile 2013 Talk: How DevOps Changes Everything
Agile 2013 Talk: How DevOps Changes Everything
 
DevOps at the CIA
DevOps at the CIADevOps at the CIA
DevOps at the CIA
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

13 practical tips for writing secure golang applications

  • 1. 13 Go security tips Karthik Gaekwad - @iteration1
  • 3. History of Go • “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.” • Almost 6 years old (November 10th). • Born after looking at hairy C++ code. • Current: Go 1.5 • Over 200 companies use go • ~1200 people @gophercon • Great for webapps/devops/server mgmt
  • 4. “Go is awesome” “Iron.io: How We Went from 30 Servers to 2 with Go” “Another go at the Next Big Language” “CloudFlare blows hole in laws of Web physics with Go and Railgun” "I have now completed two projects in Go. I predict that it's going to be the dominant language for server work." Source “Why I went from Python to Go (and not node.js)” “Why you PHP guys should learn Golang” "Prediction: Go will become the dominant language for systems work in IaaS, Orchestration, and PaaS in 24 months."
  • 6.
  • 7. Is there a security policy? https://golang.org/security#tmp_1
  • 9. Okay, so it’s not all bad news…
  • 11. Go is strongly-typed • The type of every object is known at runtime. • This cannot be changed. • Pointers exist, but pointer arithmetic does not.
  • 12. Memory Managed • Garbage collector FTW. • Accessing out of bound indexes in arrays ends with a hard panic. • Once again, no pointer arithmetic:: can’t create buffer overflows.
  • 13. Gofmt • Source code formatter. • Spend time writing code, not formatting it. • Integrated with editors (vim/sublimetext/eclipse etc) • Untweakable!
  • 14. Gofmt motivation • Code Reviews • A Best Practice but…. • “Too much time lost on reviewing formatting rather than code.” https://talks.go-zh.org/2015/gofmt-en.slide
  • 15. Other tooling • golint • Code linter. • Finds common lint issues or things that don’t belong to a standard. • Could add this to your CI pipeline, but is volatile. • go vet • Looks for weird constructs in your code. • Examples: Useless assignments, incorrect printf format, unreachable code • Good list of tools to review: http://dominik.honnef.co/posts/2014/12/ an_incomplete_list_of_go_tools/
  • 16. Standard Packages ftw • Standard libs have pretty good support for most things you need. • Don’t have to search for 3rd party libs first… • All crypto algorithms are in packages under the crypto package. • crypto.random uses /dev/urandom by default • good read: https://leanpub.com/gocrypto (Kyle Isom)
  • 17. Single Binary • Statically linked, so everything you need is in your binary. • Helps with product distribution. • Reduces burden with installation issues on client host.
  • 18. App Dependencies • Package management: • Keeps team on the same page. • Reproducible builds. • Godep: • Most popular • Code is vendorized. • All your dependencies live inside your application. • Sorta like (java) ant, but with the source.
  • 19. Web Application Building • Easy to build your own HTTP/HTTPS server
  • 20. Web Applications: XSS • Go Templates- html/template and text/template: • You want to use html/template for your webapps. • html/template package escapes all html tags! (template.HTMLEscape or ExecuteTemplate). • text/template does not!!
  • 21. Gorilla toolkit • Awesome toolkit for writing web applications. • Assists with writing more secure code when you don’t know how to code. • Gorilla toolkit >>> roll your own • http://www.gorillatoolkit.org/
  • 22. Gorilla toolkit • gorilla/securecookie • Secure cookie: Encodes/Decodes cookie values for you. • Value is validated with HMAC. • Add encryption, and content is inaccessible to end user. • gorilla/sessions • Simple API for signed (and encrypted) cookies. • Clean mechanism to rotate session authentication and encryption keys. • gorilla/mux: Great for routing web apps • Also gorilla/context, gorilla/websockets and a few others
  • 24. Secure middleware • https://github.com/unrolled/secure • Middleware that helps you with some quick security wins. • + XSS Protection headers • + CSP headers • + SSL Check/SSL Redirects
  • 25. Example: secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"example.com", "ssl.example.com"}, SSLRedirect: true, SSLHost: "ssl.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, STSSeconds: 315360000, STSIncludeSubdomains: true, STSPreload: true, FrameDeny: true, ContentTypeNosniff: true, BrowserXssFilter: true, ContentSecurityPolicy: "default-src 'self'", PublicKey: `pin-sha256="base64+primary=="; pin- sha256="base64+backup=="; max-age=5184000; includeSubdomains; report- uri="https://www.example.com/hpkp-report"`, })
  • 26. CSRF • nosurf is an HTTP package that helps with prevention of cross site request forgery. • https://github.com/justinas/nosurf
  • 27. nosurf example var templateString = ` <!doctype html> <html><body> {{ if .name }} <p>Your name: {{ .name }}</p> {{ end }} <form action="/" method="POST"> <input type="text" name="name"> <!-- Try removing this or changing its value and see what happens --> <input type="hidden" name="csrf_token" value="{{ .token }}"> <input type="submit" value="Send"> </form></body></html> ` var templ = template.Must(template.New("t1").Parse(templateString)) func myFunc(w http.ResponseWriter, r *http.Request) { context := make(map[string]string) context["token"] = nosurf.Token(r) if r.Method == "POST" { context["name"] = r.FormValue("name") } templ.Execute(w, context) } func main() { myHandler := http.HandlerFunc(myFunc) fmt.Println("Listening on http://127.0.0.1:8000/") http.ListenAndServe(":8000", nosurf.New(myHandler)) }
  • 28. SQL Injections • Same as other languages….. username := r.Form.Get("username") password := r.Form.Get(“password") // Oh noes!! sql := "SELECT * FROM user WHERE username='" + username + "' AND password='" + password + “'" Db.Exec(sql) // Oh yes!! sql := "SELECT * FROM user WHERE username=? AND password=?” Db.Exec(sql, username, password)
  • 29. SQL Injections • Limit DB user permissions so that the impact is minimal. • Sanitize inputs, escape special characters (‘“&*;). • Use the HTMLEscapeString for this. • Use parameterized queries! • Code review DB.exec so that you’re using the parameterized query interface. • Or use Query/Prepare instead. • Run your code against sqlmap or gauntlt.
  • 30. Friends who Go! This could be you
  • 31. More resources • Austin Golang meetup (@Umbel downtown) • https://golang.org/doc/ • https://golang.org/doc/code.html • https://www.digitalocean.com/company/blog/get-your- development-team-started-with-go/ • https://github.com/astaxie/build-web-application-with-golang • https://speakerdeck.com/ngalbreath/secure-application- development-with-golang