|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "regexp" |
| 10 | +) |
| 11 | + |
| 12 | +func good() (interface{}, error) { |
| 13 | + name := os.Args[1] |
| 14 | + hasBadChar, _ := regexp.MatchString(".*[?].*", name) |
| 15 | + |
| 16 | + if hasBadChar { |
| 17 | + return nil, errors.New("bad input") |
| 18 | + } |
| 19 | + |
| 20 | + dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", "username", "password", "127.0.0.1", 3306, name) |
| 21 | + db, _ := sql.Open("mysql", dbDSN) |
| 22 | + return db, nil |
| 23 | +} |
| 24 | + |
| 25 | +func bad() interface{} { |
| 26 | + name2 := os.Args[1:] |
| 27 | + // This is bad. `name` can be something like `test?allowAllFiles=true&` which will allow an attacker to access local files. |
| 28 | + dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", "username", "password", "127.0.0.1", 3306, name2[0]) |
| 29 | + db, _ := sql.Open("mysql", dbDSN) |
| 30 | + return db |
| 31 | +} |
| 32 | + |
| 33 | +func good2(w http.ResponseWriter, req *http.Request) (interface{}, error) { |
| 34 | + name := req.FormValue("name") |
| 35 | + hasBadChar, _ := regexp.MatchString(".*[?].*", name) |
| 36 | + |
| 37 | + if hasBadChar { |
| 38 | + return nil, errors.New("bad input") |
| 39 | + } |
| 40 | + |
| 41 | + dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", "username", "password", "127.0.0.1", 3306, name) |
| 42 | + db, _ := sql.Open("mysql", dbDSN) |
| 43 | + return db, nil |
| 44 | +} |
| 45 | + |
| 46 | +func bad2(w http.ResponseWriter, req *http.Request) interface{} { |
| 47 | + name := req.FormValue("name") |
| 48 | + // This is bad. `name` can be something like `test?allowAllFiles=true&` which will allow an attacker to access local files. |
| 49 | + dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", "username", "password", "127.0.0.1", 3306, name) |
| 50 | + db, _ := sql.Open("mysql", dbDSN) |
| 51 | + return db |
| 52 | +} |
| 53 | + |
| 54 | +func main() { |
| 55 | + bad2(nil, nil) |
| 56 | + good() |
| 57 | + bad() |
| 58 | + good2(nil, nil) |
| 59 | +} |
0 commit comments