Cloak/internal/client/auth.go

58 lines
1.5 KiB
Go
Raw Normal View History

2018-10-07 17:09:45 +00:00
package client
import (
2018-10-14 19:32:54 +00:00
"crypto"
2018-10-07 17:09:45 +00:00
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"github.com/cbeuw/Cloak/internal/util"
2018-10-14 19:32:54 +00:00
ecdh "github.com/cbeuw/go-ecdh"
"io"
2018-10-07 17:09:45 +00:00
)
2018-10-14 19:32:54 +00:00
type keyPair struct {
crypto.PrivateKey
crypto.PublicKey
}
2018-10-07 17:09:45 +00:00
2018-10-14 19:32:54 +00:00
func MakeRandomField(sta *State) []byte {
2018-10-07 17:09:45 +00:00
t := make([]byte, 8)
2018-10-14 19:32:54 +00:00
binary.BigEndian.PutUint64(t, uint64(sta.Now().Unix()/(12*60*60)))
rdm := make([]byte, 16)
io.ReadFull(rand.Reader, rdm)
2018-10-07 17:09:45 +00:00
preHash := make([]byte, 56)
copy(preHash[0:32], sta.SID)
copy(preHash[32:40], t)
2018-10-14 19:32:54 +00:00
copy(preHash[40:56], rdm)
2018-10-07 17:09:45 +00:00
h := sha256.New()
h.Write(preHash)
ret := make([]byte, 32)
2018-10-14 19:32:54 +00:00
copy(ret[0:16], rdm)
2018-10-07 17:09:45 +00:00
copy(ret[16:32], h.Sum(nil)[0:16])
return ret
}
func MakeSessionTicket(sta *State) []byte {
2018-10-14 19:32:54 +00:00
// sessionTicket: [marshalled ephemeral pub key 32 bytes][encrypted SID 32 bytes][padding 128 bytes]
// The first 16 bytes of the marshalled ephemeral public key is used as the IV
// for encrypting the SID
tthInterval := sta.Now().Unix() / int64(sta.TicketTimeHint)
ec := ecdh.NewCurve25519ECDH()
ephKP := sta.getKeyPair(tthInterval)
if ephKP == nil {
ephPv, ephPub, _ := ec.GenerateKey(rand.Reader)
ephKP = &keyPair{
ephPv,
ephPub,
}
sta.putKeyPair(tthInterval, ephKP)
}
ticket := make([]byte, 192)
copy(ticket[0:32], ec.Marshal(ephKP.PublicKey))
key, _ := ec.GenerateSharedSecret(ephKP.PrivateKey, sta.staticPub)
cipherSID := util.AESEncrypt(ticket[0:16], key, sta.SID)
copy(ticket[32:64], cipherSID)
2018-10-23 19:47:58 +00:00
copy(ticket[64:192], util.PsudoRandBytes(128, tthInterval+sta.opaque))
2018-10-14 19:32:54 +00:00
return ticket
2018-10-07 17:09:45 +00:00
}