Andriy Shalaenko - GO security tips

OWASP Kyiv
Sep. 11, 2017
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
1 of 27

More Related Content

Slideshows for you

Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17Bartlomiej Filipek
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - OverviewBartlomiej Filipek
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
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 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009Mario Heiderich

Similar to Andriy Shalaenko - GO security tips

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 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 JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
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 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 TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat

More from 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...OWASP Kyiv
Software Supply Chain Security та компоненти з відомими вразливостямиSoftware Supply Chain Security та компоненти з відомими вразливостями
Software Supply Chain Security та компоненти з відомими вразливостямиOWASP Kyiv
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout SuiteCloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout SuiteOWASP Kyiv
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...OWASP Kyiv
Vlad Styran - Cyber Security Economics 101Vlad Styran - Cyber Security Economics 101
Vlad Styran - Cyber Security Economics 101OWASP Kyiv

More from OWASP Kyiv(20)

Recently uploaded

Workshop on IoT and Basic Home Automation_BAIUST.pptxWorkshop on IoT and Basic Home Automation_BAIUST.pptx
Workshop on IoT and Basic Home Automation_BAIUST.pptxRedwan Ferdous
NoSQL Database Migration Masterclass - Session 2: The Anatomy of a MigrationNoSQL Database Migration Masterclass - Session 2: The Anatomy of a Migration
NoSQL Database Migration Masterclass - Session 2: The Anatomy of a MigrationScyllaDB
[KCD GT 2023] Demystifying etcd failure scenarios for Kubernetes.pdf[KCD GT 2023] Demystifying etcd failure scenarios for Kubernetes.pdf
[KCD GT 2023] Demystifying etcd failure scenarios for Kubernetes.pdfWilliam Caban
INASLA_AI and Landscape Architecture.pptxINASLA_AI and Landscape Architecture.pptx
INASLA_AI and Landscape Architecture.pptxJonathon Geels
GDSC SRMCEM Info Session 2023GDSC SRMCEM Info Session 2023
GDSC SRMCEM Info Session 2023HariOM Dwivedi
Sell&Buy.pdfSell&Buy.pdf
Sell&Buy.pdfDanielle95109

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.
  6. Vulnerability List
  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/
  26. Thank you