/
api.go
353 lines (324 loc) · 8.31 KB
/
api.go
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Clients are expected to attempt a handshake if they receive HTTP 401
//
//
// Any method may return HTTP 500
package main
// vim: set noexpandtab:
import (
//"bytes"
"crypto/rand"
"github.com/emicklei/go-restful"
"github.com/gokyle/cryptobox/box"
"github.com/golang/glog"
//"crypto/x509"
"database/sql"
"encoding/base64"
//"fmt"
//"errors"
"fmt"
"io"
"net/http"
//"time"
"regexp"
"strconv"
)
const (
challengeSize int = 16 // bytes
tokenSize int = 32 // bytes
)
func checkAuthentication(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
var err error
var token *http.Cookie
var id int64
var valid bool
token, err = req.Request.Cookie("Token")
if err != nil {
if glog.V(2) {
glog.Warningln("'Token' not set in cookie")
}
resp.WriteErrorString(400, "'Token' not set in cookie")
return
}
idStr, err := req.Request.Cookie("Id")
if err != nil {
if glog.V(2) {
glog.Warningln("'Id' not set in cookie")
}
resp.WriteErrorString(400, "'Id' not set in cookie")
return
}
id, err = strconv.ParseInt(idStr.Value, 10, 64)
if err != nil {
if glog.V(2) {
glog.Warningln("'Id' not valid int64")
}
resp.WriteErrorString(400, "'Id' not valid int64")
return
}
err = q["checkToken"].QueryRow(id, decodeBase64(token.Value)).Scan(&valid)
if err != nil {
if glog.V(2) {
glog.Errorf("Token checking SQL returned error: %v\n", q["checkToken"])
}
resp.WriteErrorString(500, "error checking token")
return
}
if !valid {
if glog.V(1) {
glog.Infof("Auth BAD for %d\n", id)
}
resp.WriteErrorString(401, "Unauthenticated")
return
}
if glog.V(1) {
glog.Infof("Auth OK for %d\n", id)
}
chain.ProcessFilter(req, resp)
}
func checkAuthorization(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
idStr, _ := req.Request.Cookie("Id")
id, _ := strconv.ParseInt(idStr.Value, 10, 64)
u, _ := GetUser(id)
if path, _ := regexp.MatchString("^/api/user(/.*)?$", req.Request.URL.Path); path {
switch req.Request.Method {
case "DELETE", "PUT":
if !u.Admin || req.PathParameter("id") != string(u.Id) {
resp.WriteErrorString(403, "Unauthorized")
return
}
case "POST":
if !u.Admin {
resp.WriteErrorString(403, "Unauthorized")
return
}
default:
break
}
}
chain.ProcessFilter(req, resp)
return
}
// GET /api/auth?name=me
// {"id": int, "challenge": <base64 string>}
func getChallenge(req *restful.Request, resp *restful.Response) {
var err error
var name string = req.PathParameter("name")
var c []byte = make([]byte, challengeSize)
u, err := GetUserByName(name)
if err != nil {
if glog.V(2) {
glog.Errorln(err)
}
resp.WriteErrorString(http.StatusBadRequest, "Cannot find user")
return
}
_, err = io.ReadFull(rand.Reader, c)
if err != nil {
glog.Errorln(err)
resp.WriteErrorString(http.StatusInternalServerError, "Error generating challenge")
return
}
//box, ok := box.SignAndSeal(c, boxPriv, boxPub, *u.PubKey)
box, ok := box.Seal(c, u.PubKey)
if !ok {
glog.Errorln("Error boxing challenge")
resp.WriteErrorString(http.StatusInternalServerError, "Error boxing challenge")
return
}
err = SaveChallenge(u.Id, c)
if err != nil {
glog.Errorln(err)
resp.WriteErrorString(http.StatusInternalServerError, "Error recording challenge")
return
}
resp.WriteEntity(&map[string]string{"challenge": base64.StdEncoding.EncodeToString(box), "id": fmt.Sprintf("%d", u.Id)})
if glog.V(1) {
glog.Infof("Auth.Login: sent challenge for %s\n", name)
if glog.V(3) {
glog.Infof("id:\t%d\n", u.Id)
glog.Infof("token:\t%x\n", c)
glog.Infof("encrypted challenge:\t%v\n", base64.StdEncoding.EncodeToString(box))
}
}
return
}
// POST /api/auth {"id": <int>, "challenge": <base64 string>}
// <Cookies>
func postChallenge(req *restful.Request, resp *restful.Response) {
var err error
var tok []byte = make([]byte, tokenSize)
var c map[string]string
err = req.ReadEntity(&c)
if err != nil {
if glog.V(1) {
glog.Warningln(err)
}
resp.WriteErrorString(http.StatusInternalServerError, "Error deserialzing response")
return
}
if glog.V(3) {
glog.Infof("recv'd:\t%+v\n", c)
}
_, okC := c["challenge"]
_, okI := c["id"]
if !(okC && okI) {
if glog.V(2) {
glog.Warningln("Malformed response")
}
resp.WriteErrorString(http.StatusBadRequest, "Malformed response")
return
}
id, err := strconv.ParseInt(c["id"], 10, 64)
if err != nil {
resp.WriteErrorString(http.StatusBadRequest, "Invalid Credentials")
return
}
if !CheckChallenge(id, decodeBase64(c["challenge"])) {
resp.WriteErrorString(http.StatusBadRequest, "Invalid Credentials")
return
}
_, err = io.ReadFull(rand.Reader, tok)
if err != nil {
glog.Errorln(err)
resp.WriteErrorString(http.StatusInternalServerError, "Error generating token")
return
}
err = SaveToken(id, tok)
if err != nil {
glog.Errorln(err)
resp.WriteErrorString(http.StatusInternalServerError, "Error saving token")
return
}
for k, v := range map[string]string{
"Token": base64.StdEncoding.EncodeToString(tok),
"Id": fmt.Sprintf("%d", id),
} {
cookie := &http.Cookie{Name: k, Value: v}
http.SetCookie(resp.ResponseWriter, cookie)
if glog.V(3) {
glog.Infof("Set cookie:\t%s:%s\n", k, v)
}
}
if glog.V(3) {
glog.Infof("Send auth token for %d\n", id)
}
return
}
func fetchUser(req *restful.Request, resp *restful.Response) {
id, err := strconv.ParseInt(req.PathParameter("id"), 10, 64)
if err != nil {
if glog.V(2) {
glog.Warningln("unable to parse id")
}
resp.WriteErrorString(http.StatusBadRequest, "unable to parse Id")
return
}
u, err := GetUser(id)
if err != nil {
if glog.V(2) {
glog.Warningf("unable to find user with id %d\n", id)
}
resp.WriteErrorString(http.StatusBadRequest, "unable to find user with Id")
return
}
if glog.V(3) {
glog.Infof("Sent info for user %d\n", id)
}
resp.WriteEntity(u)
}
func createUser(req *restful.Request, resp *restful.Response) {
var err error
var body struct {
Admin bool
Name string
Groups []int64
}
err = req.ReadEntity(&body)
if err != nil {
glog.Info("Malformed body")
resp.WriteErrorString(http.StatusBadRequest, "malformed body")
return
}
if glog.V(3) {
glog.Info(body)
}
}
func modifyUser(req *restful.Request, resp *restful.Response) {
id, err := strconv.ParseInt(req.PathParameter("id"), 10, 64)
if err != nil {
if glog.V(2) {
glog.Warningln("unable to parse id")
}
resp.WriteErrorString(http.StatusBadRequest, "unable to parse Id")
return
}
resp.WriteErrorString(http.StatusNotImplemented, fmt.Sprintf("%d", id))
return
}
func removeUser(req *restful.Request, resp *restful.Response) {
id, err := strconv.ParseInt(req.PathParameter("id"), 10, 64)
if err != nil {
if glog.V(2) {
glog.Warningln("unable to parse id")
}
resp.WriteErrorString(http.StatusBadRequest, "unable to parse Id")
return
}
resp.WriteErrorString(http.StatusNotImplemented, fmt.Sprintf("%d", id))
return
}
func searchUser(req *restful.Request, resp *restful.Response) {
var name string = req.QueryParameter("name")
var id []int64
rows, err := db.Query("SELECT id FROM users WHERE name LIKE $1;", name)
if err != nil {
glog.Error(err)
return
}
for rows.Next() {
var t int64
if err := rows.Scan(&t); err != nil {
glog.Error(err)
return
}
id = append(id, t)
}
if len(id) == 0 {
if glog.V(2) {
glog.Infof("bad name: %s\n", name)
}
resp.WriteErrorString(http.StatusBadRequest, "unable to find any user with name")
return
}
if glog.V(3) {
glog.Infof("Successful search for user %d\n", id)
}
resp.WriteEntity(&map[string][]int64{"id": id})
}
func allSecrets(req *restful.Request, resp *restful.Response) {
var rows *sql.Rows
type row struct {
Id int64
Revision int64
URI string
Note string
Secret []byte
SignerId int64
}
var ret []row //= make(row, 0)
idStr, _ := req.Request.Cookie("Id")
id, _ := strconv.ParseInt(idStr.Value, 10, 64)
rows, err := db.Query("SELECT (id, rev, uri, note, box, signer) FROM users_secrets WHERE uid = $1;", id)
if err != nil {
glog.Error(err)
resp.WriteErrorString(500, "Problem querying database")
}
for rows.Next() {
var id, rev, signerId int64
var uri, note string
var secret []byte
rows.Scan(&id, &rev, &uri, ¬e, &secret, &signerId)
ret = append(ret, row{id, rev, uri, note, secret, signerId})
}
resp.WriteEntity(&map[string][]row{"secrets": ret})
}