Web Exploitation
Challenge
Topic
Mechacore Inventory
Description
Solution
//go:build ignore
package main
import (
"fmt"
"time"
"log"
"strconv"
"net/http"
"html/template"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
)
type User struct {
Id int64
Name string
Email string
isAdmin bool
}
func (u User) String() string {
return fmt.Sprintf("User<%d %s %v %d>", u.Id, u.Name, u.Email, u.isAdmin)
}
type Item struct {
Id int64
Name string
Type string
Status string
CreationTimestamp int64
Quantity int64
OwnerId int64
Owner *User `pg:"rel:has-one"`
}
func renderTemplate(w http.ResponseWriter, name string, data interface{}) {
t, err := template.ParseGlob("templates/*.html")
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
err = t.ExecuteTemplate(w, name, data)
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
return
}
}
func dbGetItems( lastnseconds int , name string) []Item {
db := pg.Connect(&pg.Options{
User: "postgres",
Password: "postgres",
})
defer db.Close()
var items []Item
var err error
fmt.Print(lastnseconds)
fmt.Print(name)
if name=="" && lastnseconds==0 {
err = db.Model(&items).Select()
} else {
err = db.Model(&items).
Where("item.creation_timestamp >= cast(extract(epoch from current_timestamp) as integer)-? or item.name=?", lastnseconds , name).
Select()
}
if err != nil {
panic(err)
}
return items
}
// createSchema creates database schema for User and Story models.
func createSchema() error {
db := pg.Connect(&pg.Options{
User: "postgres",
Password: "postgres",
})
defer db.Close()
var err error
models := []interface{}{
(*User)(nil),
(*Item)(nil),
}
for _, model := range models {
err = db.Model(model).DropTable(&orm.DropTableOptions{
IfExists: true,
Cascade: true,
})
err = db.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
})
if err != nil {
return err
}
}
user1 := &User{
Name: "admin",
Email: "admin1@admin",
}
_, err = db.Model(user1).Insert()
if err != nil {
panic(err)
}
item1 := &Item{
Name: "UD-123-412",
Type: "Sensor",
Status: "Finished",
CreationTimestamp: time.Now().Unix() - 3600*2,
Quantity: 12,
OwnerId: user1.Id,
}
item2 := &Item{
Name: "UD-123-555",
Type: "Arm",
Status: "Creating",
CreationTimestamp: time.Now().Unix() - 3600*5,
Quantity: 5,
OwnerId: user1.Id,
}
_, err = db.Model(item1).Insert()
_, err = db.Model(item2).Insert()
if err != nil {
panic(err)
}
return nil
}
func handler(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
lastnseconds := r.FormValue("lastnseconds")
lastnsecondsi, _ := strconv.Atoi(lastnseconds)
items := dbGetItems(lastnsecondsi, name)
renderTemplate(w, "inventory.html", struct {
Items []Item
}{
Items: items,
})
}
func main() {
err := createSchema()
if err != nil {
panic(err)
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8000", nil))
}

Last updated