SlideShare une entreprise Scribd logo
1  sur  27
GO security tips
Andrey Shalaenko
Zeo Alliance
Golang overview
● Strong, static, inferred, structural typing system
● Pointers are available for all types.
There is no pointer arithmetic (except unsafe.Pointer)
● String is a read-only slice of bytes
● Dynamic arrays (slices), HashMap, etc
● GC (mark-sweep, tri-color)
(Go's next GC propose)
● Functional programming (first class function)
● Light-weight process (goroutine)
● Interface system (replace class inheritance)
● Quick and native compilation, speed
● Tools for developers (list)
● Standard packages
● Statically linked
Language Benefits
Golang overview
Language omissions
● Generics
● Exceptions (“errors are values“ © Rob Pike)
● Inheritance (structs compose)
● Method overloading
● Assertation
Golang overview
● Quick and native compilation, speed
● Tools for developers
(https://dominik.honnef.co/posts/2014/12/go-tools/)
● Standard packages
● Statically linked
● Package Management (Godep)
Developers benefits
Go Lang has proved to be a better choice for the following tasks :
● Web applications and web servers
Originally Go was created as a tool for fast and easy writing of web and
mobile applications by a large number of developers and to provide an
easy support environment for the code. Its own features, go routines
and channels, only enhance its advantages when writing code.
● Stand-alone command-line application or script.
This language has everything going for it: a single executed file without
any dependencies (if they are not needed), higher processing speed,
compared to other applications, ability to work with outside C libraries
and even to process system calls.
● A great alternative to parallel script writing in C/C++. It is easier to write
and deploy those scripts in Go.
Vulnerability List
Golang and OWASP TOP 10
● Same as other languages…
● databes/sql supports placeholder args
● nil, nil, nil …
//bad
sql := "SELECT * FROM users WHERE name='"+name+"' and
password='"+password+"'"
Db.Exec(sql)
//good
sql := "SELECT * FROM users WHERE name = ? AND password = ?"
Db.Exec(sql, name, password)
SQL Injections
Golang and OWASP TOP 10
SQL Injections
● Limit DB user permissions so that impact is minimal
● Sanitize inputs, escape special chars (HTMLEscapeString)
● Use parameterized queries
○ Code review Db.exec so that you’re using the parameterized
query interface
○ Or use Query/Prepare instead (Golang make prepare
statement from your parameterized query)
● Run your code against sqlmap or gauntlt
Golang and OWASP TOP 10
Web Applications: XSS
● Go Templates - html/templates and text/templates
○ Use html/templates for your app (same interface)
■ html/packages escape all html tags
(template.HTMLEscape or ExecuteTemplate)
● https://gohugo.io/
Golang and OWASP TOP 10
Web Applications: CSRF
● nosurf
○ https://github.com/justinas/nosurf
● Gorilla CSRF
○ http://www.gorillatoolkit.org/pkg/csrf
● gin-csrf
○ https://github.com/utrack/gin-csrf
Web Application building
● Easy to build your own HTTPS/HTTPS server
Web Application building
Web Frameworks and routers
● compare public api of famous Go web frameworks and routers
○ https://github.com/diyan/go-web-framework-comparsion
● benchmark of famous Go web frameworks and routers
○ https://github.com/smallnest/go-web-framework-benchmark
● benchmark HTTP request routers
○ https://github.com/julienschmidt/go-http-routing-benchmark
● Which I use:
○ GIn
■ https://github.com/gin-gonic/gin
○ Gorilla
■ https://github.com/gorilla
Web Application building
Gorilla toolkit
● Toolkit for writing web applications
○ https://github.com/gorilla
● gorilla/securecookie
○ secure cookie: encode/decode
○ value is validate with HMAC
● 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
● gorilla/context (in Go1.8 part of STL), gorilla/websockets, gorilla/gettext,
gorilla/http, etc
Web Application building
Gin
● Web Framework
○ https://github.com/gin-gonic/gin
● Fast
○ Use lightweight and high performance HTTP request router
(HttpRouter https://github.com/julienschmidt/httprouter)
● Zero Allocation router
● Graceful restart or stop server (native support in Go1.8)
● gin-contrib
○ A lot of tools for comfort web development
○ https://github.com/gin-gonic/contrib
○ gin-cors, gin-csrf, gin-jwt, gin-sessions, gin-oauth2, gin-sentry,
etc...
Web Application building
Secure middleware
● https://github.com/unrolled/secure
○ + XSS Protection
○ + CSP header
○ + SSL Check/SSL Redirects
Web Application building
Secure middleware: example
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
})
func main() {
secureMiddleware := secure.New(secure.Options{
AllowedHosts: []string{"example.com",
"ssl.example.com"},
HostsProxyHeaders: []string{"X-Forwarded-Host"},
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"`,
})
app := secureMiddleware.Handler(myHandler)
Concurrency
● Go makes concurrency easy
// explicit concurrency using 'go' statement
go func() {
...
}
// implicit concurrency via standard library
timer.AfterFunc(5 * time.Seconds, func() {
...
})
● ... but also allows you to share mutable data between goroutines
● Therefore data races are possible
● These are often hard to debug
● Go's memory safety guarantees do not apply in presence of data races
Concurrency
Data Race conditions
● Two memory accesses are involved in a data race if they:
○ Target the same piece of memory
○ Happen concurrently in two goroutines
○ At least one of the accesses is a write
value := 0
for i := 0; i < 1000000; i++ {
go func() {
value += 1
}()
}
fmt.Printf("%dn", value)
Concurrency
Detecting race condition
● Use the `-race` build option
○ go test -race net/http
○ go run -race app.go
○ go build -race path/to/package
● Run your app (or tests)
● The race detector will log details of races to console
Concurrency
Detecting race condition. Caveats
● Only finds races in running code.
● Therefore testing must exercise realistic workloads
● Performance overhead - CPU cost of runtime library calls (~2-10x) and
additional memory usage (~5-10x)
○ In order to detect data races, we need to monitor:
■ Accesses to memory from different threads
■ Operations that impose ordering on memory accesses - either
directly (eg. functions in `sync/atomic`) or indirectly (eg.
primitives like mutexes, sending values over channels).
● Only detects data races - These are not the only kind of race condition
Concurrency
Detecting race condition. Example
func main() {
c := make(chan bool)
m := make(map[string]string)
go func() {
m["1"] = "a" // First conflicting access.
c <- true
}()
m["2"] = "b" // Second conflicting access.
<-c
for k, v := range m {
fmt.Println(k, v)
}
}
$ go test -race mypkg // to test the package
$ go run -race mysrc.go // to run the source file
$ go build -race mycmd // to build the command
$ go install -race mypkg // to install the package
Concurrency
Detecting race condition. Example
==================
WARNING: DATA RACE
Write at 0x00c42007c0c0 by goroutine 6:
runtime.mapassign1()
/usr/local/go/src/runtime/hashmap.go:442 +0x0
main.main.func1()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:8 +0x86
Previous write at 0x00c42007c0c0 by main goroutine:
runtime.mapassign1()
/usr/local/go/src/runtime/hashmap.go:442 +0x0
main.main()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:11 +0x13e
Goroutine 6 (running) created at:
main.main()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:10 +0xd4
==================
2 b
1 a
Found 1 data race(s)
exit status 66
Concurrency
Detecting race condition. Rules
● Use channel to synchronize between goroutine
● Only one goroutine can read and write a variable
● + or use sync/mutex or sync/atomic
○ https://golang.org/pkg/sync/#Mutex
○ https://golang.org/pkg/sync/atomic/
● close(c): Use like sending an EOF value. Only sending goroutine should
call close
Concurrency
Detecting race condition.
Further Reading
● Usage
○ http://blog.golang.org/race-detector Introducing the Go Race
Detector (blog post)
○ https://code.google.com/p/thread-sanitizer/wiki/GoManual
ThreadSanitizer Go manual
● Implementation
○ https://code.google.com/p/thread-sanitizer/wiki/Algorithm
ThreadSanitizer algorithm overview
○ http://preshing.com/20120913/acquire-and-release-semantics/
Primer on Acquire and Release Semantics (useful to understand
what it means for one memory access to happen_before another)
● The Go memory model
○ http://golang.org/ref/mem
More resources
● https://golang.org/doc/
● https://golang.org/doc/code.html
● https://golang.org/doc/effective_go.htm
● https://github.com/astaxie/build-web-application-with-golang
● https://speakerdeck.com/ngalbreath/secure-application-development-with-
golang
● https://www.reddit.com/r/golang/
Thank you
Andriy Shalaenko - GO security tips

Contenu connexe

Tendances

C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - OverviewBartlomiej Filipek
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009Mario Heiderich
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupBadoo Development
 
ClojureScript interfaces to React
ClojureScript interfaces to ReactClojureScript interfaces to React
ClojureScript interfaces to ReactMichiel Borkent
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGuillaume Laforge
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersJen Yee Hong
 
DEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webDEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webFelipe Prado
 

Tendances (19)

Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Graph ql api gateway
Graph ql api gatewayGraph ql api gateway
Graph ql api gateway
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Xdebug from a to x
Xdebug from a to xXdebug from a to x
Xdebug from a to x
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
ClojureScript interfaces to React
ClojureScript interfaces to ReactClojureScript interfaces to React
ClojureScript interfaces to React
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
(not= DSL macros)
(not= DSL macros)(not= DSL macros)
(not= DSL macros)
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
DEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webDEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot web
 

Similaire à Andriy Shalaenko - GO security tips

Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Lars Albertsson
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxSignalFx
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud appsDavid Cunningham
 
To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GOsuperstas88
 
一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构勇浩 赖
 
FP - Découverte de Play Framework Scala
FP - Découverte de Play Framework ScalaFP - Découverte de Play Framework Scala
FP - Découverte de Play Framework ScalaKévin Margueritte
 
Web application security and Python security best practices
Web application security and Python security best practicesWeb application security and Python security best practices
Web application security and Python security best practicesPGS Software S.A.
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Behave manners for ui testing pycon2019
Behave manners for ui testing pycon2019Behave manners for ui testing pycon2019
Behave manners for ui testing pycon2019Panos Christeas
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
React starter-kitでとっとと始めるisomorphic開発
React starter-kitでとっとと始めるisomorphic開発React starter-kitでとっとと始めるisomorphic開発
React starter-kitでとっとと始めるisomorphic開発Yoichi Toyota
 
Porting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindPorting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindBeMyApp
 

Similaire à Andriy Shalaenko - GO security tips (20)

Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFx
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud apps
 
To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GO
 
一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构
 
Tp web
Tp webTp web
Tp web
 
FP - Découverte de Play Framework Scala
FP - Découverte de Play Framework ScalaFP - Découverte de Play Framework Scala
FP - Découverte de Play Framework Scala
 
Web application security and Python security best practices
Web application security and Python security best practicesWeb application security and Python security best practices
Web application security and Python security best practices
 
Clang: More than just a C/C++ Compiler
Clang: More than just a C/C++ CompilerClang: More than just a C/C++ Compiler
Clang: More than just a C/C++ Compiler
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Behave manners for ui testing pycon2019
Behave manners for ui testing pycon2019Behave manners for ui testing pycon2019
Behave manners for ui testing pycon2019
 
Grails 101
Grails 101Grails 101
Grails 101
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
React starter-kitでとっとと始めるisomorphic開発
React starter-kitでとっとと始めるisomorphic開発React starter-kitでとっとと始めるisomorphic開発
React starter-kitでとっとと始めるisomorphic開発
 
Porting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindPorting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mind
 

Plus de OWASP Kyiv

Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...OWASP Kyiv
 
Software Supply Chain Security та компоненти з відомими вразливостями
Software Supply Chain Security та компоненти з відомими вразливостямиSoftware Supply Chain Security та компоненти з відомими вразливостями
Software Supply Chain Security та компоненти з відомими вразливостямиOWASP Kyiv
 
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout SuiteCloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout SuiteOWASP Kyiv
 
Threat Modeling with OWASP Threat Dragon
Threat Modeling with OWASP Threat DragonThreat Modeling with OWASP Threat Dragon
Threat Modeling with OWASP Threat DragonOWASP Kyiv
 
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...OWASP Kyiv
 
Vlad Styran - Cyber Security Economics 101
Vlad Styran - Cyber Security Economics 101Vlad Styran - Cyber Security Economics 101
Vlad Styran - Cyber Security Economics 101OWASP Kyiv
 
Pavlo Radchuk - OWASP SAMM: Understanding Agile in Security
Pavlo Radchuk - OWASP SAMM: Understanding Agile in SecurityPavlo Radchuk - OWASP SAMM: Understanding Agile in Security
Pavlo Radchuk - OWASP SAMM: Understanding Agile in SecurityOWASP Kyiv
 
Ivan Vyshnevskyi - Not So Quiet Git Push
Ivan Vyshnevskyi - Not So Quiet Git PushIvan Vyshnevskyi - Not So Quiet Git Push
Ivan Vyshnevskyi - Not So Quiet Git PushOWASP Kyiv
 
Dima Kovalenko - Modern SSL Pinning
Dima Kovalenko - Modern SSL PinningDima Kovalenko - Modern SSL Pinning
Dima Kovalenko - Modern SSL PinningOWASP Kyiv
 
Yevhen Teleshyk - OAuth Phishing
Yevhen Teleshyk - OAuth PhishingYevhen Teleshyk - OAuth Phishing
Yevhen Teleshyk - OAuth PhishingOWASP Kyiv
 
Vlada Kulish - Why So Serial?
Vlada Kulish - Why So Serial?Vlada Kulish - Why So Serial?
Vlada Kulish - Why So Serial?OWASP Kyiv
 
Vlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
Vlad Styran - OWASP Kyiv 2017 Report and 2018 PlansVlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
Vlad Styran - OWASP Kyiv 2017 Report and 2018 PlansOWASP Kyiv
 
Roman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
Roman Borodin - ISC2 & ISACA Certification Programs First-hand ExperienceRoman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
Roman Borodin - ISC2 & ISACA Certification Programs First-hand ExperienceOWASP Kyiv
 
Ihor Bliumental - WebSockets
Ihor Bliumental - WebSocketsIhor Bliumental - WebSockets
Ihor Bliumental - WebSocketsOWASP Kyiv
 
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017OWASP Kyiv
 
Viktor Zhora - Cyber and Geopolitics: Ukrainian factor
Viktor Zhora - Cyber and Geopolitics: Ukrainian factorViktor Zhora - Cyber and Geopolitics: Ukrainian factor
Viktor Zhora - Cyber and Geopolitics: Ukrainian factorOWASP Kyiv
 
Vlad Styran - "Hidden" Features of the Tools We All Love
Vlad Styran - "Hidden" Features of the Tools We All LoveVlad Styran - "Hidden" Features of the Tools We All Love
Vlad Styran - "Hidden" Features of the Tools We All LoveOWASP Kyiv
 
Volodymyr Ilibman - Close Look at Nyetya Investigation
Volodymyr Ilibman - Close Look at Nyetya InvestigationVolodymyr Ilibman - Close Look at Nyetya Investigation
Volodymyr Ilibman - Close Look at Nyetya InvestigationOWASP Kyiv
 
Ihor Bliumental - Collision CORS
Ihor Bliumental - Collision CORSIhor Bliumental - Collision CORS
Ihor Bliumental - Collision CORSOWASP Kyiv
 
Lidiia 'Alice' Skalytska - Security Checklist for Web Developers
Lidiia 'Alice' Skalytska - Security Checklist for Web DevelopersLidiia 'Alice' Skalytska - Security Checklist for Web Developers
Lidiia 'Alice' Skalytska - Security Checklist for Web DevelopersOWASP Kyiv
 

Plus de OWASP Kyiv (20)

Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
 
Software Supply Chain Security та компоненти з відомими вразливостями
Software Supply Chain Security та компоненти з відомими вразливостямиSoftware Supply Chain Security та компоненти з відомими вразливостями
Software Supply Chain Security та компоненти з відомими вразливостями
 
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout SuiteCloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
 
Threat Modeling with OWASP Threat Dragon
Threat Modeling with OWASP Threat DragonThreat Modeling with OWASP Threat Dragon
Threat Modeling with OWASP Threat Dragon
 
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
 
Vlad Styran - Cyber Security Economics 101
Vlad Styran - Cyber Security Economics 101Vlad Styran - Cyber Security Economics 101
Vlad Styran - Cyber Security Economics 101
 
Pavlo Radchuk - OWASP SAMM: Understanding Agile in Security
Pavlo Radchuk - OWASP SAMM: Understanding Agile in SecurityPavlo Radchuk - OWASP SAMM: Understanding Agile in Security
Pavlo Radchuk - OWASP SAMM: Understanding Agile in Security
 
Ivan Vyshnevskyi - Not So Quiet Git Push
Ivan Vyshnevskyi - Not So Quiet Git PushIvan Vyshnevskyi - Not So Quiet Git Push
Ivan Vyshnevskyi - Not So Quiet Git Push
 
Dima Kovalenko - Modern SSL Pinning
Dima Kovalenko - Modern SSL PinningDima Kovalenko - Modern SSL Pinning
Dima Kovalenko - Modern SSL Pinning
 
Yevhen Teleshyk - OAuth Phishing
Yevhen Teleshyk - OAuth PhishingYevhen Teleshyk - OAuth Phishing
Yevhen Teleshyk - OAuth Phishing
 
Vlada Kulish - Why So Serial?
Vlada Kulish - Why So Serial?Vlada Kulish - Why So Serial?
Vlada Kulish - Why So Serial?
 
Vlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
Vlad Styran - OWASP Kyiv 2017 Report and 2018 PlansVlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
Vlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
 
Roman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
Roman Borodin - ISC2 & ISACA Certification Programs First-hand ExperienceRoman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
Roman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
 
Ihor Bliumental - WebSockets
Ihor Bliumental - WebSocketsIhor Bliumental - WebSockets
Ihor Bliumental - WebSockets
 
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
 
Viktor Zhora - Cyber and Geopolitics: Ukrainian factor
Viktor Zhora - Cyber and Geopolitics: Ukrainian factorViktor Zhora - Cyber and Geopolitics: Ukrainian factor
Viktor Zhora - Cyber and Geopolitics: Ukrainian factor
 
Vlad Styran - "Hidden" Features of the Tools We All Love
Vlad Styran - "Hidden" Features of the Tools We All LoveVlad Styran - "Hidden" Features of the Tools We All Love
Vlad Styran - "Hidden" Features of the Tools We All Love
 
Volodymyr Ilibman - Close Look at Nyetya Investigation
Volodymyr Ilibman - Close Look at Nyetya InvestigationVolodymyr Ilibman - Close Look at Nyetya Investigation
Volodymyr Ilibman - Close Look at Nyetya Investigation
 
Ihor Bliumental - Collision CORS
Ihor Bliumental - Collision CORSIhor Bliumental - Collision CORS
Ihor Bliumental - Collision CORS
 
Lidiia 'Alice' Skalytska - Security Checklist for Web Developers
Lidiia 'Alice' Skalytska - Security Checklist for Web DevelopersLidiia 'Alice' Skalytska - Security Checklist for Web Developers
Lidiia 'Alice' Skalytska - Security Checklist for Web Developers
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Andriy Shalaenko - GO security tips

  • 1. GO security tips Andrey Shalaenko Zeo Alliance
  • 2. Golang overview ● Strong, static, inferred, structural typing system ● Pointers are available for all types. There is no pointer arithmetic (except unsafe.Pointer) ● String is a read-only slice of bytes ● Dynamic arrays (slices), HashMap, etc ● GC (mark-sweep, tri-color) (Go's next GC propose) ● Functional programming (first class function) ● Light-weight process (goroutine) ● Interface system (replace class inheritance) ● Quick and native compilation, speed ● Tools for developers (list) ● Standard packages ● Statically linked Language Benefits
  • 3. Golang overview Language omissions ● Generics ● Exceptions (“errors are values“ © Rob Pike) ● Inheritance (structs compose) ● Method overloading ● Assertation
  • 4. Golang overview ● Quick and native compilation, speed ● Tools for developers (https://dominik.honnef.co/posts/2014/12/go-tools/) ● Standard packages ● Statically linked ● Package Management (Godep) Developers benefits
  • 5. Go Lang has proved to be a better choice for the following tasks : ● Web applications and web servers Originally Go was created as a tool for fast and easy writing of web and mobile applications by a large number of developers and to provide an easy support environment for the code. Its own features, go routines and channels, only enhance its advantages when writing code. ● Stand-alone command-line application or script. This language has everything going for it: a single executed file without any dependencies (if they are not needed), higher processing speed, compared to other applications, ability to work with outside C libraries and even to process system calls. ● A great alternative to parallel script writing in C/C++. It is easier to write and deploy those scripts in Go.
  • 7. Golang and OWASP TOP 10 ● Same as other languages… ● databes/sql supports placeholder args ● nil, nil, nil … //bad sql := "SELECT * FROM users WHERE name='"+name+"' and password='"+password+"'" Db.Exec(sql) //good sql := "SELECT * FROM users WHERE name = ? AND password = ?" Db.Exec(sql, name, password) SQL Injections
  • 8. Golang and OWASP TOP 10 SQL Injections ● Limit DB user permissions so that impact is minimal ● Sanitize inputs, escape special chars (HTMLEscapeString) ● Use parameterized queries ○ Code review Db.exec so that you’re using the parameterized query interface ○ Or use Query/Prepare instead (Golang make prepare statement from your parameterized query) ● Run your code against sqlmap or gauntlt
  • 9. Golang and OWASP TOP 10 Web Applications: XSS ● Go Templates - html/templates and text/templates ○ Use html/templates for your app (same interface) ■ html/packages escape all html tags (template.HTMLEscape or ExecuteTemplate) ● https://gohugo.io/
  • 10. Golang and OWASP TOP 10 Web Applications: CSRF ● nosurf ○ https://github.com/justinas/nosurf ● Gorilla CSRF ○ http://www.gorillatoolkit.org/pkg/csrf ● gin-csrf ○ https://github.com/utrack/gin-csrf
  • 11. Web Application building ● Easy to build your own HTTPS/HTTPS server
  • 12. Web Application building Web Frameworks and routers ● compare public api of famous Go web frameworks and routers ○ https://github.com/diyan/go-web-framework-comparsion ● benchmark of famous Go web frameworks and routers ○ https://github.com/smallnest/go-web-framework-benchmark ● benchmark HTTP request routers ○ https://github.com/julienschmidt/go-http-routing-benchmark ● Which I use: ○ GIn ■ https://github.com/gin-gonic/gin ○ Gorilla ■ https://github.com/gorilla
  • 13. Web Application building Gorilla toolkit ● Toolkit for writing web applications ○ https://github.com/gorilla ● gorilla/securecookie ○ secure cookie: encode/decode ○ value is validate with HMAC ● 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 ● gorilla/context (in Go1.8 part of STL), gorilla/websockets, gorilla/gettext, gorilla/http, etc
  • 14. Web Application building Gin ● Web Framework ○ https://github.com/gin-gonic/gin ● Fast ○ Use lightweight and high performance HTTP request router (HttpRouter https://github.com/julienschmidt/httprouter) ● Zero Allocation router ● Graceful restart or stop server (native support in Go1.8) ● gin-contrib ○ A lot of tools for comfort web development ○ https://github.com/gin-gonic/contrib ○ gin-cors, gin-csrf, gin-jwt, gin-sessions, gin-oauth2, gin-sentry, etc...
  • 15. Web Application building Secure middleware ● https://github.com/unrolled/secure ○ + XSS Protection ○ + CSP header ○ + SSL Check/SSL Redirects
  • 16. Web Application building Secure middleware: example var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"example.com", "ssl.example.com"}, HostsProxyHeaders: []string{"X-Forwarded-Host"}, 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"`, }) app := secureMiddleware.Handler(myHandler)
  • 17. Concurrency ● Go makes concurrency easy // explicit concurrency using 'go' statement go func() { ... } // implicit concurrency via standard library timer.AfterFunc(5 * time.Seconds, func() { ... }) ● ... but also allows you to share mutable data between goroutines ● Therefore data races are possible ● These are often hard to debug ● Go's memory safety guarantees do not apply in presence of data races
  • 18. Concurrency Data Race conditions ● Two memory accesses are involved in a data race if they: ○ Target the same piece of memory ○ Happen concurrently in two goroutines ○ At least one of the accesses is a write value := 0 for i := 0; i < 1000000; i++ { go func() { value += 1 }() } fmt.Printf("%dn", value)
  • 19. Concurrency Detecting race condition ● Use the `-race` build option ○ go test -race net/http ○ go run -race app.go ○ go build -race path/to/package ● Run your app (or tests) ● The race detector will log details of races to console
  • 20. Concurrency Detecting race condition. Caveats ● Only finds races in running code. ● Therefore testing must exercise realistic workloads ● Performance overhead - CPU cost of runtime library calls (~2-10x) and additional memory usage (~5-10x) ○ In order to detect data races, we need to monitor: ■ Accesses to memory from different threads ■ Operations that impose ordering on memory accesses - either directly (eg. functions in `sync/atomic`) or indirectly (eg. primitives like mutexes, sending values over channels). ● Only detects data races - These are not the only kind of race condition
  • 21. Concurrency Detecting race condition. Example func main() { c := make(chan bool) m := make(map[string]string) go func() { m["1"] = "a" // First conflicting access. c <- true }() m["2"] = "b" // Second conflicting access. <-c for k, v := range m { fmt.Println(k, v) } } $ go test -race mypkg // to test the package $ go run -race mysrc.go // to run the source file $ go build -race mycmd // to build the command $ go install -race mypkg // to install the package
  • 22. Concurrency Detecting race condition. Example ================== WARNING: DATA RACE Write at 0x00c42007c0c0 by goroutine 6: runtime.mapassign1() /usr/local/go/src/runtime/hashmap.go:442 +0x0 main.main.func1() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:8 +0x86 Previous write at 0x00c42007c0c0 by main goroutine: runtime.mapassign1() /usr/local/go/src/runtime/hashmap.go:442 +0x0 main.main() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:11 +0x13e Goroutine 6 (running) created at: main.main() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:10 +0xd4 ================== 2 b 1 a Found 1 data race(s) exit status 66
  • 23. Concurrency Detecting race condition. Rules ● Use channel to synchronize between goroutine ● Only one goroutine can read and write a variable ● + or use sync/mutex or sync/atomic ○ https://golang.org/pkg/sync/#Mutex ○ https://golang.org/pkg/sync/atomic/ ● close(c): Use like sending an EOF value. Only sending goroutine should call close
  • 24. Concurrency Detecting race condition. Further Reading ● Usage ○ http://blog.golang.org/race-detector Introducing the Go Race Detector (blog post) ○ https://code.google.com/p/thread-sanitizer/wiki/GoManual ThreadSanitizer Go manual ● Implementation ○ https://code.google.com/p/thread-sanitizer/wiki/Algorithm ThreadSanitizer algorithm overview ○ http://preshing.com/20120913/acquire-and-release-semantics/ Primer on Acquire and Release Semantics (useful to understand what it means for one memory access to happen_before another) ● The Go memory model ○ http://golang.org/ref/mem
  • 25. More resources ● https://golang.org/doc/ ● https://golang.org/doc/code.html ● https://golang.org/doc/effective_go.htm ● https://github.com/astaxie/build-web-application-with-golang ● https://speakerdeck.com/ngalbreath/secure-application-development-with- golang ● https://www.reddit.com/r/golang/