Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.
GO security tips
Andrey Shalaenko
Zeo Alliance
Golang overview
● Strong, static, inferred, structural typing system
● Pointers are available for all types.
There is no p...
Golang overview
Language omissions
● Generics
● Exceptions (“errors are values“ © Rob Pike)
● Inheritance (structs compose...
Golang overview
● Quick and native compilation, speed
● Tools for developers
(https://dominik.honnef.co/posts/2014/12/go-t...
Go Lang has proved to be a better choice for the following tasks :
● Web applications and web servers
Originally Go was cr...
Vulnerability List
Golang and OWASP TOP 10
● Same as other languages…
● databes/sql supports placeholder args
● nil, nil, nil …
//bad
sql := ...
Golang and OWASP TOP 10
SQL Injections
● Limit DB user permissions so that impact is minimal
● Sanitize inputs, escape spe...
Golang and OWASP TOP 10
Web Applications: XSS
● Go Templates - html/templates and text/templates
○ Use html/templates for ...
Golang and OWASP TOP 10
Web Applications: CSRF
● nosurf
○ https://github.com/justinas/nosurf
● Gorilla CSRF
○ http://www.g...
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:/...
Web Application building
Gorilla toolkit
● Toolkit for writing web applications
○ https://github.com/gorilla
● gorilla/sec...
Web Application building
Gin
● Web Framework
○ https://github.com/gin-gonic/gin
● Fast
○ Use lightweight and high performa...
Web Application building
Secure middleware
● https://github.com/unrolled/secure
○ + XSS Protection
○ + CSP header
○ + SSL ...
Web Application building
Secure middleware: example
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.R...
Concurrency
● Go makes concurrency easy
// explicit concurrency using 'go' statement
go func() {
...
}
// implicit concurr...
Concurrency
Data Race conditions
● Two memory accesses are involved in a data race if they:
○ Target the same piece of mem...
Concurrency
Detecting race condition
● Use the `-race` build option
○ go test -race net/http
○ go run -race app.go
○ go bu...
Concurrency
Detecting race condition. Caveats
● Only finds races in running code.
● Therefore testing must exercise realis...
Concurrency
Detecting race condition. Example
func main() {
c := make(chan bool)
m := make(map[string]string)
go func() {
...
Concurrency
Detecting race condition. Example
==================
WARNING: DATA RACE
Write at 0x00c42007c0c0 by goroutine 6...
Concurrency
Detecting race condition. Rules
● Use channel to synchronize between goroutine
● Only one goroutine can read a...
Concurrency
Detecting race condition.
Further Reading
● Usage
○ http://blog.golang.org/race-detector Introducing the Go Ra...
More resources
● https://golang.org/doc/
● https://golang.org/doc/code.html
● https://golang.org/doc/effective_go.htm
● ht...
Thank you
Andriy Shalaenko - GO security tips
Próxima SlideShare
Cargando en…5
×

Andriy Shalaenko - GO security tips

1.219 visualizaciones

Publicado el

Security potential and some neat tips from an experienced GO developer.

Publicado en: Tecnología
  • Inicia sesión para ver los comentarios

Andriy Shalaenko - GO security tips

  1. 1. GO security tips Andrey Shalaenko Zeo Alliance
  2. 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. 3. Golang overview Language omissions ● Generics ● Exceptions (“errors are values“ © Rob Pike) ● Inheritance (structs compose) ● Method overloading ● Assertation
  4. 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. 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.
  6. 6. Vulnerability List
  7. 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. 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. 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. 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. 11. Web Application building ● Easy to build your own HTTPS/HTTPS server
  12. 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. 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. 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. 15. Web Application building Secure middleware ● https://github.com/unrolled/secure ○ + XSS Protection ○ + CSP header ○ + SSL Check/SSL Redirects
  16. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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/
  26. 26. Thank you

×