Skip to content

Commit 6293b0f

Browse files
committed
finish implementation
1 parent dbd9fef commit 6293b0f

2 files changed

Lines changed: 63 additions & 1 deletion

File tree

handler/handler.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@ package handler
22

33
import (
44
"bufio"
5+
"bytes"
6+
"fmt"
57
"io"
68
"log"
79

10+
"github.com/SenseUnit/basic_hmac_auth/hmac"
811
"github.com/SenseUnit/basic_hmac_auth/proto"
912
)
1013

@@ -27,7 +30,20 @@ func (a *BasicHMACAuthHandler) Run(input io.Reader, output io.Writer) error {
2730
scanner := proto.NewElasticLineScanner(rd, '\n')
2831

2932
for scanner.Scan() {
30-
log.Printf("line=%q", string(scanner.Bytes()))
33+
parts := bytes.SplitN(scanner.Bytes(), []byte{' '}, 4)
34+
if len(parts) < 3 {
35+
err := fmt.Errorf("bad request line sent to auth helper: %q", string(scanner.Bytes()))
36+
return err
37+
}
38+
channelID := parts[0]
39+
username := proto.RFC1738Unescape(parts[1])
40+
password := proto.RFC1738Unescape(parts[2])
41+
42+
if hmac.VerifyHMACLoginAndPassword(a.Secret, username, password) {
43+
fmt.Fprintf(output, "%s OK\n", channelID)
44+
} else {
45+
fmt.Fprintf(output, "%s ERR\n", channelID)
46+
}
3147
}
3248

3349
return scanner.Err()

hmac/hmac.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package hmac
2+
3+
import (
4+
"bytes"
5+
"crypto/hmac"
6+
"crypto/sha256"
7+
"encoding/base64"
8+
"encoding/binary"
9+
"time"
10+
)
11+
12+
const (
13+
HMACSignaturePrefix = "dumbproxy grant token v1"
14+
HMACSignatureSize = 32
15+
)
16+
17+
var hmacSignaturePrefix = []byte(HMACSignaturePrefix)
18+
19+
type HMACToken struct {
20+
Expire int64
21+
Signature [HMACSignatureSize]byte
22+
}
23+
24+
func VerifyHMACLoginAndPassword(secret, login, password []byte) bool {
25+
rd := base64.NewDecoder(base64.RawURLEncoding, bytes.NewReader(password))
26+
27+
var token HMACToken
28+
if err := binary.Read(rd, binary.BigEndian, &token); err != nil {
29+
return false
30+
}
31+
32+
if time.Unix(token.Expire, 0).Before(time.Now()) {
33+
return false
34+
}
35+
36+
expectedMAC := CalculateHMACSignature(secret, login, token.Expire)
37+
return hmac.Equal(token.Signature[:], expectedMAC)
38+
}
39+
40+
func CalculateHMACSignature(secret, username []byte, expire int64) []byte {
41+
mac := hmac.New(sha256.New, secret)
42+
mac.Write(hmacSignaturePrefix)
43+
mac.Write(username)
44+
binary.Write(mac, binary.BigEndian, expire)
45+
return mac.Sum(nil)
46+
}

0 commit comments

Comments
 (0)