ref: bd7bd9b30650ca74cf4997a5e1b3d8b7bc6e5a6b cisco/api/main.go -rw-r--r-- 4.0 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main

import (
	"cisco/sdk"
	"crypto/hmac"
	"crypto/md5"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	"github.com/kataras/iris"
	"github.com/satori/go.uuid"
	"os"
)

func S3Auth(ctx iris.Context) bool {
	var token DbToken
	var user DbUser
	var toSign string

	key := ctx.GetHeader("X-Csc-Key")
	DB.First(&token, "key = ?", key)
	if token.ID == 0 {
		APIError(ctx, 403, "The request signature we calculated does not match the signature you provided. Check your key!")
		return false
	}

	toSign = ctx.Method() + Config.HTTPHost + ctx.RequestPath(false) + ctx.GetHeader("Date") + key

	rawData := RequestBody(ctx)
	if rawData != nil && len(rawData) != 0 {
		sum := md5.Sum(rawData)
		if ctx.GetHeader("Content-MD5") != hex.EncodeToString(sum[:]) {
			APIError(ctx, 400, "The provided content hash did not match the body content (Are you safe?)")
			return false
		}

		toSign += string(rawData[:]) + ctx.GetHeader("Content-MD5")
	}

	secretHex, err := hex.DecodeString(token.Secret)
	if err != nil {
		APIError(ctx, 500, "We could not get your secret key")
		return false
	}

	h := hmac.New(sha256.New, secretHex)
	h.Write([]byte(toSign))
	signature := hex.EncodeToString(h.Sum(nil))

	if signature != ctx.GetHeader("X-Csc-Signature") {
		APIError(ctx, 403, "The request signature we calculated does not match the signature you provided. Check your key!")
		return false
	}

	DB.First(&user, "ID = ?", token.User)

	ctx.Values().Set("User", token.User)
	ctx.Values().Set("Role", user.Role)
	return true
}

func APIAuth(ctx iris.Context) {
	if S3Auth(ctx) {
		ctx.Next()
	}
}

func AdminAuth(ctx iris.Context) {
	if S3Auth(ctx) {
		role := ctx.Values().Get("Role")
		if role == "admin" {
			ctx.Next()
		} else {
			APIError(ctx, 403, "This route is only for users with an admin privilege")
		}
	}
}

func parseFlags() {
	admin := flag.String("admin", "", "Admin username")
	password := flag.String("password", "", "Admin password (SHA256)")
	email := flag.String("email", "", "Admin email")
	filename := flag.String("config", "/etc/cisco-api.conf", "The yaml configuration file")
	version := flag.Bool("version", false, "Show version")

	flag.Parse()

	if *version {
		fmt.Printf("%s-%s (%s)\n", cisco.GitTag(), cisco.GitRev(), cisco.GitBranch())
		os.Exit(0)
	}

	ReadConfig(*filename)
	InitDB()

	if *admin != "" && *password != "" && *email != "" {
		var user DbUser
		var entry DbToken

		if ValidateSHA256(*password) == false {
			panic("The provided admin password is not a valid SHA256 hash")
		}

		DB.First(&user, "username = ?", *admin)
		if user.ID != 0 {
			panic("This username already exists!")
		}

		fmt.Printf("Creating admin user %s\n", *admin)
		user.Password = HashNSalt(*password)
		user.Username = *admin
		user.Email = *email
		user.Role = "admin"
		DB.Create(&user)

		secret := make([]byte, 32)

		_, err := rand.Read(secret)
		if err != nil {
			panic("Not enough entropy to generate the secret key")
		}

		entry.Key = uuid.NewV4().String()
		entry.Description = "Initialization admin credentials"
		entry.Secret = hex.EncodeToString(secret[:])
		entry.User = user.ID

		DB.Create(&entry)

		fmt.Printf("Admin credentials (It will only print once, don't loose this!):\n")
		fmt.Printf("key: %s\n", entry.Key)
		fmt.Printf("secret: %s\n", entry.Secret)

		os.Exit(0)
	} else if *admin != "" || *password != "" || *email != "" {
		panic("In order to create an admin user, you must provide _all_ three flags: -admin, -password, -email")
	}
}

func main() {
	parseFlags()
	defer CloseDB()

	app := iris.New()

	app.OnErrorCode(404, func(ctx iris.Context) {
		if ctx.GetHeader("X-Csc-Version") == cisco.GitTag() {
			APIError(ctx, 404, "The route you asked for could not be found")
		} else {
			APIError(ctx, 404, "The route you asked for could not be found (Server Version: "+cisco.GitTag()+", Client Version: "+ctx.GetHeader("X-Csc-Version")+")")
		}
	})

	InitInviteRoutes(app)
	InitTokenRoutes(app)
	InitAdminRoutes(app)
	InitSSHRoutes(app)
	InitInstanceRoutes(app)
	InitImageRoutes(app)

	app.Run(iris.Addr(Config.Address))
}