SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
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
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...
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