Cloak/internal/server/auth.go

65 lines
1.6 KiB
Go
Raw Normal View History

2018-10-09 15:07:54 +00:00
package server
import (
"bytes"
2018-10-14 19:32:54 +00:00
"crypto"
2018-10-09 15:07:54 +00:00
"crypto/sha256"
"encoding/binary"
"log"
2018-10-14 19:32:54 +00:00
"github.com/cbeuw/Cloak/internal/util"
ecdh "github.com/cbeuw/go-ecdh"
2018-10-09 15:07:54 +00:00
)
2018-11-07 21:16:13 +00:00
// input ticket, return UID
func decryptSessionTicket(staticPv crypto.PrivateKey, ticket []byte) ([]byte, uint32, error) {
2018-10-14 19:32:54 +00:00
ec := ecdh.NewCurve25519ECDH()
ephPub, _ := ec.Unmarshal(ticket[0:32])
key, err := ec.GenerateSharedSecret(staticPv, ephPub)
2018-10-09 15:07:54 +00:00
if err != nil {
2018-11-07 21:16:13 +00:00
return nil, 0, err
2018-10-09 15:07:54 +00:00
}
2018-11-07 21:16:13 +00:00
UIDsID := util.AESDecrypt(ticket[0:16], key, ticket[32:68])
sessionID := binary.BigEndian.Uint32(UIDsID[32:36])
return UIDsID[0:32], sessionID, nil
2018-10-09 15:07:54 +00:00
}
2018-11-07 21:16:13 +00:00
func validateRandom(random []byte, UID []byte, time int64) bool {
2018-10-09 15:07:54 +00:00
t := make([]byte, 8)
2018-10-14 19:32:54 +00:00
binary.BigEndian.PutUint64(t, uint64(time/(12*60*60)))
rdm := random[0:16]
2018-10-09 15:07:54 +00:00
preHash := make([]byte, 56)
2018-11-07 21:16:13 +00:00
copy(preHash[0:32], UID)
2018-10-09 15:07:54 +00:00
copy(preHash[32:40], t)
2018-10-14 19:32:54 +00:00
copy(preHash[40:56], rdm)
2018-10-09 15:07:54 +00:00
h := sha256.New()
h.Write(preHash)
return bytes.Equal(h.Sum(nil)[0:16], random[16:32])
}
2018-11-07 21:16:13 +00:00
func TouchStone(ch *ClientHello, sta *State) (isSS bool, UID []byte, sessionID uint32) {
2018-10-09 15:07:54 +00:00
var random [32]byte
copy(random[:], ch.random)
used := sta.getUsedRandom(random)
if used != 0 {
log.Println("Replay! Duplicate random")
2018-11-07 21:16:13 +00:00
return false, nil, 0
2018-10-09 15:07:54 +00:00
}
sta.putUsedRandom(random)
2018-10-20 20:41:01 +00:00
ticket := ch.extensions[[2]byte{0x00, 0x23}]
if len(ticket) < 64 {
2018-11-07 21:16:13 +00:00
return false, nil, 0
2018-10-20 20:41:01 +00:00
}
2018-11-07 21:16:13 +00:00
UID, sessionID, err := decryptSessionTicket(sta.staticPv, ticket)
2018-10-09 15:07:54 +00:00
if err != nil {
2018-10-14 19:32:54 +00:00
log.Printf("ts: %v\n", err)
2018-11-07 21:16:13 +00:00
return false, nil, 0
2018-10-09 15:07:54 +00:00
}
2018-11-07 21:16:13 +00:00
isSS = validateRandom(ch.random, UID, sta.Now().Unix())
2018-10-09 15:07:54 +00:00
if !isSS {
2018-11-07 21:16:13 +00:00
return false, nil, 0
2018-10-09 15:07:54 +00:00
}
2018-11-07 21:16:13 +00:00
return
2018-10-09 15:07:54 +00:00
}