├── .gitignore
├── images
└── tincan.png
├── tls
├── serverccs.go
├── clientfinished.go
├── clienthello_test.go
├── serverhandshake_test.go
├── computefinished.go
├── test_test.go
├── constants.go
├── conncrypt.go
├── serveralert.go
├── computekeys.go
├── clienthello.go
├── computefinished_test.go
├── serverhandshake.go
├── conncrypt_test.go
├── conn.go
└── computekeys_test.go
├── Makefile
├── algo
├── gcm
│ ├── ghash.go
│ ├── inc.go
│ ├── gctr.go
│ ├── inc_test.go
│ ├── test_test.go
│ ├── mult_block.go
│ ├── hash_test.go
│ ├── mult_block_test.go
│ ├── gcm.go
│ ├── gctr_test.go
│ └── gcm_test.go
├── hmac
│ ├── test_test.go
│ ├── hmac.go
│ └── hmac_test.go
├── sha256
│ ├── test_test.go
│ ├── sha256.go
│ └── sha256_test.go
├── ecdhe
│ ├── ecdhe.go
│ ├── ecdhe_test.go
│ └── test_test.go
├── hkdf
│ ├── hkdf.go
│ ├── test_test.go
│ └── hkdf_test.go
├── aes
│ ├── test_test.go
│ ├── aes.go
│ └── aes_test.go
└── curve25519
│ ├── test_test.go
│ ├── curve25519_test.go
│ ├── curve25519.go
│ ├── coord.go
│ └── coord_test.go
├── cmd
└── tincan-client
│ └── main.go
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .*.swp
2 | /tincan-client
3 |
--------------------------------------------------------------------------------
/images/tincan.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/syncsynchalt/tincan-tls/HEAD/images/tincan.png
--------------------------------------------------------------------------------
/tls/serverccs.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | func handleChangeCipherSpec(conn *TLSConn, payload []byte) action {
4 | if len(payload) != 1 || payload[0] != 1 {
5 | panic("weird ccs")
6 | }
7 | return action_reset_sequence
8 | }
9 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all:
2 | go build ./cmd/tincan-client
3 |
4 | test:
5 | @for i in $$(find . -name '*_test.go' | xargs -n1 dirname | uniq); do \
6 | go test -timeout=3s "$$i" || exit 1; \
7 | done
8 |
9 | clean:
10 | rm -f timcan-client
11 |
12 | fmt:
13 | go fmt ./...
14 |
--------------------------------------------------------------------------------
/algo/gcm/ghash.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | func ghash(H, X []byte) []byte {
4 | if len(H) != 16 || len(X)%16 != 0 {
5 | panic("ghash bad length")
6 | }
7 | Y := make([]byte, 16)
8 | for len(X) > 0 {
9 | xor(Y, X[:16])
10 | Y = multBlocks(Y, H)
11 | X = X[16:]
12 | }
13 | return Y
14 | }
15 |
--------------------------------------------------------------------------------
/algo/gcm/inc.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | func inc_32(b []byte) {
4 | if len(b) < 4 {
5 | panic("inc_32 b too short")
6 | }
7 | l := len(b)
8 | var n = uint32(b[l-1]) | uint32(b[l-2])<<8 | uint32(b[l-3])<<16 | uint32(b[l-4])<<24
9 | n++
10 | for i := 0; i < 4; i++ {
11 | b[l-i-1] = byte(n >> uint(8*i))
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/tls/clientfinished.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | func makeClientFinished(conn *TLSConn) ([]byte, error) {
4 | finished := computeClientFinished(conn)
5 |
6 | hs := make([]byte, 0)
7 | hs = append(hs, kHS_TYPE_FINISHED)
8 | hs = appendLen24(hs, len(finished))
9 | hs = append(hs, finished...)
10 | hs = append(hs, kREC_TYPE_HANDSHAKE)
11 |
12 | return conn.createEncryptedRecord(hs)
13 | }
14 |
--------------------------------------------------------------------------------
/tls/clienthello_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestClientHello(t *testing.T) {
9 | c := &TLSConn{}
10 | rec, err := makeClientHello(c, "host.name")
11 | ok(t, err)
12 |
13 | for i := range rec {
14 | fmt.Printf("%02x", rec[i])
15 | if i%16 == 15 {
16 | fmt.Printf("\n")
17 | } else {
18 | fmt.Printf(" ")
19 | }
20 | }
21 | fmt.Printf("\n")
22 | }
23 |
--------------------------------------------------------------------------------
/algo/hmac/test_test.go:
--------------------------------------------------------------------------------
1 | package hmac_test
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | func equals(tb testing.TB, exp, act interface{}) {
12 | if !reflect.DeepEqual(exp, act) {
13 | _, file, line, _ := runtime.Caller(1)
14 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
15 | tb.FailNow()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/algo/sha256/test_test.go:
--------------------------------------------------------------------------------
1 | package sha256_test
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | func equals(tb testing.TB, exp, act interface{}) {
12 | if !reflect.DeepEqual(exp, act) {
13 | _, file, line, _ := runtime.Caller(1)
14 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
15 | tb.FailNow()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/tls/serverhandshake_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestReadNum(t *testing.T) {
8 | b := []byte{1, 2, 3, 4}
9 | equals(t, uint(1), readNum(8, b))
10 | equals(t, uint(258), readNum(16, b))
11 | equals(t, uint(66051), readNum(24, b))
12 | }
13 |
14 | func TestReadVec(t *testing.T) {
15 | b := []byte{0, 0, 1, 2, 3, 4}
16 | v, rest := readVec(24, b)
17 | equals(t, []byte{2}, v)
18 | equals(t, []byte{3, 4}, rest)
19 | }
20 |
--------------------------------------------------------------------------------
/algo/ecdhe/ecdhe.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on RFC 4492
5 |
6 | package ecdhe
7 |
8 | import (
9 | "github.com/syncsynchalt/tincan-tls/algo/curve25519"
10 | )
11 |
12 | func GenerateKeys() (privkey, pubkey []byte, err error) {
13 | key, pub, err := curve25519.KeyPair()
14 | if err != nil {
15 | return nil, nil, err
16 | }
17 | return key[:], pub[:], err
18 | }
19 |
20 | func CalculateSharedSecret(mykey, otherpub []byte) []byte {
21 | var k, p [32]byte
22 | copy(k[:], mykey)
23 | copy(p[:], otherpub)
24 | secret := curve25519.Mult(k, p)
25 | return secret[:]
26 | }
27 |
--------------------------------------------------------------------------------
/algo/gcm/gctr.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | func gctr(ciph Cipher, icb, x []byte) []byte {
4 | if len(icb) != 16 {
5 | panic("gctr bad len")
6 | }
7 | if len(x) == 0 {
8 | return []byte{}
9 | }
10 | y := make([]byte, 0)
11 | yi := make([]byte, 16)
12 | n := (len(x) + 15) / 16
13 | cb := make([]byte, 16)
14 | encout := make([]byte, 16)
15 | for i := 1; i <= n; i++ {
16 | if i == 1 {
17 | copy(cb, icb)
18 | } else {
19 | inc_32(cb)
20 | }
21 | ciph.Encrypt(cb, encout)
22 | if i < n {
23 | copy(yi, x[:16])
24 | xor(yi, encout)
25 | y = append(y, yi...)
26 | x = x[16:]
27 | } else {
28 | copy(yi, x)
29 | xor(yi, encout)
30 | y = append(y, yi[:len(x)]...)
31 | }
32 | }
33 | return y
34 | }
35 |
--------------------------------------------------------------------------------
/tls/computefinished.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "github.com/syncsynchalt/tincan-tls/algo/hmac"
5 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
6 | )
7 |
8 | func computeServerFinished(conn *TLSConn) []byte {
9 | finishedKey := hkdfExpandLabel(conn.serverHandshakeTrafficSecret[:], "finished", []byte{}, kSHA256OutLen)
10 | transcriptHash := sha256.SumData(conn.lastTranscript)
11 | return hmac.Compute(finishedKey, transcriptHash, sha256.New())
12 | }
13 |
14 | func computeClientFinished(conn *TLSConn) []byte {
15 | finishedKey := hkdfExpandLabel(conn.clientHandshakeTrafficSecret[:], "finished", []byte{}, kSHA256OutLen)
16 | transcriptHash := sha256.SumData(conn.transcript)
17 | return hmac.Compute(finishedKey, transcriptHash, sha256.New())
18 | }
19 |
--------------------------------------------------------------------------------
/algo/gcm/inc_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "testing"
5 |
6 | "encoding/hex"
7 | )
8 |
9 | func inc_str(t *testing.T, s string) (string, error) {
10 | b, err := hex.DecodeString(s)
11 | if err != nil {
12 | return "", err
13 | }
14 | inc_32(b)
15 | result := hex.EncodeToString(b)
16 | return result, nil
17 | }
18 |
19 | func TestInc(t *testing.T) {
20 | s, err := inc_str(t, "01020304")
21 | ok(t, err)
22 | equals(t, "01020305", s)
23 |
24 | s, err = inc_str(t, "ffff01020304")
25 | ok(t, err)
26 | equals(t, "ffff01020305", s)
27 | }
28 |
29 | func TestIncWrap(t *testing.T) {
30 | s, err := inc_str(t, "ffffffff")
31 | ok(t, err)
32 | equals(t, "00000000", s)
33 |
34 | s, err = inc_str(t, "aabbffffffff")
35 | ok(t, err)
36 | equals(t, "aabb00000000", s)
37 | }
38 |
--------------------------------------------------------------------------------
/algo/ecdhe/ecdhe_test.go:
--------------------------------------------------------------------------------
1 | package ecdhe_test
2 |
3 | import (
4 | "testing"
5 |
6 | "encoding/hex"
7 | "github.com/syncsynchalt/tincan-tls/algo/ecdhe"
8 | "time"
9 | )
10 |
11 | func TestCalc(t *testing.T) {
12 | start := time.Now()
13 | defer func() { t.Log("took", time.Since(start)) }()
14 |
15 | mykey, mypub, err := ecdhe.GenerateKeys()
16 | ok(t, err)
17 | t.Log("mykey:", hex.EncodeToString(mykey))
18 | t.Log("mypub:", hex.EncodeToString(mypub))
19 |
20 | otherkey, otherpub, err := ecdhe.GenerateKeys()
21 | ok(t, err)
22 | t.Log("otherkey:", hex.EncodeToString(otherkey))
23 | t.Log("otherpub:", hex.EncodeToString(otherpub))
24 |
25 | secret1 := ecdhe.CalculateSharedSecret(mykey, otherpub)
26 | secret2 := ecdhe.CalculateSharedSecret(otherkey, mypub)
27 | equals(t, secret1, secret2)
28 | }
29 |
--------------------------------------------------------------------------------
/algo/hkdf/hkdf.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on RFC 5869
5 |
6 | package hkdf
7 |
8 | import (
9 | "github.com/syncsynchalt/tincan-tls/algo/hmac"
10 | )
11 |
12 | func Extract(hasher hmac.Hasher, salt, keymaterial []byte) []byte {
13 | if len(salt) == 0 {
14 | salt = make([]byte, hasher.BlockSize())
15 | }
16 | return hmac.Compute(salt, keymaterial, hasher)
17 | }
18 |
19 | func Expand(hasher hmac.Hasher, keymaterial, info []byte, outlength int) []byte {
20 | n := (outlength + hasher.HashLen() + 1) / hasher.HashLen()
21 | result := []byte{}
22 | T := []byte{}
23 | for i := 1; i <= n; i++ {
24 | T = append(T, info...)
25 | T = append(T, byte(i))
26 | T = hmac.Compute(keymaterial, T, hasher)
27 | result = append(result, T...)
28 | }
29 | return result[:outlength]
30 | }
31 |
--------------------------------------------------------------------------------
/algo/aes/test_test.go:
--------------------------------------------------------------------------------
1 | package aes
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | // equals fails the test if exp is not equal to act.
12 | func equals(tb testing.TB, exp, act interface{}) {
13 | if !reflect.DeepEqual(exp, act) {
14 | _, file, line, _ := runtime.Caller(1)
15 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
16 | tb.FailNow()
17 | }
18 | }
19 |
20 | // ok fails the test if an err is not nil.
21 | func ok(tb testing.TB, err error) {
22 | if err != nil {
23 | _, file, line, _ := runtime.Caller(1)
24 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
25 | tb.FailNow()
26 | }
27 | }
28 |
29 | // assert fails the test if the condition is false.
30 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
31 | if !condition {
32 | _, file, line, _ := runtime.Caller(1)
33 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
34 | tb.FailNow()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algo/gcm/test_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | // equals fails the test if exp is not equal to act.
12 | func equals(tb testing.TB, exp, act interface{}) {
13 | if !reflect.DeepEqual(exp, act) {
14 | _, file, line, _ := runtime.Caller(1)
15 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
16 | tb.FailNow()
17 | }
18 | }
19 |
20 | // ok fails the test if an err is not nil.
21 | func ok(tb testing.TB, err error) {
22 | if err != nil {
23 | _, file, line, _ := runtime.Caller(1)
24 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
25 | tb.FailNow()
26 | }
27 | }
28 |
29 | // assert fails the test if the condition is false.
30 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
31 | if !condition {
32 | _, file, line, _ := runtime.Caller(1)
33 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
34 | tb.FailNow()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algo/ecdhe/test_test.go:
--------------------------------------------------------------------------------
1 | package ecdhe_test
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | // equals fails the test if exp is not equal to act.
12 | func equals(tb testing.TB, exp, act interface{}) {
13 | if !reflect.DeepEqual(exp, act) {
14 | _, file, line, _ := runtime.Caller(1)
15 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
16 | tb.FailNow()
17 | }
18 | }
19 |
20 | // ok fails the test if an err is not nil.
21 | func ok(tb testing.TB, err error) {
22 | if err != nil {
23 | _, file, line, _ := runtime.Caller(1)
24 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
25 | tb.FailNow()
26 | }
27 | }
28 |
29 | // assert fails the test if the condition is false.
30 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
31 | if !condition {
32 | _, file, line, _ := runtime.Caller(1)
33 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
34 | tb.FailNow()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algo/hkdf/test_test.go:
--------------------------------------------------------------------------------
1 | package hkdf_test
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | // equals fails the test if exp is not equal to act.
12 | func equals(tb testing.TB, exp, act interface{}) {
13 | if !reflect.DeepEqual(exp, act) {
14 | _, file, line, _ := runtime.Caller(1)
15 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
16 | tb.FailNow()
17 | }
18 | }
19 |
20 | // ok fails the test if an err is not nil.
21 | func ok(tb testing.TB, err error) {
22 | if err != nil {
23 | _, file, line, _ := runtime.Caller(1)
24 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
25 | tb.FailNow()
26 | }
27 | }
28 |
29 | // assert fails the test if the condition is false.
30 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
31 | if !condition {
32 | _, file, line, _ := runtime.Caller(1)
33 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
34 | tb.FailNow()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algo/curve25519/test_test.go:
--------------------------------------------------------------------------------
1 | package curve25519
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 | )
10 |
11 | // equals fails the test if exp is not equal to act.
12 | func equals(tb testing.TB, exp, act interface{}) {
13 | if !reflect.DeepEqual(exp, act) {
14 | _, file, line, _ := runtime.Caller(1)
15 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
16 | tb.FailNow()
17 | }
18 | }
19 |
20 | // ok fails the test if an err is not nil.
21 | func ok(tb testing.TB, err error) {
22 | if err != nil {
23 | _, file, line, _ := runtime.Caller(1)
24 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
25 | tb.FailNow()
26 | }
27 | }
28 |
29 | // assert fails the test if the condition is false.
30 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
31 | if !condition {
32 | _, file, line, _ := runtime.Caller(1)
33 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
34 | tb.FailNow()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algo/curve25519/curve25519_test.go:
--------------------------------------------------------------------------------
1 | package curve25519
2 |
3 | import (
4 | "testing"
5 |
6 | "encoding/hex"
7 | )
8 |
9 | func TestSwap(t *testing.T) {
10 | a := newCoord(1)
11 | b := newCoord(2)
12 |
13 | a, b = cswap(1, a, b)
14 | equals(t, newCoord(1), b)
15 | equals(t, newCoord(2), a)
16 |
17 | a, b = cswap(0, a, b)
18 | equals(t, newCoord(1), b)
19 | equals(t, newCoord(2), a)
20 | }
21 |
22 | func TestMult(t *testing.T) {
23 | var key = [32]byte{
24 | 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
25 | 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
26 | }
27 | var expect = [32]byte{
28 | 0x07, 0xa3, 0x7c, 0xbc, 0x14, 0x20, 0x93, 0xc8, 0xb7, 0x55, 0xdc, 0x1b, 0x10, 0xe8, 0x6c, 0xb4,
29 | 0x26, 0x37, 0x4a, 0xd1, 0x6a, 0xa8, 0x53, 0xed, 0x0b, 0xdf, 0xc0, 0xb2, 0xb8, 0x6d, 0x1c, 0x7c,
30 | }
31 |
32 | out := Mult(key, u_nine_bytes)
33 | equals(t, expect, out)
34 | }
35 |
36 | func TestKeyPair(t *testing.T) {
37 | priv, pub, err := KeyPair()
38 | ok(t, err)
39 |
40 | t.Log("private key:", hex.EncodeToString(priv[:]))
41 | t.Log(" public key:", hex.EncodeToString(pub[:]))
42 | }
43 |
--------------------------------------------------------------------------------
/algo/gcm/mult_block.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | var r = []byte{0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
4 |
5 | func multBlocks(X, Y []byte) []byte {
6 | if len(X) != 16 || len(Y) != 16 {
7 | panic("multBlocks bad block length")
8 | }
9 | Z := make([]byte, 16)
10 | V := make([]byte, 16)
11 | Zero := make([]byte, 16)
12 | copy(V[:], Y)
13 | for i := 0; i < 128; i++ {
14 | if bit(X, i) == 0 {
15 | xor(Z, Zero)
16 | } else {
17 | xor(Z, V)
18 | }
19 | lv := bit(V, 127) != 0
20 | shiftr(V)
21 | if lv {
22 | xor(V, r)
23 | } else {
24 | xor(V, Zero)
25 | }
26 | }
27 | return Z
28 | }
29 |
30 | // where 0 is the first bit, ie. most significant in BE terms
31 | func bit(b []byte, bitnum int) byte {
32 | i := uint(0)
33 | for bitnum >= 8 {
34 | i++
35 | bitnum -= 8
36 | }
37 | return b[i] >> uint(7-bitnum) & 1
38 | }
39 |
40 | func xor(dst, xad []byte) {
41 | if len(dst) != len(xad) {
42 | panic("xor mismatch len")
43 | }
44 | for i := range dst {
45 | dst[i] = dst[i] ^ xad[i]
46 | }
47 | }
48 |
49 | func shiftr(b []byte) {
50 | carry := byte(0)
51 | for i := range b {
52 | newcarry := b[i] & 1
53 | b[i] >>= 1
54 | b[i] |= carry << 7
55 | carry = newcarry
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/cmd/tincan-client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/syncsynchalt/tincan-tls/tls"
6 | "io"
7 | "net"
8 | "os"
9 | )
10 |
11 | func main() {
12 | if len(os.Args) != 3 {
13 | fmt.Fprintf(os.Stderr, "Usage: %s host port\n", os.Args[0])
14 | os.Exit(1)
15 | }
16 | host := os.Args[1]
17 | port := os.Args[2]
18 | conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", host, port))
19 | if err != nil {
20 | panic(err)
21 | }
22 |
23 | tlsConn, err := tls.NewConn(conn, host)
24 | if err != nil {
25 | panic(err)
26 | }
27 |
28 | go func() {
29 | rbuf := make([]byte, 102400)
30 | for {
31 | n, err := tlsConn.Read(rbuf)
32 | if n != 0 {
33 | os.Stdout.Write(rbuf[:n])
34 | }
35 | if n == 0 || err == io.EOF {
36 | break
37 | }
38 | if err != nil {
39 | panic(err)
40 | }
41 | }
42 | fmt.Fprintln(os.Stderr, "EOF from peer")
43 | tlsConn.Close()
44 | os.Exit(0)
45 | }()
46 |
47 | wbuf := make([]byte, 102400)
48 | for {
49 | n, err := os.Stdin.Read(wbuf)
50 | if n != 0 {
51 | tlsConn.Write(wbuf[:n])
52 | }
53 | if err == io.EOF {
54 | break
55 | }
56 | if err != nil {
57 | panic(err)
58 | }
59 | }
60 |
61 | tlsConn.Close()
62 | }
63 |
--------------------------------------------------------------------------------
/algo/hmac/hmac.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // from RFC 2104
5 |
6 | package hmac
7 |
8 | type Hasher interface {
9 | Reset()
10 | Add([]byte)
11 | Sum() []byte
12 | BlockSize() int
13 | HashLen() int
14 | }
15 |
16 | func Compute(key, data []byte, h Hasher) []byte {
17 | if len(key) > h.BlockSize() {
18 | h.Reset()
19 | h.Add(key)
20 | key = h.Sum()
21 | }
22 | for len(key) < h.BlockSize() {
23 | key = append(key, 0)
24 | }
25 | ipad := repeat(0x36, h.BlockSize())
26 | opad := repeat(0x5c, h.BlockSize())
27 | h.Reset()
28 | h.Add(xor(key, ipad))
29 | h.Add(data)
30 | s1 := h.Sum()
31 | h.Reset()
32 | h.Add(xor(key, opad))
33 | h.Add(s1)
34 | return h.Sum()
35 | }
36 |
37 | func repeat(b byte, length int) []byte {
38 | r := make([]byte, length)
39 | for i := range r {
40 | r[i] = b
41 | }
42 | return r
43 | }
44 |
45 | func min(a, b int) int {
46 | if a < b {
47 | return a
48 | } else {
49 | return b
50 | }
51 | }
52 |
53 | func xor(a, b []byte) []byte {
54 | l := min(len(a), len(b))
55 | result := make([]byte, l)
56 | for i := range result {
57 | result[i] = a[i] ^ b[i]
58 | }
59 | return result
60 | }
61 |
--------------------------------------------------------------------------------
/algo/gcm/hash_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestGHashOne(t *testing.T) {
8 | a := make16([]byte{1})
9 | h := make16([]byte{2})
10 |
11 | result := ghash(h, a)
12 |
13 | // X1•Hm ⊕ X2•Hm-1 ⊕ ... ⊕ Xm-1•H2 ⊕ Xm•H
14 | calc1 := multBlocks(a, h)
15 | equals(t, calc1, result)
16 | }
17 |
18 | func TestGHashTwo(t *testing.T) {
19 | a := make16([]byte{1})
20 | b := make16([]byte{2})
21 | c := a
22 | c = append(c, b...)
23 | h := make16([]byte{0x10, 0x20, 0x30})
24 | h2 := multBlocks(h, h)
25 |
26 | result := ghash(h, c)
27 |
28 | // X1•Hm ⊕ X2•Hm-1 ⊕ ... ⊕ Xm-1•H2 ⊕ Xm•H
29 | calc1 := multBlocks(a, h2)
30 | calc_ := multBlocks(b, h)
31 | xor(calc1, calc_)
32 | equals(t, calc1, result)
33 | }
34 |
35 | func TestGHashMult(t *testing.T) {
36 | a := make16([]byte{1})
37 | b := make16([]byte{2})
38 | c := make16([]byte{3})
39 | d := a
40 | d = append(d, b...)
41 | d = append(d, c...)
42 | h1 := make16([]byte{0x16, 0x20, 0x3f})
43 | h2 := multBlocks(h1, h1)
44 | h3 := multBlocks(h2, h1)
45 |
46 | result := ghash(h1, d)
47 |
48 | // X1•Hm ⊕ X2•Hm-1 ⊕ ... ⊕ Xm-1•H2 ⊕ Xm•H
49 | calc1 := multBlocks(a, h3)
50 | calc2 := multBlocks(b, h2)
51 | calc3 := multBlocks(c, h1)
52 | xor(calc1, calc2)
53 | xor(calc1, calc3)
54 | equals(t, calc1, result)
55 | }
56 |
--------------------------------------------------------------------------------
/tls/test_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "reflect"
7 | "runtime"
8 | "testing"
9 |
10 | "encoding/hex"
11 | "strings"
12 | )
13 |
14 | // equals fails the test if exp is not equal to act.
15 | func equals(tb testing.TB, exp, act interface{}) {
16 | if !reflect.DeepEqual(exp, act) {
17 | _, file, line, _ := runtime.Caller(1)
18 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
19 | tb.FailNow()
20 | }
21 | }
22 |
23 | // ok fails the test if an err is not nil.
24 | func ok(tb testing.TB, err error) {
25 | if err != nil {
26 | _, file, line, _ := runtime.Caller(1)
27 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
28 | tb.FailNow()
29 | }
30 | }
31 |
32 | // assert fails the test if the condition is false.
33 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
34 | if !condition {
35 | _, file, line, _ := runtime.Caller(1)
36 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
37 | tb.FailNow()
38 | }
39 | }
40 |
41 | func hexBytes(s string) []byte {
42 | // strip spaces
43 | s = strings.Join(strings.Fields(s), "")
44 | b, err := hex.DecodeString(s)
45 | if err != nil {
46 | panic("bad hex input")
47 | }
48 | return b
49 | }
50 |
--------------------------------------------------------------------------------
/tls/constants.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | var (
4 | kTLS_VERSION_12 = []byte{0x03, 0x03}
5 | kTLS_VERSION_13 = []byte{0x03, 0x04}
6 |
7 | kTLS_AES_128_GCM_SHA256 = []byte{0x13, 0x01}
8 | kTLS_RSA_PKCS1_SHA256 = []byte{0x04, 0x01}
9 | kTLS_ECDSA_SECP256R1_SHA256 = []byte{0x04, 0x03}
10 | kTLS_RSA_PSS_RSAE_SHA256 = []byte{0x08, 0x04}
11 |
12 | kEXT_SERVER_NAME = 0
13 | kEXT_SERVER_NAME_HOST = byte(0)
14 | kEXT_SUPPORTED_GROUPS = 10
15 | kEXT_SUPPORTED_GROUPS_X25519 = []byte{0, 29}
16 | kEXT_SIGNATURE_ALGORITHMS = 13
17 | kEXT_SUPPORTED_VERSIONS = 43
18 | kEXT_COOKIE = 44
19 | kEXT_KEY_SHARE = 51
20 |
21 | kREC_TYPE_CHANGE_CIPHER_SPEC = byte(20)
22 | kREC_TYPE_ALERT = byte(21)
23 | kREC_TYPE_HANDSHAKE = byte(22)
24 | kREC_TYPE_APPLICATION_DATA = byte(23)
25 |
26 | kHS_TYPE_CLIENT_HELLO = byte(1)
27 | kHS_TYPE_SERVER_HELLO = byte(2)
28 | kHS_TYPE_NEW_SESSION_TICKET = byte(4)
29 | kHS_TYPE_ENCRYPTED_EXTENSIONS = byte(8)
30 | kHS_TYPE_CERTIFICATE = byte(11)
31 | kHS_TYPE_CERTIFICATE_VERIFY = byte(15)
32 | kHS_TYPE_FINISHED = byte(20)
33 |
34 | kHS_HELLO_RETRY_REQUEST = []byte{
35 | 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
36 | 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
37 | }
38 | )
39 |
--------------------------------------------------------------------------------
/tls/conncrypt.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "github.com/syncsynchalt/tincan-tls/algo/aes"
5 | "github.com/syncsynchalt/tincan-tls/algo/gcm"
6 | )
7 |
8 | func (conn *TLSConn) decryptRecord(rechdr []byte, record []byte) (plaintext []byte) {
9 | cipher := aes.New128(conn.serverWriteKey[:])
10 | ciphertext := record[:len(record)-gcm.TagLength]
11 | iv := buildIV(conn.serverSeq, conn.serverWriteIV[:])
12 | adata := rechdr
13 | tag := record[len(record)-gcm.TagLength:]
14 |
15 | plain, failed := gcm.Decrypt(cipher, iv, ciphertext, adata, tag)
16 | if failed {
17 | panic("decrypt app record failed")
18 | }
19 | return plain
20 | }
21 |
22 | func (conn *TLSConn) createEncryptedRecord(plaintext []byte) ([]byte, error) {
23 | ll := len(plaintext) + gcm.TagLength
24 | iv := buildIV(conn.clientSeq, conn.clientWriteIV[:])
25 |
26 | rechdr := make([]byte, 0)
27 | rechdr = append(rechdr, kREC_TYPE_APPLICATION_DATA)
28 | rechdr = append(rechdr, kTLS_VERSION_12...)
29 | rechdr = appendLen16(rechdr, ll)
30 |
31 | cipher := aes.New128(conn.clientWriteKey[:])
32 | crypted, tag := gcm.Encrypt(cipher, iv, plaintext, rechdr)
33 | if ll != len(crypted)+len(tag) {
34 | panic("bad encrypt length calc")
35 | }
36 |
37 | rec := make([]byte, 0)
38 | rec = append(rec, rechdr...)
39 | rec = append(rec, crypted...)
40 | rec = append(rec, tag...)
41 | return rec, nil
42 | }
43 |
44 | func buildIV(seq uint64, base []byte) []byte {
45 | result := make([]byte, len(base))
46 | copy(result, base)
47 | for i := 0; i < 8; i++ {
48 | result[len(result)-i-1] ^= byte(seq >> uint(8*i))
49 | }
50 | return result
51 | }
52 |
--------------------------------------------------------------------------------
/algo/gcm/mult_block_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func make16(b []byte) []byte {
8 | for len(b) < 16 {
9 | b = append(b, 0)
10 | }
11 | return b
12 | }
13 |
14 | // test commutative property
15 | func TestCommute(t *testing.T) {
16 | a := make16([]byte{0x01, 0x02})
17 | b := make16([]byte{0x02, 0x03})
18 |
19 | c := multBlocks(a, b)
20 | d := multBlocks(b, a)
21 |
22 | equals(t, c, d)
23 | }
24 |
25 | // test distributive property, (a+b)*c == (a*c)+(b*c)
26 | func TestDistrib(t *testing.T) {
27 | a := make16([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3})
28 | b := make16([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4})
29 | c := make16([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 5})
30 |
31 | aplusb := make16([]byte{})
32 | copy(aplusb, a)
33 | xor(aplusb, b)
34 | d1 := multBlocks(aplusb, c)
35 |
36 | d2 := multBlocks(a, c)
37 | d_ := multBlocks(b, c)
38 | xor(d2, d_)
39 |
40 | equals(t, d1, d2)
41 | }
42 |
43 | // order of GF(2^128) is 2^128-1, so squaring 128 times should result in identity
44 | func TestOrder(t *testing.T) {
45 | a := make16([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3})
46 | b := make16([]byte{})
47 | copy(b, a)
48 |
49 | t.Log(b)
50 | for i := 0; i < 128; i++ {
51 | b = multBlocks(b, b)
52 | t.Log(b)
53 | }
54 | equals(t, a[:], b)
55 | }
56 |
57 | func TestTestVector(t *testing.T) {
58 | a := make16([]byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff})
59 | b := make16([]byte{0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78, 0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2, 0xe1, 0xf0})
60 | e := make16([]byte{0x91, 0x61, 0x62, 0x9d, 0xe5, 0xfa, 0x86, 0x86, 0x1d, 0xa2, 0xde, 0xde, 0x59, 0xb9, 0x3a, 0xc5})
61 | c := multBlocks(a, b)
62 | equals(t, e, c)
63 | }
64 |
--------------------------------------------------------------------------------
/tls/serveralert.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | func handleAlert(conn *TLSConn, payload []byte) action {
4 | if len(payload) < 2 {
5 | panic("short alert")
6 | }
7 |
8 | prefix := ""
9 | switch payload[0] {
10 | case 1:
11 | prefix = "warning alert: "
12 | case 2:
13 | prefix = "fatal alert: "
14 | default:
15 | prefix = "unknown alert: "
16 | }
17 |
18 | switch payload[1] {
19 | case 0:
20 | panic(prefix + "close notify")
21 | case 10:
22 | panic(prefix + "unexpected message")
23 | case 20:
24 | panic(prefix + "bad record MAC")
25 | case 22:
26 | panic(prefix + "record overflow")
27 | case 40:
28 | panic(prefix + "handshake failure")
29 | case 42:
30 | panic(prefix + "bad certificate")
31 | case 43:
32 | panic(prefix + "unsupported certificate")
33 | case 44:
34 | panic(prefix + "certificate revoked")
35 | case 45:
36 | panic(prefix + "certificate expired")
37 | case 46:
38 | panic(prefix + "certificate unknown")
39 | case 47:
40 | panic(prefix + "illegal parameter")
41 | case 48:
42 | panic(prefix + "unknown CA")
43 | case 49:
44 | panic(prefix + "access denied")
45 | case 50:
46 | panic(prefix + "decode error")
47 | case 51:
48 | panic(prefix + "decrypt error")
49 | case 70:
50 | panic(prefix + "protocol version")
51 | case 71:
52 | panic(prefix + "insufficient security")
53 | case 80:
54 | panic(prefix + "internal error")
55 | case 86:
56 | panic(prefix + "inappropriate fallback")
57 | case 90:
58 | panic(prefix + "user canceled")
59 | case 109:
60 | panic(prefix + "missing extension")
61 | case 110:
62 | panic(prefix + "unsupported extension")
63 | case 112:
64 | panic(prefix + "unrecognized name")
65 | case 113:
66 | panic(prefix + "bad certificate status response")
67 | case 115:
68 | panic(prefix + "unknown PSK identity")
69 | case 116:
70 | panic(prefix + "certificate required")
71 | case 120:
72 | panic(prefix + "no application protocol")
73 | default:
74 | panic(prefix + "unknown alert")
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # tincan-tls
2 |
3 |
5 |
6 | This is a soup-to-nuts implementation of [TLS 1.3](https://tools.ietf.org/html/rfc8446)
7 | created by staring at documents for hours until code came out. The
8 | single goal was to establish a valid TLS session by any means
9 | possible and trick servers into talking to me.
10 |
11 | This code is crude and lumpy and ugly. This is intentional and
12 | should serve as a warning to others: this code is not usable for
13 | real work. In particular the crypto code is slow and full of timing
14 | side-channels. Any attempts to clean things up will be viewed as
15 | an attempt to trick someone else into using this code and will be
16 | rejected.
17 |
18 | To win a bet I implemented this with as few dependencies as possible.
19 | The crypto library has only one dependency, `crypto/rand`. This
20 | caused some code to be particularly un-golangly as I couldn't create
21 | `error` objects.
22 |
23 | > Note: The above paragraphs are examples of bad software practices.
24 |
25 | ### Usage
26 |
27 | Build and run with the following:
28 |
29 | ```
30 | go get github.com/syncsynchalt/tincan-tls/cmd/tincan-client
31 | export PATH=$PATH:~/go/bin
32 | tincan-client host port
33 | ```
34 |
35 | ### Algorithms
36 |
37 | The following algorithms were built for this implementation:
38 |
39 | * `SHA-256` message digest - [RFC 6234](https://tools.ietf.org/html/rfc6234)
40 | * `HMAC` message authentication codes - [RFC 2104](https://tools.ietf.org/html/rfc2104)
41 | * `AES-128` symmetric cipher - [FIPS 197](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf)
42 | * `curve25519` (a particular elliptic curve) - [RFC 7748](https://tools.ietf.org/html/rfc7748)
43 | * `ECDHE` (Elliptic Curve Diffie-Hellman with Ephemeral keys) - [RFC 4492](https://tools.ietf.org/html/rfc4492)
44 | * `GCM` (Galois/Counter Mode) - [NIST SP 800-38D](https://csrc.nist.gov/publications/detail/sp/800-38d/final)
45 | * `HKDF` (HMAC Key Derivation Function) - [RFC 5869](https://tools.ietf.org/html/rfc5869)
46 |
--------------------------------------------------------------------------------
/algo/curve25519/curve25519.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on RFC 7748
5 |
6 | package curve25519
7 |
8 | import (
9 | "crypto/rand"
10 | )
11 |
12 | var (
13 | u_nine_bytes = newCoord(9).toBytes()
14 | u_a24 = newCoord(121665)
15 | u_p = coordModulus
16 | u_p_minus_2 = coordModulus.sub(newCoord(2))
17 | )
18 |
19 | func KeyPair() (priv, pub [32]byte, err error) {
20 | _, err = rand.Read(priv[:])
21 | if err != nil {
22 | return
23 | }
24 |
25 | b := Mult(priv, u_nine_bytes)
26 | copy(pub[:], b[:])
27 | return
28 | }
29 |
30 | func Mult(scalar, base [32]byte) [32]byte {
31 | // clamp, from https://cr.yp.to/ecdh.html
32 | scalar[0] &= 248
33 | scalar[31] &= 127 // sign bit from RFC
34 | scalar[31] |= 64
35 |
36 | k := bytesToCoord(scalar)
37 | u := bytesToCoord(base)
38 |
39 | x_1 := u.copy()
40 | x_2 := newCoord(1)
41 | z_2 := newCoord(0)
42 | x_3 := u.copy()
43 | z_3 := newCoord(1)
44 | swap := 0
45 |
46 | // Montgomery ladder around DoubleAndAdd
47 | for t := 255 - 1; t >= 0; t-- {
48 | k_t := k.nbit(uint(t))
49 | swap ^= k_t
50 | x_2, x_3 = cswap(swap, x_2, x_3)
51 | z_2, z_3 = cswap(swap, z_2, z_3)
52 | swap = k_t
53 |
54 | A := x_2.add(z_2).reduce()
55 | AA := A.mult(A).reduce()
56 | B := x_2.sub(z_2).reduce()
57 | BB := B.mult(B).reduce()
58 | E := AA.sub(BB).reduce()
59 | C := x_3.add(z_3).reduce()
60 | D := x_3.sub(z_3).reduce()
61 | DA := D.mult(A).reduce()
62 | CB := C.mult(B).reduce()
63 | x_3 = DA.add(CB).reduce()
64 | x_3 = x_3.mult(x_3).reduce()
65 | z_3 = DA.sub(CB).reduce()
66 | z_3 = z_3.mult(z_3).reduce()
67 | z_3 = x_1.mult(z_3).reduce()
68 | x_2 = AA.mult(BB).reduce()
69 | z_2 = u_a24.mult(E).reduce()
70 | z_2 = AA.add(z_2).reduce()
71 | z_2 = E.mult(z_2).reduce()
72 | }
73 |
74 | x_2, x_3 = cswap(swap, x_2, x_3)
75 | z_2, z_3 = cswap(swap, z_2, z_3)
76 | result := z_2.exp(u_p_minus_2).reduce()
77 | result = x_2.mult(result).reduce()
78 | return result.toBytes()
79 | }
80 |
81 | // conditional swap, with some constant-time magic
82 | func cswap(swap int, x_2, x_3 coord) (coord, coord) {
83 | mask := uint64(0)
84 | if swap != 0 {
85 | mask = 0xFFFFFFFFFFFFFFFF
86 | } else {
87 | mask = 0x00
88 | }
89 | dummy := coord{}
90 | for i := range dummy {
91 | dummy[i] = mask & (x_2[i] ^ x_3[i])
92 | x_2[i] = x_2[i] ^ dummy[i]
93 | x_3[i] = x_3[i] ^ dummy[i]
94 | }
95 | return x_2, x_3
96 | }
97 |
--------------------------------------------------------------------------------
/algo/gcm/gcm.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on NIST SP 800-38D (https://csrc.nist.gov/publications/detail/sp/800-38d/final)
5 |
6 | package gcm
7 |
8 | var (
9 | // from RFC 5288, all defined AEAD ciphers have tag length of 128 bits
10 | TagLength = 16
11 | )
12 |
13 | type Cipher interface {
14 | BlockSize() int
15 | KeySize() int
16 | Encrypt(in, out []byte)
17 | }
18 |
19 | func Encrypt(cipher Cipher, iv, plaintext, adata []byte) (ciphertext []byte, authtag []byte) {
20 | if len(iv) != 12 {
21 | panic("gcm unexpected iv length")
22 | }
23 |
24 | zeroBlock := make([]byte, cipher.BlockSize())
25 | H := make([]byte, cipher.BlockSize())
26 | cipher.Encrypt(zeroBlock, H)
27 |
28 | J0 := append(iv, 0, 0, 0, 1)
29 | J1 := copyBytes(J0)
30 | inc_32(J1)
31 |
32 | ctext := gctr(cipher, J1, plaintext)
33 | u := (16 - len(ctext)%16) % 16
34 | v := (16 - len(adata)%16) % 16
35 |
36 | inS := adata
37 | inS = append(inS, zeroBlock[:v]...)
38 | inS = append(inS, ctext...)
39 | inS = append(inS, zeroBlock[:u]...)
40 | inS = append(inS, uint64ToBEBytes(uint64(8*len(adata)))...)
41 | inS = append(inS, uint64ToBEBytes(uint64(8*len(ctext)))...)
42 | S := ghash(H, inS)
43 |
44 | T := gctr(cipher, J0, S)
45 | T = T[:TagLength]
46 |
47 | return ctext, T
48 | }
49 |
50 | func uint64ToBEBytes(n uint64) []byte {
51 | b := make([]byte, 8)
52 | for i := 0; i < 8; i++ {
53 | b[i] = byte(n >> uint(56-8*i))
54 | }
55 | return b
56 | }
57 |
58 | func copyBytes(b []byte) []byte {
59 | c := make([]byte, len(b))
60 | copy(c, b)
61 | return c
62 | }
63 |
64 | func Decrypt(cipher Cipher, iv, ciphertext, adata, tag []byte) (plaintext []byte, failed bool) {
65 | if len(iv) != 12 {
66 | panic("gcm unexpected iv length")
67 | }
68 |
69 | zeroBlock := make([]byte, cipher.BlockSize())
70 | H := make([]byte, cipher.BlockSize())
71 | cipher.Encrypt(zeroBlock, H)
72 |
73 | J0 := append(iv, 0, 0, 0, 1)
74 | J1 := copyBytes(J0)
75 | inc_32(J1)
76 |
77 | plain := gctr(cipher, J1, ciphertext)
78 | u := (16 - len(ciphertext)%16) % 16
79 | v := (16 - len(adata)%16) % 16
80 |
81 | inS := make([]byte, 0)
82 | inS = append(inS, adata...)
83 | inS = append(inS, zeroBlock[:v]...)
84 | inS = append(inS, ciphertext...)
85 | inS = append(inS, zeroBlock[:u]...)
86 | inS = append(inS, uint64ToBEBytes(uint64(8*len(adata)))...)
87 | inS = append(inS, uint64ToBEBytes(uint64(8*len(ciphertext)))...)
88 | S := ghash(H, inS)
89 |
90 | T := gctr(cipher, J0, S)
91 | T = T[:TagLength]
92 | for i := range tag {
93 | if T[i] != tag[i] {
94 | return []byte{}, true
95 | }
96 | }
97 | return plain, false
98 | }
99 |
--------------------------------------------------------------------------------
/algo/hkdf/hkdf_test.go:
--------------------------------------------------------------------------------
1 | package hkdf_test
2 |
3 | import (
4 | "encoding/hex"
5 | "github.com/syncsynchalt/tincan-tls/algo/hkdf"
6 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
7 | "testing"
8 | )
9 |
10 | func TestVec1(t *testing.T) {
11 | ikm, _ := hex.DecodeString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
12 | salt, _ := hex.DecodeString("000102030405060708090a0b0c")
13 | info, _ := hex.DecodeString("f0f1f2f3f4f5f6f7f8f9")
14 | eprk, _ := hex.DecodeString("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5")
15 | eokm, _ := hex.DecodeString("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf" +
16 | "34007208d5b887185865")
17 | L := 42
18 |
19 | h := sha256.New()
20 | prk := hkdf.Extract(h, salt, ikm)
21 | equals(t, eprk, prk)
22 | okm := hkdf.Expand(h, prk, info, L)
23 | equals(t, eokm, okm)
24 | }
25 |
26 | func TestVec2(t *testing.T) {
27 | ikm, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f" +
28 | "101112131415161718191a1b1c1d1e1f" +
29 | "202122232425262728292a2b2c2d2e2f" +
30 | "303132333435363738393a3b3c3d3e3f" +
31 | "404142434445464748494a4b4c4d4e4f")
32 | salt, _ := hex.DecodeString("606162636465666768696a6b6c6d6e6f" +
33 | "707172737475767778797a7b7c7d7e7f" +
34 | "808182838485868788898a8b8c8d8e8f" +
35 | "909192939495969798999a9b9c9d9e9f" +
36 | "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf")
37 | info, _ := hex.DecodeString("b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" +
38 | "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" +
39 | "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" +
40 | "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" +
41 | "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
42 | eprk, _ := hex.DecodeString("06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244")
43 | eokm, _ := hex.DecodeString("b11e398dc80327a1c8e7f78c596a4934" +
44 | "4f012eda2d4efad8a050cc4c19afa97c" +
45 | "59045a99cac7827271cb41c65e590e09" +
46 | "da3275600c2f09b8367793a9aca3db71" +
47 | "cc30c58179ec3e87c14c01d5c1f3434f" +
48 | "1d87")
49 | L := 82
50 |
51 | h := sha256.New()
52 | prk := hkdf.Extract(h, salt, ikm)
53 | equals(t, eprk, prk)
54 | okm := hkdf.Expand(h, prk, info, L)
55 | equals(t, eokm, okm)
56 | }
57 |
58 | func TestVec3(t *testing.T) {
59 | ikm, _ := hex.DecodeString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
60 | salt, _ := hex.DecodeString("")
61 | info, _ := hex.DecodeString("")
62 | eprk, _ := hex.DecodeString("19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04")
63 | eokm, _ := hex.DecodeString("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d" +
64 | "9d201395faa4b61a96c8")
65 | L := 42
66 |
67 | h := sha256.New()
68 | prk := hkdf.Extract(h, salt, ikm)
69 | equals(t, eprk, prk)
70 | okm := hkdf.Expand(h, prk, info, L)
71 | equals(t, eokm, okm)
72 | }
73 |
--------------------------------------------------------------------------------
/algo/gcm/gctr_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "encoding/hex"
5 | "testing"
6 |
7 | "github.com/syncsynchalt/tincan-tls/algo/aes"
8 | )
9 |
10 | func TestGctrIndependent(t *testing.T) {
11 | key := []byte{0xff, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
12 | t.Log("key:", hex.EncodeToString(key))
13 |
14 | x := make([]byte, 48)
15 | x[0] = 1
16 | x[16] = 2
17 | x[32] = 3
18 | t.Log("plaintext:", hex.EncodeToString(x))
19 |
20 | icb := []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
21 | t.Log("icb:", hex.EncodeToString(icb))
22 |
23 | // found using openssl enc command line tool
24 | ccb1, _ := hex.DecodeString("fc7a6d88a672b5fab0f2f1982c7851b9")
25 | ccb2, _ := hex.DecodeString("d51377c6d7b957ba75f5f9525589a4ff")
26 | ccb3, _ := hex.DecodeString("51ce5e4c40546a0d88a908955faff973")
27 | xor(ccb1, x[0:16])
28 | xor(ccb2, x[16:32])
29 | xor(ccb3, x[32:48])
30 | expect := ccb1
31 | expect = append(expect, ccb2...)
32 | expect = append(expect, ccb3...)
33 |
34 | cipher := aes.New128(key)
35 | result := gctr(cipher, icb, x)
36 | equals(t, expect, result)
37 | }
38 |
39 | func expectedResult(key, icb, plaintext []byte) []byte {
40 | cipher := aes.New128(key)
41 | expected := make([]byte, 0)
42 | out := make([]byte, 16)
43 | scratch := make([]byte, 16)
44 | cb := copyBytes(icb)
45 |
46 | for len(plaintext) > 0 {
47 | cipher.Encrypt(cb, out)
48 | l := 16
49 | if len(plaintext) < 16 {
50 | l = len(plaintext)
51 | }
52 | copy(scratch, plaintext)
53 | xor(out, scratch)
54 | expected = append(expected, out[:l]...)
55 |
56 | inc_32(cb)
57 | plaintext = plaintext[l:]
58 | }
59 | return expected
60 | }
61 |
62 | func TestGctrFullBlock(t *testing.T) {
63 | key := []byte{10, 11, 12, 13, 14, 15, 16, 17, 28, 29, 30, 31, 32, 33, 34, 35}
64 |
65 | x := make([]byte, 48)
66 | for i := range x {
67 | x[i] = byte(i)
68 | }
69 | t.Log("plaintext:", hex.EncodeToString(x))
70 |
71 | icb := []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
72 | t.Log("icb:", hex.EncodeToString(icb))
73 |
74 | expect := expectedResult(key, icb, x)
75 |
76 | cipher := aes.New128(key)
77 | result := gctr(cipher, icb, x)
78 | equals(t, expect, result)
79 | }
80 |
81 | func TestGctrPartBlocks(t *testing.T) {
82 | key := []byte{10, 11, 12, 13, 14, 15, 16, 17, 28, 29, 30, 31, 32, 33, 34, 35}
83 | cipher := aes.New128(key)
84 |
85 | x := make([]byte, 1024)
86 | for i := range x {
87 | x[i] = byte(i)
88 | }
89 |
90 | icb := []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
91 |
92 | for i := 0; i < 32; i++ {
93 | t.Log("testing plaintext of", len(x), "bytes")
94 | expect := expectedResult(key, icb, x)
95 | result := gctr(cipher, icb, x)
96 | equals(t, expect, result)
97 | x = x[:len(x)-1]
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/algo/hmac/hmac_test.go:
--------------------------------------------------------------------------------
1 | package hmac_test
2 |
3 | import (
4 | "testing"
5 |
6 | "encoding/hex"
7 |
8 | "github.com/syncsynchalt/tincan-tls/algo/hmac"
9 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
10 | )
11 |
12 | func h(sum []byte) string {
13 | return hex.EncodeToString(sum)
14 | }
15 |
16 | func b(s string) []byte {
17 | return []byte(s)
18 | }
19 |
20 | func TestShort(t *testing.T) {
21 | s := sha256.New()
22 | key := make([]byte, 32)
23 | for i := range key {
24 | key[i] = byte(i)
25 | }
26 | data := b("abcd")
27 | equals(t, "ce5ab0733fe9b6f0767e841868c523e7db0c60d1fe6f276399fdee63d61d6c5b", h(hmac.Compute(key, data, s)))
28 | }
29 |
30 | func TestSimple(t *testing.T) {
31 | s := sha256.New()
32 | key := make([]byte, 64)
33 | for i := range key {
34 | key[i] = byte(i)
35 | }
36 | data := b("abcd")
37 | equals(t, "7eb364829d5bc45f32c18799e8aa3f23fa86a1aff4e747eae54ce1771b6b2ce2", h(hmac.Compute(key, data, s)))
38 | }
39 |
40 | func TestLongKey(t *testing.T) {
41 | s := sha256.New()
42 | key := make([]byte, 70)
43 | for i := range key {
44 | key[i] = byte(i)
45 | }
46 | data := b("abcd")
47 | equals(t, "1ae43d93e2b3ef5de29a06231bd5c1e2699d62db9cc7457f5b7c2e707bab5b4f", h(hmac.Compute(key, data, s)))
48 | }
49 |
50 | func TestPad(t *testing.T) {
51 | s := sha256.New()
52 | key := []byte{0x1, 0x2, 0x3, 0x4}
53 | data := b("abcd")
54 | equals(t, "a7201c7404c3cebbaa55742e9d3cda4495682d53138192738cf9d26ef4f2422e", h(hmac.Compute(key, data, s)))
55 | }
56 |
57 | func TestZeros(t *testing.T) {
58 | s := sha256.New()
59 | key := []byte{}
60 | data := []byte{}
61 | equals(t, "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", h(hmac.Compute(key, data, s)))
62 | }
63 |
64 | func TestLong(t *testing.T) {
65 | s := sha256.New()
66 | key := []byte{0x1, 0x2, 0x3, 0x4}
67 | str := ""
68 | for i := 0; i < 1000; i++ {
69 | str += "1234567890"
70 | }
71 | data := b(str)
72 | equals(t, "a726645fabd1dc68c14d07a33de851d7a3a0d86d5c988754e066e8105beb6061", h(hmac.Compute(key, data, s)))
73 | }
74 |
75 | // test vectors from RFC 4231
76 | func TestRfcVec1(t *testing.T) {
77 | s := sha256.New()
78 | key, _ := hex.DecodeString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
79 | data := []byte("Hi There")
80 | expect, _ := hex.DecodeString("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7")
81 | equals(t, expect, hmac.Compute(key, data, s))
82 | }
83 |
84 | func TestRfcVec2(t *testing.T) {
85 | s := sha256.New()
86 | key := []byte("Jefe")
87 | data := []byte("what do ya want for nothing?")
88 | expect, _ := hex.DecodeString("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")
89 | equals(t, expect, hmac.Compute(key, data, s))
90 | }
91 |
92 | func TestRfcVec3(t *testing.T) {
93 | s := sha256.New()
94 | key, _ := hex.DecodeString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
95 | data, _ := hex.DecodeString("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" +
96 | "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD")
97 | expect, _ := hex.DecodeString("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe")
98 | equals(t, expect, hmac.Compute(key, data, s))
99 | }
100 |
--------------------------------------------------------------------------------
/tls/computekeys.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "github.com/syncsynchalt/tincan-tls/algo/ecdhe"
5 | "github.com/syncsynchalt/tincan-tls/algo/hkdf"
6 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
7 | )
8 |
9 | func computeHandshakeKeys(conn *TLSConn) {
10 | salt := []byte{}
11 | psk := [32]byte{}
12 | sharedSecret := ecdhe.CalculateSharedSecret(conn.clientPrivKey[:], conn.serverPubKey[:])
13 | earlySecret := hkdf.Extract(sha256.New(), salt, psk[:])
14 | derivedSecret := deriveSecret(earlySecret, "derived", []byte{})
15 | handshakeSecret := hkdf.Extract(sha256.New(), derivedSecret, sharedSecret)
16 | copy(conn.clientHandshakeTrafficSecret[:], deriveSecret(handshakeSecret, "c hs traffic", conn.transcript))
17 | copy(conn.serverHandshakeTrafficSecret[:], deriveSecret(handshakeSecret, "s hs traffic", conn.transcript))
18 | derivedSecret = deriveSecret(handshakeSecret, "derived", []byte{})
19 | zeros := [32]byte{}
20 | masterSecret := hkdf.Extract(sha256.New(), derivedSecret, zeros[:])
21 | copy(conn.masterSecret[:], masterSecret)
22 | csecret := conn.clientHandshakeTrafficSecret[:]
23 | ssecret := conn.serverHandshakeTrafficSecret[:]
24 | copy(conn.clientWriteKey[:], hkdfExpandLabel(csecret, "key", []byte{}, len(conn.clientWriteKey)))
25 | copy(conn.serverWriteKey[:], hkdfExpandLabel(ssecret, "key", []byte{}, len(conn.serverWriteKey)))
26 | copy(conn.clientWriteIV[:], hkdfExpandLabel(csecret, "iv", []byte{}, len(conn.clientWriteIV)))
27 | copy(conn.serverWriteIV[:], hkdfExpandLabel(ssecret, "iv", []byte{}, len(conn.serverWriteIV)))
28 | conn.serverSeq = 0
29 | conn.clientSeq = 0
30 | }
31 |
32 | func computeServerApplicationKeys(conn *TLSConn) {
33 | copy(conn.serverApplicationTrafficSecret[:], deriveSecret(conn.masterSecret[:], "s ap traffic", conn.transcript))
34 | copy(conn.clientApplicationTrafficSecret[:], deriveSecret(conn.masterSecret[:], "c ap traffic", conn.transcript))
35 | ssecret := conn.serverApplicationTrafficSecret[:]
36 | copy(conn.serverWriteKey[:], hkdfExpandLabel(ssecret, "key", []byte{}, len(conn.serverWriteKey)))
37 | copy(conn.serverWriteIV[:], hkdfExpandLabel(ssecret, "iv", []byte{}, len(conn.serverWriteIV)))
38 | conn.serverSeq = 0
39 | }
40 |
41 | func computeClientApplicationKeys(conn *TLSConn) {
42 | csecret := conn.clientApplicationTrafficSecret[:]
43 | copy(conn.clientWriteKey[:], hkdfExpandLabel(csecret, "key", []byte{}, len(conn.clientWriteKey)))
44 | copy(conn.clientWriteIV[:], hkdfExpandLabel(csecret, "iv", []byte{}, len(conn.clientWriteIV)))
45 | conn.clientSeq = 0
46 | }
47 |
48 | func hkdfExpandLabel(secret []byte, label string, context []byte, length int) []byte {
49 | hkdflabel := make([]byte, 0)
50 | hkdflabel = append(hkdflabel, byte(length>>8))
51 | hkdflabel = append(hkdflabel, byte(length))
52 | hkdflabel = append(hkdflabel, byte(len(label)+6))
53 | hkdflabel = append(hkdflabel, "tls13 "...)
54 | hkdflabel = append(hkdflabel, label...)
55 | hkdflabel = append(hkdflabel, byte(len(context)))
56 | hkdflabel = append(hkdflabel, context...)
57 | return hkdf.Expand(sha256.New(), secret, hkdflabel, length)
58 | }
59 |
60 | func deriveSecret(secret []byte, label string, messages []byte) []byte {
61 | s := sha256.New()
62 | s.Add(messages)
63 | sum := s.Sum()
64 | return hkdfExpandLabel(secret, label, sum, len(sum))
65 | }
66 |
--------------------------------------------------------------------------------
/tls/clienthello.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "crypto/rand"
5 | "github.com/syncsynchalt/tincan-tls/algo/curve25519"
6 | )
7 |
8 | func makeClientHello(conn *TLSConn, hostname string) ([]byte, error) {
9 | b := make([]byte, 0)
10 |
11 | // legacy_version
12 | b = append(b, "\x03\x03"...)
13 |
14 | // random
15 | _, err := rand.Read(conn.clientRandom[:])
16 | if err != nil {
17 | return nil, err
18 | }
19 | b = append(b, conn.clientRandom[:]...)
20 |
21 | // legacy_session_id
22 | b = append(b, 0x00)
23 |
24 | // cipher suites
25 | b = appendLen16(b, 2)
26 | b = append(b, kTLS_AES_128_GCM_SHA256...)
27 |
28 | // legacy_compression_methods
29 | b = append(b, 0x01)
30 | b = append(b, 0x00)
31 |
32 | // extensions
33 | exts := make([]byte, 0)
34 |
35 | // extension - supported versions
36 | exts = append(exts, to16(kEXT_SUPPORTED_VERSIONS)...)
37 | exts = appendLen16(exts, 3)
38 | exts = appendLen8(exts, 2)
39 | exts = append(exts, kTLS_VERSION_13...)
40 |
41 | // extension - supported groups
42 | exts = append(exts, to16(kEXT_SUPPORTED_GROUPS)...)
43 | exts = appendLen16(exts, 4)
44 | exts = appendLen16(exts, 2)
45 | exts = append(exts, kEXT_SUPPORTED_GROUPS_X25519...)
46 |
47 | // extension - key share
48 | priv, pub, err := curve25519.KeyPair()
49 | if err != nil {
50 | return nil, err
51 | }
52 | copy(conn.clientPrivKey[:], priv[:])
53 | copy(conn.clientPubKey[:], pub[:])
54 | exts = append(exts, to16(kEXT_KEY_SHARE)...)
55 | exts = appendLen16(exts, len(conn.clientPubKey)+2+2+2)
56 | exts = appendLen16(exts, len(conn.clientPubKey)+2+2)
57 | exts = append(exts, kEXT_SUPPORTED_GROUPS_X25519...)
58 | exts = appendLen16(exts, len(conn.clientPubKey))
59 | exts = append(exts, conn.clientPubKey[:]...)
60 |
61 | // extension - server name
62 | exts = append(exts, to16(kEXT_SERVER_NAME)...)
63 | exts = appendLen16(exts, len(hostname)+5)
64 | exts = appendLen16(exts, len(hostname)+3)
65 | exts = append(exts, kEXT_SERVER_NAME_HOST)
66 | exts = appendLen16(exts, len(hostname))
67 | exts = append(exts, hostname...)
68 |
69 | // extension - signature algorithms
70 | exts = append(exts, to16(kEXT_SIGNATURE_ALGORITHMS)...)
71 | exts = appendLen16(exts, 8)
72 | exts = appendLen16(exts, 6)
73 | // we're not going to check the signature anyway, so advertise all the requireds
74 | exts = append(exts, kTLS_RSA_PKCS1_SHA256...)
75 | exts = append(exts, kTLS_ECDSA_SECP256R1_SHA256...)
76 | exts = append(exts, kTLS_RSA_PSS_RSAE_SHA256...)
77 |
78 | // append extensions to our handshake
79 | b = appendLen16(b, len(exts))
80 | b = append(b, exts...)
81 |
82 | // wrap as handshake type: client_hello
83 | hs := make([]byte, 0)
84 | hs = append(hs, kHS_TYPE_CLIENT_HELLO)
85 | hs = appendLen24(hs, len(b))
86 | hs = append(hs, b...)
87 |
88 | // wrap as record type: handshake
89 | rec := make([]byte, 0)
90 | rec = append(rec, kREC_TYPE_HANDSHAKE)
91 | rec = append(rec, kTLS_VERSION_12...)
92 | rec = appendLen16(rec, len(hs))
93 | rec = append(rec, hs...)
94 |
95 | return rec, nil
96 | }
97 |
98 | func appendLen8(b []byte, len int) []byte {
99 | return append(b, byte(len))
100 | }
101 |
102 | func appendLen16(b []byte, len int) []byte {
103 | b = append(b, byte(len>>8))
104 | return append(b, byte(len))
105 | }
106 |
107 | func appendLen24(b []byte, len int) []byte {
108 | b = append(b, byte(len>>16))
109 | b = append(b, byte(len>>8))
110 | return append(b, byte(len))
111 | }
112 |
113 | func to16(num int) []byte {
114 | return []byte{byte(num << 8), byte(num)}
115 | }
116 |
--------------------------------------------------------------------------------
/tls/computefinished_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | // https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-07
8 | func TestComputeFinished(t *testing.T) {
9 | conn := &TLSConn{}
10 | recs := generateTestRecords()
11 | conn.addToTranscript(recs["client_hello"])
12 | conn.addToTranscript(recs["server_hello"])
13 |
14 | clientPriv := hexBytes(`49 af 42 ba 7f 79 94 85 2d 71 3e f2 78
15 | 4b cb ca a7 91 1d e2 6a dc 56 42 cb 63 45 40 e7 ea 50 05`)
16 | serverPub := hexBytes(`c9 82 88 76 11 20 95 fe 66 76 2b db f7 c6
17 | 72 e1 56 d6 cc 25 3b 83 3d f1 dd 69 b1 b0 4e 75 1f 0f`)
18 | copy(conn.clientPrivKey[:], clientPriv)
19 | copy(conn.serverPubKey[:], serverPub)
20 |
21 | computeHandshakeKeys(conn)
22 |
23 | conn.addToTranscript(recs["server_encrypted_extensions"])
24 | conn.addToTranscript(recs["server_certificate"])
25 | conn.addToTranscript(recs["server_certificate_verify"])
26 | conn.addToTranscript(recs["server_finished"])
27 |
28 | expected := hexBytes(`9b 9b 14 1d 90 63 37 fb d2 cb dc e7 1d f4
29 | de da 4a b4 2c 30 95 72 cb 7f ff ee 54 54 b7 8f 07 18`)
30 | calculated := computeServerFinished(conn)
31 | equals(t, expected, calculated)
32 | }
33 |
34 | func TestIllustratedFinished(t *testing.T) {
35 | conn := &TLSConn{}
36 | clientHello := hexBytes(`010000c20303000102030405060708090a0b0c0d0e0f101112
37 | 131415161718191a1b1c1d1e1f20e0e1e2e3e4e5e6e7e8e9eaebecedeeef
38 | f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff0006130113021303010000730000
39 | 001800160000136578616d706c652e756c666865696d2e6e6574000a0004
40 | 0002001d000d001400120403080404010503080505010806060102010033
41 | 00260024001d0020358072d6365880d1aeea329adf9121383851ed21a28e
42 | 3b75e965d0d2cd166254002d00020101002b0003020304`)
43 | serverHello := hexBytes(`020000760303707172737475767778797a7b7c7d7e7f808182
44 | 838485868788898a8b8c8d8e8f20e0e1e2e3e4e5e6e7e8e9eaebecedeeef
45 | f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff130100002e00330024001d00209f
46 | d7ad6dcff4298dd3f96d5b1b2af910a0535b1488d7f8fabb349a982880b6
47 | 15002b00020304`)
48 | conn.addToTranscript(clientHello)
49 | conn.addToTranscript(serverHello)
50 |
51 | clientPriv := hexBytes(`202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f`)
52 | serverPub := hexBytes(`9fd7ad6dcff4298dd3f96d5b1b2af910a0535b1488d7f8fabb349a982880b615`)
53 | copy(conn.clientPrivKey[:], clientPriv)
54 | copy(conn.serverPubKey[:], serverPub)
55 |
56 | computeHandshakeKeys(conn)
57 |
58 | conn.addToTranscript(hexBytes(`080000020000`))
59 | conn.addToTranscript(hexBytes(`0b00032e0000032a0003253082032130820209a0030201020208155a92adc2048f90300d06092a864886f70d01010b05003022310b300906035504061302555331133011060355040a130a4578616d706c65204341301e170d3138313030353031333831375a170d3139313030353031333831375a302b310b3009060355040613025553311c301a060355040313136578616d706c652e756c666865696d2e6e657430820122300d06092a864886f70d01010105000382010f003082010a0282010100c4803606bae7476b089404eca7b691043ff792bc19eefb7d74d7a80d001e7b4b3a4ae60fe8c071fc73e7024c0dbcf4bdd11d396bba70464a13e94af83df3e10959547bc955fb412da3765211e1f3dc776caa53376eca3aecbec3aab73b31d56cb6529c8098bcc9e02818e20bf7f8a03afd1704509ece79bd9f39f1ea69ec47972e830fb5ca95de95a1e60422d5eebe527954a1e7bf8a86f6466d0d9f16951a4cf7a04692595c1352f2549e5afb4ebfd77a37950144e4c026874c653e407d7d23074401f484ffd08f7a1fa05210d1f4f0d5ce79702932e2cabe701fdfad6b4bb71101f44bad666a11130fe2ee829e4d029dc91cdd6716dbb9061886edc1ba94210203010001a3523050300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030206082b06010505070301301f0603551d23041830168014894fde5bcc69e252cf3ea300dfb197b81de1c146300d06092a864886f70d01010b05000382010100591645a69a2e3779e4f6dd271aba1c0bfd6cd75599b5e7c36e533eff3659084324c9e7a504079d39e0d42987ffe3ebdd09c1cf1d914455870b571dd19bdf1d24f8bb9a11fe80fd592ba0398cde11e2651e618ce598fa96e5372eef3d248afde17463ebbfabb8e4d1ab502a54ec0064e92f7819660d3f27cf209e667fce5ae2e4ac99c7c93818f8b2510722dfed97f32e3e9349d4c66c9ea6396d744462a06b42c6d5ba688eac3a017bddfc8e2cfcad27cb69d3ccdca280414465d3ae348ce0f34ab2fb9c618371312b191041641c237f11a5d65c844f0404849938712b959ed685bc5c5dd645ed19909473402926dcb40e3469a15941e8e2cca84bb6084636a00000`))
60 | conn.addToTranscript(hexBytes(`0f000104080401002cf8ece7242804934b58ef48794c252bd34ad10aedfff930ca05a3169a5917668f399d43fcdbaf2b1c174d52d725174db9c754c79b63303be72de1837f682f6a94d355de74c3d04d6d612414c9b5ec285761271c68f5ce66b7c2fb6536199826fc41fe6123fc8006b425fd4b03a3421e91fb4b63f7a314e19517b7f17456f56667b5ba81d759d35d21f0ed7614a89899979e992f37abd7f2250c7ddd453bf812b6fe99ff18aaac8680785532d7cd27fded167fc89abd44ece78d1a69ec71370f0a32b0b97a6c224ee9d6a5eb263651421dbddd5391c85b3e9b664235797c0c31820e3e675aa2469a98287c5e4fcd80bed5547aaf8a80b80cfc11dba1b43a4ac2`))
61 | conn.addToTranscript(hexBytes(`14000020a2b22c83f1b01637d57bfa853d61a27057fddeebf975ec0367b93682c80eda14`))
62 |
63 | expected := hexBytes(`0db5e06f69d73436d047561acd8f9f60a6fe93e7ec6f6125faa1598fd28170ec`)
64 |
65 | _ = computeServerFinished(conn)
66 | calculated := computeClientFinished(conn)
67 | equals(t, expected, calculated)
68 | }
69 |
--------------------------------------------------------------------------------
/algo/curve25519/coord.go:
--------------------------------------------------------------------------------
1 | package curve25519
2 |
3 | // this package implements 256-bit math with a modulus of 2^255-19
4 |
5 | // little-endian x-value on the 25519 curve
6 | type coord [9]uint64
7 |
8 | var coordModulus = coord{
9 | 0xFFFFFFFFFFFFFFED, 0xFFFFFFFFFFFFFFFF,
10 | 0xFFFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF,
11 | }
12 |
13 | func newCoord(num uint64) coord {
14 | return coord{num}
15 | }
16 |
17 | func bytesToCoord(b [32]byte) coord {
18 | c := coord{}
19 | for i := 0; i < 4; i++ {
20 | for j := 0; j < 8; j++ {
21 | c[i] |= uint64(b[i*8+j]) << uint(j*8)
22 | }
23 | }
24 | return c
25 | }
26 |
27 | func (c coord) toBytes() [32]byte {
28 | var b [32]byte
29 | for i := 0; i < 4; i++ {
30 | for j := 0; j < 8; j++ {
31 | b[i*8+j] = byte(c[i] >> uint(j*8))
32 | }
33 | }
34 | return b
35 | }
36 |
37 | func (c coord) toHex() string {
38 | var hexstring = "0123456789abcdef"
39 |
40 | i := len(c) - 1
41 | for i > 0 && c[i] == 0 {
42 | i--
43 | }
44 |
45 | s := make([]byte, 0, 20)
46 | s = append(s, "0x"...)
47 |
48 | first := true
49 | for i >= 0 {
50 | if !first || c[i]&0xFFFFFFFF00000000 != 0 {
51 | for sh := 0; sh < 8; sh++ {
52 | ind := c[i] >> uint(60-4*sh) & 0xF
53 | s = append(s, hexstring[ind])
54 | }
55 | s = append(s, '_')
56 | }
57 | first = false
58 | for sh := 0; sh < 8; sh++ {
59 | ind := c[i] >> uint(28-4*sh) & 0xF
60 | s = append(s, hexstring[ind])
61 | }
62 | s = append(s, '_')
63 | i--
64 | }
65 | return string(s[:len(s)-1])
66 | }
67 |
68 | func (c *coord) copy() coord {
69 | c2 := coord{}
70 | copy(c2[:], c[:])
71 | return c2
72 | }
73 |
74 | func (c coord) reduce() coord {
75 | discard := coord{}
76 | // negative -> positive, not time safe
77 | for c[len(c)-1]&8000000000000000 != 0 {
78 | c = c.add(coordModulus)
79 | }
80 | window := len(c)*64 - 256
81 | mod := coordModulus.rotl(uint(window))
82 | for i := 0; i < window+1; i++ {
83 | x := c.sub(mod)
84 | if c.compare(mod) >= 0 {
85 | copy(c[:], x[:])
86 | } else {
87 | copy(discard[:], x[:])
88 | }
89 | mod = mod.rotr(1)
90 | }
91 | return c
92 | }
93 |
94 | func (a *coord) add(b coord) coord {
95 | var c coord
96 | var carry uint64
97 | for i := range a {
98 | c[i] = a[i] + b[i] + carry
99 | x1 := a[i] == 0xFFFFFFFFFFFFFFFF && (carry != 0)
100 | x2 := b[i] == 0xFFFFFFFFFFFFFFFF && (carry != 0)
101 | x3 := a[i] > c[i]
102 | x4 := b[i] > c[i]
103 | carry = 0
104 | if x1 {
105 | carry = 1
106 | }
107 | if x2 {
108 | carry = 1
109 | }
110 | if x3 {
111 | carry = 1
112 | }
113 | if x4 {
114 | carry = 1
115 | }
116 | }
117 | return c
118 | }
119 |
120 | func (a *coord) sub(b coord) coord {
121 | var c coord
122 | var carry uint64
123 | for i := range a {
124 | c[i] = a[i] - b[i] - carry
125 | x1 := b[i] > a[i]
126 | x2 := b[i] == 0xFFFFFFFFFFFFFFFF && (carry != 0)
127 | x3 := b[i]+carry > a[i]
128 | carry = 0
129 | if x1 {
130 | carry = 1
131 | }
132 | if x2 {
133 | carry = 1
134 | }
135 | if x3 {
136 | carry = 1
137 | }
138 | }
139 | return c
140 | }
141 |
142 | func (a *coord) compare(b coord) int {
143 | for i := len(a) - 1; i >= 0; i-- {
144 | if a[i] != b[i] {
145 | if a[i] > b[i] {
146 | return +1
147 | } else {
148 | return -1
149 | }
150 | }
151 | }
152 | return 0
153 | }
154 |
155 | func (c coord) rotl(num uint) coord {
156 | for num >= 64 {
157 | for i := len(c) - 1; i > 0; i-- {
158 | c[i] = c[i-1]
159 | }
160 | c[0] = 0
161 | num -= 64
162 | }
163 |
164 | carry := uint64(0)
165 | for i := 0; i < len(c)-1; i++ {
166 | newcarry := c[i] >> (64 - num)
167 | c[i] <<= num
168 | c[i] |= carry
169 | carry = newcarry
170 | }
171 | return c
172 | }
173 |
174 | func (c coord) rotr(num uint) coord {
175 | for num >= 64 {
176 | for i := 0; i < len(c)-2; i++ {
177 | c[i] = c[i+1]
178 | }
179 | c[len(c)-1] = 0
180 | num -= 64
181 | }
182 |
183 | carry := uint64(0)
184 | for i := len(c) - 1; i >= 0; i-- {
185 | newcarry := c[i] << (64 - num)
186 | c[i] >>= num
187 | c[i] |= carry
188 | carry = newcarry
189 | }
190 | return c
191 | }
192 |
193 | func (a coord) mult(b coord) coord {
194 | var sum coord
195 | for n := 0; n < len(a)*64; n++ {
196 | x := sum.add(b)
197 | if a[0]&1 == 1 {
198 | sum = x
199 | } else {
200 | _ = x
201 | }
202 | a = a.rotr(1)
203 | b = b.rotl(1)
204 | }
205 | return sum
206 | }
207 |
208 | func (a coord) nbit(t uint) int {
209 | i := 0
210 | for t >= 64 {
211 | i++
212 | t -= 64
213 | }
214 | return int(a[i] >> t & 1)
215 | }
216 |
217 | func (base coord) exp(exponent coord) coord {
218 | // from https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
219 |
220 | result := newCoord(1)
221 | zero := newCoord(0)
222 | base = base.reduce()
223 | for exponent.compare(zero) > 0 {
224 | if exponent[0]&1 != 0 {
225 | result = result.mult(base).reduce()
226 | }
227 | exponent = exponent.rotr(1)
228 | base = base.mult(base).reduce()
229 | }
230 |
231 | return result
232 | }
233 |
--------------------------------------------------------------------------------
/tls/serverhandshake.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | func handleHandshake(conn *TLSConn, payload []byte) action {
4 | acts := action_none
5 | if len(payload) < 4 {
6 | panic("short handshake")
7 | }
8 | typ := int(payload[0])
9 | payload, rest := readVec(24, payload[1:])
10 | if len(rest) != 0 {
11 | panic("long handshake")
12 | }
13 | switch byte(typ) {
14 | case kHS_TYPE_SERVER_HELLO:
15 | acts = handleServerHello(conn, payload)
16 | computeHandshakeKeys(conn)
17 | case kHS_TYPE_ENCRYPTED_EXTENSIONS:
18 | acts = handleEncryptedExtensions(conn, payload)
19 | case kHS_TYPE_CERTIFICATE:
20 | acts = handleServerCertificate(conn, payload)
21 | case kHS_TYPE_CERTIFICATE_VERIFY:
22 | acts = handleServerCertificateVerify(conn, payload)
23 | case kHS_TYPE_FINISHED:
24 | acts = handleServerFinished(conn, payload)
25 | case kHS_TYPE_NEW_SESSION_TICKET:
26 | acts = handleNewSessionTicket(conn, payload)
27 | default:
28 | panic("handshake type not handled")
29 | }
30 | return acts
31 | }
32 |
33 | func readNum(bits int, b []byte) uint {
34 | x := uint(0)
35 | for i := 0; i < bits; i += 8 {
36 | x <<= 8
37 | x |= uint(b[i/8])
38 | }
39 | return x
40 | }
41 |
42 | func readVec(lenBits int, payload []byte) (vec []byte, rest []byte) {
43 | len := readNum(lenBits, payload)
44 | return payload[uint(lenBits/8) : uint(lenBits/8)+len], payload[uint(lenBits/8)+len:]
45 | }
46 |
47 | func match(c []byte, payload []byte) bool {
48 | for i := range c {
49 | if c[i] != payload[i] {
50 | return false
51 | }
52 | }
53 | return true
54 | }
55 |
56 | func handleServerHello(conn *TLSConn, payload []byte) action {
57 | // version
58 | payload = payload[2:]
59 |
60 | // server random
61 | if match(kHS_HELLO_RETRY_REQUEST, payload) {
62 | panic("server sent HelloRetryRequest")
63 | }
64 | copy(conn.serverRandom[:], payload[:32])
65 | payload = payload[32:]
66 |
67 | // session id
68 | _, payload = readVec(8, payload)
69 |
70 | // cipher suite
71 | if !match(kTLS_AES_128_GCM_SHA256, payload) {
72 | panic("wrong cipher")
73 | }
74 | payload = payload[2:]
75 |
76 | // compression method
77 | if payload[0] != 0x00 {
78 | panic("wrong compression method")
79 | }
80 | payload = payload[1:]
81 |
82 | // extensions
83 | exts, payload := readVec(16, payload)
84 | parseExtensions(conn, exts)
85 |
86 | if len(payload) != 0 {
87 | panic("unexpected suffix")
88 | }
89 | return action_reset_sequence
90 | }
91 |
92 | func parseExtensions(conn *TLSConn, exts []byte) {
93 | for len(exts) > 0 {
94 | typ := int(exts[0])<<8 | int(exts[1])
95 | var ext []byte
96 | ext, exts = readVec(16, exts[2:])
97 | switch typ {
98 | case kEXT_SUPPORTED_GROUPS:
99 | parseExtSupportedGroups(conn, ext)
100 | case kEXT_KEY_SHARE:
101 | parseExtKeyShare(conn, ext)
102 | case kEXT_SUPPORTED_VERSIONS:
103 | parseExtSupportedVersions(conn, ext)
104 | case kEXT_SERVER_NAME:
105 | parseExtServerName(conn, ext)
106 | default:
107 | panic("unknown ext type")
108 | }
109 | }
110 | }
111 |
112 | func parseExtKeyShare(conn *TLSConn, payload []byte) {
113 | if !match(kEXT_SUPPORTED_GROUPS_X25519, payload) {
114 | panic("bad group in key share")
115 | }
116 | payload = payload[2:]
117 | pubkey, payload := readVec(16, payload)
118 | if len(pubkey) != 32 || len(payload) != 0 {
119 | panic("bad key share length")
120 | }
121 | copy(conn.serverPubKey[:], pubkey)
122 | }
123 |
124 | func parseExtSupportedVersions(conn *TLSConn, payload []byte) {
125 | if !match(kTLS_VERSION_13, payload) {
126 | panic("bad supported version")
127 | }
128 | }
129 |
130 | func parseExtSupportedGroups(conn *TLSConn, payload []byte) {
131 | // the server advises its preferred groups, for use in subsequent connections
132 | }
133 |
134 | func parseExtServerName(conn *TLSConn, payload []byte) {
135 | // not sure why tls13.crypto.mozilla.org sends this (empty) extension
136 | }
137 |
138 | func handleEncryptedExtensions(conn *TLSConn, payload []byte) action {
139 | exts, _ := readVec(16, payload)
140 | parseExtensions(conn, exts)
141 | return action_none
142 | }
143 |
144 | func handleServerCertificate(conn *TLSConn, payload []byte) action {
145 | // x509 authentication is outside the spec of this barest-minimal connection
146 | return action_none
147 | }
148 |
149 | func handleServerCertificateVerify(conn *TLSConn, payload []byte) action {
150 | // x509 authentication is outside the spec of this barest-minimal connection
151 | return action_none
152 | }
153 |
154 | func handleNewSessionTicket(conn *TLSConn, payload []byte) action {
155 | // ignored as we don't support session resume
156 | return action_none
157 | }
158 |
159 | func handleServerFinished(conn *TLSConn, payload []byte) action {
160 | expectedResult := computeServerFinished(conn)
161 | if len(expectedResult) != len(payload) {
162 | panic("server finished bytes differ")
163 | }
164 | for i := range payload {
165 | if expectedResult[i] != payload[i] {
166 | panic("server finished unexpected result")
167 | }
168 | }
169 | computeServerApplicationKeys(conn)
170 | return action_send_finished | action_reset_sequence
171 | }
172 |
--------------------------------------------------------------------------------
/algo/sha256/sha256.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on RFC 6234
5 |
6 | package sha256
7 |
8 | var k = [...]uint32{
9 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
10 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
11 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
12 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
13 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
14 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
15 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
16 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
17 | }
18 | var initialState = [...]uint32{
19 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
20 | 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
21 | }
22 |
23 | type Sha256 struct {
24 | tmp [64]byte
25 | unprocessed [64]byte
26 | unprocessedLen int
27 | state [8]uint32
28 | addBits uint64
29 | }
30 |
31 | func New() *Sha256 {
32 | s := Sha256{}
33 | s.Reset()
34 | return &s
35 | }
36 |
37 | func (s *Sha256) Reset() {
38 | s.unprocessedLen = 0
39 | copy(s.state[:], initialState[:])
40 | s.addBits = 0
41 | }
42 |
43 | func (s *Sha256) BlockSize() int {
44 | return 64
45 | }
46 |
47 | func (s *Sha256) HashLen() int {
48 | return 32
49 | }
50 |
51 | func (s *Sha256) Add(in []byte) {
52 | s.addBits += uint64(8 * len(in))
53 | var b []byte
54 | for len(in)+s.unprocessedLen >= 64 {
55 | if s.unprocessedLen == 0 {
56 | b = in[:64]
57 | in = in[64:]
58 | } else {
59 | copy(s.tmp[:], s.unprocessed[:s.unprocessedLen])
60 | copy(s.tmp[s.unprocessedLen:], in)
61 | b = s.tmp[:]
62 | in = in[64-s.unprocessedLen:]
63 | s.unprocessedLen = 0
64 | }
65 |
66 | s.chomp(b)
67 | }
68 | if len(in) > 0 {
69 | copy(s.unprocessed[s.unprocessedLen:], in)
70 | s.unprocessedLen += len(in)
71 | }
72 | }
73 |
74 | func (s *Sha256) chomp(block []byte) {
75 | var w [64]uint32
76 | for t := 0; t < 16; t++ {
77 | w[t] = uint32(
78 | uint32(block[t*4+0])<<24 |
79 | uint32(block[t*4+1])<<16 |
80 | uint32(block[t*4+2])<<8 |
81 | uint32(block[t*4+3])<<0)
82 | }
83 | for t := 16; t < 64; t++ {
84 | w[t] = ssig1(w[t-2]) + w[t-7] + ssig0(w[t-15]) + w[t-16]
85 | }
86 |
87 | a, b, c, d, e, f, g, h := s.state[0], s.state[1], s.state[2], s.state[3],
88 | s.state[4], s.state[5], s.state[6], s.state[7]
89 | var t1, t2 uint32
90 |
91 | for i := 0; i < 64; i++ {
92 | t1 = h + bsig1(e) + ch(e, f, g) + k[i] + w[i]
93 | t2 = bsig0(a) + maj(a, b, c)
94 | h = g
95 | g = f
96 | f = e
97 | e = d + t1
98 | d = c
99 | c = b
100 | b = a
101 | a = t1 + t2
102 | }
103 | s.state[0] = a + s.state[0]
104 | s.state[1] = b + s.state[1]
105 | s.state[2] = c + s.state[2]
106 | s.state[3] = d + s.state[3]
107 | s.state[4] = e + s.state[4]
108 | s.state[5] = f + s.state[5]
109 | s.state[6] = g + s.state[6]
110 | s.state[7] = h + s.state[7]
111 | }
112 |
113 | func ch(x, y, z uint32) uint32 {
114 | return (x & y) ^ (^x & z)
115 | }
116 |
117 | func maj(x, y, z uint32) uint32 {
118 | return (x & y) ^ (x & z) ^ (y & z)
119 | }
120 |
121 | func rotr(x uint32, n uint) uint32 {
122 | return (x >> n) | (x << (32 - n))
123 | }
124 |
125 | func rotl(x uint32, n uint) uint32 {
126 | return (x << n) | (x >> (32 - n))
127 | }
128 |
129 | func bsig0(x uint32) uint32 {
130 | return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22)
131 | }
132 |
133 | func bsig1(x uint32) uint32 {
134 | return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25)
135 | }
136 |
137 | func ssig0(x uint32) uint32 {
138 | return rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
139 | }
140 |
141 | func ssig1(x uint32) uint32 {
142 | return rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10)
143 | }
144 |
145 | func (s *Sha256) finalPad() {
146 | // assumes we'll never max out L to reach these bits, so we consume the whole byte
147 | s.unprocessed[s.unprocessedLen] = 0x80
148 | s.unprocessedLen++
149 | for s.unprocessedLen > 56 && s.unprocessedLen < 64 {
150 | s.unprocessed[s.unprocessedLen] = 0
151 | s.unprocessedLen++
152 | }
153 | if s.unprocessedLen >= 64 {
154 | s.chomp(s.unprocessed[:])
155 | s.unprocessedLen = 0
156 | }
157 | for s.unprocessedLen < 56 {
158 | s.unprocessed[s.unprocessedLen] = 0
159 | s.unprocessedLen++
160 | }
161 | s.unprocessed[56] = byte(s.addBits >> 56)
162 | s.unprocessed[57] = byte(s.addBits >> 48)
163 | s.unprocessed[58] = byte(s.addBits >> 40)
164 | s.unprocessed[59] = byte(s.addBits >> 32)
165 | s.unprocessed[60] = byte(s.addBits >> 24)
166 | s.unprocessed[61] = byte(s.addBits >> 16)
167 | s.unprocessed[62] = byte(s.addBits >> 8)
168 | s.unprocessed[63] = byte(s.addBits >> 0)
169 | s.chomp(s.unprocessed[:])
170 | s.unprocessedLen = 0
171 | }
172 |
173 | func (s *Sha256) Sum() []byte {
174 | result := make([]byte, 32)
175 | s.finalPad()
176 | for i := 0; i < 8; i++ {
177 | result[i*4+0] = byte(s.state[i] >> 24)
178 | result[i*4+1] = byte(s.state[i] >> 16)
179 | result[i*4+2] = byte(s.state[i] >> 8)
180 | result[i*4+3] = byte(s.state[i] >> 0)
181 | }
182 | return result
183 | }
184 |
185 | func SumData(b []byte) []byte {
186 | s := New()
187 | s.Add(b)
188 | return s.Sum()
189 | }
190 |
--------------------------------------------------------------------------------
/algo/aes/aes.go:
--------------------------------------------------------------------------------
1 | // This is a toy implementation and is full of side channels and other defects.
2 | // DO NOT use this in a real cryptographic application.
3 |
4 | // based on FIPS 197 (https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf)
5 |
6 | package aes
7 |
8 | // aes128 values, we've only implemented it for now
9 | const (
10 | nk = 4
11 | nb = 4
12 | nr = 10
13 | )
14 |
15 | var sbox [256]byte = generateSBox()
16 |
17 | type AES struct {
18 | w []uint32
19 | }
20 |
21 | func New128(key []byte) *AES {
22 | a := AES{}
23 | a.w = keyExpansion(key)
24 | return &a
25 | }
26 |
27 | func (a *AES) BlockSize() int {
28 | return 4 * nb
29 | }
30 |
31 | func (a *AES) KeySize() int {
32 | return 4 * nk
33 | }
34 |
35 | func (a *AES) Encrypt(in, out []byte) {
36 | cipher(in, out, a.w)
37 | }
38 |
39 | // returns a 16x16 substitution box
40 | func generateSBox() [256]byte {
41 | inverses := make([]byte, 256)
42 | for i := range inverses {
43 | inverses[i] = findInverse(byte(i))
44 | }
45 | var box [256]byte
46 | for i := range box {
47 | box[i] = sboxAffine(inverses[i])
48 | }
49 | return box
50 | }
51 |
52 | func findInverse(b byte) byte {
53 | // find the multiplicative inverse in GF(2^8) for reducing polynomial of x^8 + x^4 + x^3 + x + 1 (100011011b)
54 | // in other words, b * bi == 1
55 | // uses brute-force method to find inverses (slow)
56 | if b == 0 {
57 | return 0
58 | }
59 | for i := 0; i < 256; i++ {
60 | if rjmult(byte(i), b) == 1 {
61 | return byte(i)
62 | }
63 | }
64 | panic("no inverse found, can't happen")
65 | }
66 |
67 | func rjmult(a, b byte) byte {
68 | result := uint(0)
69 |
70 | // polynomial expansion of abit_i*x^i times bbit_i*x^i
71 | ascale := uint(0)
72 | for a != 0 {
73 | if a&1 == 1 {
74 | bscale := uint(0)
75 | bt := b
76 | for bt != 0 {
77 | if bt&1 == 1 {
78 | result ^= 1 << (ascale + bscale)
79 | }
80 | bt >>= 1
81 | bscale++
82 | }
83 | }
84 | a >>= 1
85 | ascale++
86 | }
87 |
88 | // mod x^8 + x^4 + x^3 + x + 1 (reduces result to 8 bits)
89 | for i := uint(15); i > 7; i-- {
90 | if result&(1<>24), 2)) << 24
125 | }
126 |
127 | var tmp uint32
128 | for i := nk; i < nb*(nr+1); i++ {
129 | tmp = w[i-1]
130 | if i%nk == 0 {
131 | tmp = subWord(rotWord(tmp)) ^ rcon[i/nk-1]
132 | } else if nk > 6 && i%nk == 4 {
133 | // not reached in AES-128
134 | tmp = subWord(tmp)
135 | }
136 | w[i] = w[i-nk] ^ tmp
137 | }
138 | return w
139 | }
140 |
141 | func subWord(w uint32) uint32 {
142 | return uint32(sbox[byte(w>>24)])<<24 | uint32(sbox[byte(w>>16)])<<16 |
143 | uint32(sbox[byte(w>>8)])<<8 | uint32(sbox[byte(w)])
144 | }
145 |
146 | func rotWord(w uint32) uint32 {
147 | return (w << 8) | (w >> 24)
148 | }
149 |
150 | // w is the output of keyExpansion()
151 | func cipher(in, out []byte, w []uint32) {
152 | if len(in) != 4*nb || len(in) != len(out) {
153 | panic("incorrect blocksize in cipher")
154 | }
155 |
156 | state := out
157 |
158 | copy(state, in)
159 | addRoundKey(state, w[:nb])
160 |
161 | for i := 1; i < nr; i++ {
162 | subBytes(state)
163 | shiftRows(state)
164 | mixColumns(state)
165 | addRoundKey(state, w[(i)*nb:(i+1)*nb])
166 | }
167 |
168 | subBytes(state)
169 | shiftRows(state)
170 | addRoundKey(state, w[nr*nb:(nr+1)*nb])
171 | }
172 |
173 | func subBytes(state []byte) {
174 | for i := range state {
175 | state[i] = sbox[state[i]]
176 | }
177 | }
178 |
179 | func addRoundKey(state []byte, w []uint32) {
180 | if len(state) != 4*len(w) {
181 | panic("mismatch in state and w")
182 | }
183 | for i := range w {
184 | state[i*4+0] ^= byte(w[i] >> 24)
185 | state[i*4+1] ^= byte(w[i] >> 16)
186 | state[i*4+2] ^= byte(w[i] >> 8)
187 | state[i*4+3] ^= byte(w[i])
188 | }
189 | }
190 |
191 | func shiftRows(state []byte) {
192 | roll := func(col int) {
193 | x := state[col]
194 | for i := 0; i < nb-1; i++ {
195 | state[col+4*i] = state[col+4*(i+1)]
196 | }
197 | state[col+4*(nb-1)] = x
198 | }
199 | for i := 1; i < nb; i++ {
200 | for j := 0; j < i; j++ {
201 | roll(i)
202 | }
203 | }
204 | }
205 |
206 | func mixColumns(state []byte) {
207 | mix := func(s []byte) {
208 | s0 := rjmult(2, s[0]) ^ rjmult(3, s[1]) ^ s[2] ^ s[3]
209 | s1 := s[0] ^ rjmult(2, s[1]) ^ rjmult(3, s[2]) ^ s[3]
210 | s2 := s[0] ^ s[1] ^ rjmult(2, s[2]) ^ rjmult(3, s[3])
211 | s3 := rjmult(3, s[0]) ^ s[1] ^ s[2] ^ rjmult(2, s[3])
212 | s[0], s[1], s[2], s[3] = s0, s1, s2, s3
213 | }
214 | mix(state[0:4])
215 | mix(state[4:8])
216 | mix(state[8:12])
217 | mix(state[12:16])
218 | }
219 |
--------------------------------------------------------------------------------
/algo/aes/aes_test.go:
--------------------------------------------------------------------------------
1 | package aes
2 |
3 | import (
4 | "testing"
5 |
6 | "encoding/hex"
7 | )
8 |
9 | func TestMult(t *testing.T) {
10 | equals(t, byte(0x01), rjmult(0x53, 0xca))
11 | equals(t, byte(0xc1), rjmult(0x57, 0x83))
12 | equals(t, byte(0x2), rjmult(0x01, 0x02))
13 | equals(t, byte(0x4), rjmult(0x02, 0x02))
14 | }
15 |
16 | func TestAllInverse(t *testing.T) {
17 | for i := 0; i < 256; i++ {
18 | t.Log("testing", i)
19 | j := findInverse(byte(i))
20 | t.Log("got", j)
21 | }
22 | }
23 |
24 | func TestSBoxAffine(t *testing.T) {
25 | equals(t, byte(0x63), sboxAffine(0x00))
26 | equals(t, byte(0x7c), sboxAffine(0x01))
27 | equals(t, byte(0x77), sboxAffine(0x8d))
28 | equals(t, byte(0x53), sboxAffine(0xed))
29 | }
30 |
31 | func TestSBox(t *testing.T) {
32 | sbox := generateSBox()
33 | t.Log("SBox:")
34 | for i := 0; i < 16; i++ {
35 | s := sbox[i*16 : (i+1)*16]
36 | t.Logf("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
37 | s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15])
38 | }
39 |
40 | xy := func(x, y int) byte {
41 | return sbox[y+16*x]
42 | }
43 | equals(t, byte(0x63), xy(0x0, 0x0))
44 | equals(t, byte(0x76), xy(0x0, 0xF))
45 | equals(t, byte(0x49), xy(0xA, 0x4))
46 | equals(t, byte(0x16), xy(0xF, 0xF))
47 |
48 | chk := make([]bool, 256)
49 | for i := range sbox {
50 | assert(t, chk[sbox[i]] == false, "bit %d is already set", i)
51 | chk[sbox[i]] = true
52 | }
53 | }
54 |
55 | func TestSubWord(t *testing.T) {
56 | equals(t, uint32(0x777d3696), subWord(0x02132435))
57 | }
58 |
59 | func TestRotWord(t *testing.T) {
60 | equals(t, uint32(0x02030401), rotWord(0x01020304))
61 | equals(t, uint32(0xfdfefffc), rotWord(0xfcfdfeff))
62 | }
63 |
64 | func TestKeyExpansion(t *testing.T) {
65 | key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
66 | w := keyExpansion(key)
67 | t.Log("Key Expansion:")
68 | for i := 0; i < len(w)/4; i++ {
69 | z := w[i*4 : (i+1)*4]
70 | t.Logf("%08x %08x %08x %08x\n", z[0], z[1], z[2], z[3])
71 | }
72 | equals(t, len(w), 44)
73 | equals(t, uint32(0x2b7e1516), w[0])
74 | equals(t, uint32(0x7a96b943), w[9])
75 | equals(t, uint32(0xb6630ca6), w[43])
76 | }
77 |
78 | func TestSubBytes(t *testing.T) {
79 | b, _ := hex.DecodeString("01102144")
80 | e, _ := hex.DecodeString("7ccafd1b")
81 | subBytes(b)
82 | equals(t, e, b)
83 |
84 | b, _ = hex.DecodeString("00102030405060708090a0b0c0d0e0f0")
85 | e, _ = hex.DecodeString("63cab7040953d051cd60e0e7ba70e18c")
86 | subBytes(b)
87 | equals(t, e, b)
88 | }
89 |
90 | func TestAddRoundKey(t *testing.T) {
91 | b, _ := hex.DecodeString("013c7dff020405089799abc066770110")
92 | w := []uint32{0x2000000, 0xffffffff, 0x23456789, 0xabcdef01}
93 | e, _ := hex.DecodeString("033c7dfffdfbfaf7b4dccc49cdbaee11")
94 | addRoundKey(b, w)
95 | equals(t, e, b)
96 |
97 | b, _ = hex.DecodeString("00112233445566778899aabbccddeeff")
98 | w = []uint32{0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f}
99 | e, _ = hex.DecodeString("00102030405060708090a0b0c0d0e0f0")
100 | addRoundKey(b, w)
101 | equals(t, e, b)
102 | }
103 |
104 | func TestShiftRows(t *testing.T) {
105 | // 63cab704 0953d051 cd60e0e7 ba70e18c ->
106 | // 6353e08c 0960e104 cd70b751 bacad0e7
107 | b, _ := hex.DecodeString("63cab7040953d051cd60e0e7ba70e18c")
108 | e, _ := hex.DecodeString("6353e08c0960e104cd70b751bacad0e7")
109 | shiftRows(b)
110 | equals(t, e, b)
111 | }
112 |
113 | func TestMixColumns(t *testing.T) {
114 | b, _ := hex.DecodeString("6353e08c0960e104cd70b751bacad0e7")
115 | e, _ := hex.DecodeString("5f72641557f5bc92f7be3b291db9f91a")
116 | mixColumns(b)
117 | equals(t, e, b)
118 |
119 | b, _ = hex.DecodeString("a7be1a6997ad739bd8c9ca451f618b61")
120 | e, _ = hex.DecodeString("ff87968431d86a51645151fa773ad009")
121 | mixColumns(b)
122 | equals(t, e, b)
123 |
124 | b, _ = hex.DecodeString("3bd92268fc74fb735767cbe0c0590e2d")
125 | e, _ = hex.DecodeString("4c9c1e66f771f0762c3f868e534df256")
126 | mixColumns(b)
127 | equals(t, e, b)
128 |
129 | b, _ = hex.DecodeString("2d6d7ef03f33e334093602dd5bfb12c7")
130 | e, _ = hex.DecodeString("6385b79ffc538df997be478e7547d691")
131 | mixColumns(b)
132 | equals(t, e, b)
133 |
134 | b, _ = hex.DecodeString("36339d50f9b539269f2c092dc4406d23")
135 | e, _ = hex.DecodeString("f4bcd45432e554d075f1d6c51dd03b3c")
136 | mixColumns(b)
137 | equals(t, e, b)
138 | }
139 |
140 | func TestCipher(t *testing.T) {
141 | key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
142 | in, _ := hex.DecodeString("3243f6a8885a308d313198a2e0370734")
143 | e, _ := hex.DecodeString("3925841d02dc09fbdc118597196a0b32")
144 | out := make([]byte, 16)
145 | w := keyExpansion(key)
146 | cipher(in, out, w)
147 | equals(t, e, out)
148 |
149 | // repeat to ensure everything's intact
150 | cipher(in, out, w)
151 | equals(t, e, out)
152 | }
153 |
154 | func TestCipherIndependent(t *testing.T) {
155 | key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f")
156 | in := []byte("abcdefghijklmnop")
157 | e, _ := hex.DecodeString("d25363fc721337648a68f34abef3b405")
158 |
159 | out := make([]byte, 16)
160 | w := keyExpansion(key)
161 | cipher(in, out, w)
162 | equals(t, e, out)
163 | }
164 |
165 | func TestInterface(t *testing.T) {
166 | key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f")
167 | e, _ := hex.DecodeString("d25363fc721337648a68f34abef3b405")
168 |
169 | a := New128(key)
170 | equals(t, 16, a.KeySize())
171 | equals(t, 16, a.BlockSize())
172 | out := make([]byte, a.BlockSize())
173 | a.Encrypt([]byte("abcdefghijklmnop"), out)
174 | equals(t, e, out)
175 |
176 | e, _ = hex.DecodeString("8bd658946c56fee7598ce6e41544b92b")
177 | a.Encrypt([]byte("qrstuvwxyz012345"), out)
178 | equals(t, e, out)
179 | }
180 |
181 | func TestFromCLI(t *testing.T) {
182 | key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f")
183 | e, _ := hex.DecodeString("e37cd363dd7c87a09aff0e3e60e09c82")
184 | in, _ := hex.DecodeString("01000000000000000000000000000000")
185 |
186 | a := New128(key)
187 | out := make([]byte, a.BlockSize())
188 | a.Encrypt(in, out)
189 | equals(t, e, out)
190 | }
191 |
--------------------------------------------------------------------------------
/tls/conncrypt_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | // https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-07
8 | func TestDecryptRecord(t *testing.T) {
9 | conn := &TLSConn{}
10 | SHKey := hexBytes(`3f ce 51 60 09 c2 17 27 d0 f2 e4 e8 6e e4 03 bc`)
11 | copy(conn.serverWriteKey[:], SHKey)
12 | SHIV := hexBytes(`5d 31 3e b2 67 12 76 ee 13 00 0b 30`)
13 | copy(conn.serverWriteIV[:], SHIV)
14 | conn.serverSeq = 0
15 |
16 | input := hexBytes(`17 03 03 02 a2 d1 ff 33 4a 56 f5 bf
17 | f6 59 4a 07 cc 87 b5 80 23 3f 50 0f 45 e4 89 e7 f3 3a f3 5e df
18 | 78 69 fc f4 0a a4 0a a2 b8 ea 73 f8 48 a7 ca 07 61 2e f9 f9 45
19 | cb 96 0b 40 68 90 51 23 ea 78 b1 11 b4 29 ba 91 91 cd 05 d2 a3
20 | 89 28 0f 52 61 34 aa dc 7f c7 8c 4b 72 9d f8 28 b5 ec f7 b1 3b
21 | d9 ae fb 0e 57 f2 71 58 5b 8e a9 bb 35 5c 7c 79 02 07 16 cf b9
22 | b1 18 3e f3 ab 20 e3 7d 57 a6 b9 d7 47 76 09 ae e6 e1 22 a4 cf
23 | 51 42 73 25 25 0c 7d 0e 50 92 89 44 4c 9b 3a 64 8f 1d 71 03 5d
24 | 2e d6 5b 0e 3c dd 0c ba e8 bf 2d 0b 22 78 12 cb b3 60 98 72 55
25 | cc 74 41 10 c4 53 ba a4 fc d6 10 92 8d 80 98 10 e4 b7 ed 1a 8f
26 | d9 91 f0 6a a6 24 82 04 79 7e 36 a6 a7 3b 70 a2 55 9c 09 ea d6
27 | 86 94 5b a2 46 ab 66 e5 ed d8 04 4b 4c 6d e3 fc f2 a8 94 41 ac
28 | 66 27 2f d8 fb 33 0e f8 19 05 79 b3 68 45 96 c9 60 bd 59 6e ea
29 | 52 0a 56 a8 d6 50 f5 63 aa d2 74 09 96 0d ca 63 d3 e6 88 61 1e
30 | a5 e2 2f 44 15 cf 95 38 d5 1a 20 0c 27 03 42 72 96 8a 26 4e d6
31 | 54 0c 84 83 8d 89 f7 2c 24 46 1a ad 6d 26 f5 9e ca ba 9a cb bb
32 | 31 7b 66 d9 02 f4 f2 92 a3 6a c1 b6 39 c6 37 ce 34 31 17 b6 59
33 | 62 22 45 31 7b 49 ee da 0c 62 58 f1 00 d7 d9 61 ff b1 38 64 7e
34 | 92 ea 33 0f ae ea 6d fa 31 c7 a8 4d c3 bd 7e 1b 7a 6c 71 78 af
35 | 36 87 90 18 e3 f2 52 10 7f 24 3d 24 3d c7 33 9d 56 84 c8 b0 37
36 | 8b f3 02 44 da 8c 87 c8 43 f5 e5 6e b4 c5 e8 28 0a 2b 48 05 2c
37 | f9 3b 16 49 9a 66 db 7c ca 71 e4 59 94 26 f7 d4 61 e6 6f 99 88
38 | 2b d8 9f c5 08 00 be cc a6 2d 6c 74 11 6d bd 29 72 fd a1 fa 80
39 | f8 5d f8 81 ed be 5a 37 66 89 36 b3 35 58 3b 59 91 86 dc 5c 69
40 | 18 a3 96 fa 48 a1 81 d6 b6 fa 4f 9d 62 d5 13 af bb 99 2f 2b 99
41 | 2f 67 f8 af e6 7f 76 91 3f a3 88 cb 56 30 c8 ca 01 e0 c6 5d 11
42 | c6 6a 1e 2a c4 c8 59 77 b7 c7 a6 99 9b bf 10 dc 35 ae 69 f5 51
43 | 56 14 63 6c 0b 9b 68 c1 9e d2 e3 1c 0b 3b 66 76 30 38 eb ba 42
44 | f3 b3 8e dc 03 99 f3 a9 f2 3f aa 63 97 8c 31 7f c9 fa 66 a7 3f
45 | 60 f0 50 4d e9 3b 5b 84 5e 27 55 92 c1 23 35 ee 34 0b bc 4f dd
46 | d5 02 78 40 16 e4 b3 be 7e f0 4d da 49 f4 b4 40 a3 0c b5 d2 af
47 | 93 98 28 fd 4a e3 79 4e 44 f9 4d f5 a6 31 ed e4 2c 17 19 bf da
48 | bf 02 53 fe 51 75 be 89 8e 75 0e dc 53 37 0d 2b`)
49 |
50 | expect := hexBytes(`08 00 00 24 00 22 00 0a 00 14 00 12 00 1d
51 | 00 17 00 18 00 19 01 00 01 01 01 02 01 03 01 04 00 1c 00 02 40
52 | 01 00 00 00 00 0b 00 01 b9 00 00 01 b5 00 01 b0 30 82 01 ac 30
53 | 82 01 15 a0 03 02 01 02 02 01 02 30 0d 06 09 2a 86 48 86 f7 0d
54 | 01 01 0b 05 00 30 0e 31 0c 30 0a 06 03 55 04 03 13 03 72 73 61
55 | 30 1e 17 0d 31 36 30 37 33 30 30 31 32 33 35 39 5a 17 0d 32 36
56 | 30 37 33 30 30 31 32 33 35 39 5a 30 0e 31 0c 30 0a 06 03 55 04
57 | 03 13 03 72 73 61 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01
58 | 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 b4 bb 49 8f 82 79 30
59 | 3d 98 08 36 39 9b 36 c6 98 8c 0c 68 de 55 e1 bd b8 26 d3 90 1a
60 | 24 61 ea fd 2d e4 9a 91 d0 15 ab bc 9a 95 13 7a ce 6c 1a f1 9e
61 | aa 6a f9 8c 7c ed 43 12 09 98 e1 87 a8 0e e0 cc b0 52 4b 1b 01
62 | 8c 3e 0b 63 26 4d 44 9a 6d 38 e2 2a 5f da 43 08 46 74 80 30 53
63 | 0e f0 46 1c 8c a9 d9 ef bf ae 8e a6 d1 d0 3e 2b d1 93 ef f0 ab
64 | 9a 80 02 c4 74 28 a6 d3 5a 8d 88 d7 9f 7f 1e 3f 02 03 01 00 01
65 | a3 1a 30 18 30 09 06 03 55 1d 13 04 02 30 00 30 0b 06 03 55 1d
66 | 0f 04 04 03 02 05 a0 30 0d 06 09 2a 86 48 86 f7 0d 01 01 0b 05
67 | 00 03 81 81 00 85 aa d2 a0 e5 b9 27 6b 90 8c 65 f7 3a 72 67 17
68 | 06 18 a5 4c 5f 8a 7b 33 7d 2d f7 a5 94 36 54 17 f2 ea e8 f8 a5
69 | 8c 8f 81 72 f9 31 9c f3 6b 7f d6 c5 5b 80 f2 1a 03 01 51 56 72
70 | 60 96 fd 33 5e 5e 67 f2 db f1 02 70 2e 60 8c ca e6 be c1 fc 63
71 | a4 2a 99 be 5c 3e b7 10 7c 3c 54 e9 b9 eb 2b d5 20 3b 1c 3b 84
72 | e0 a8 b2 f7 59 40 9b a3 ea c9 d9 1d 40 2d cc 0c c8 f8 96 12 29
73 | ac 91 87 b4 2b 4d e1 00 00 0f 00 00 84 08 04 00 80 5a 74 7c 5d
74 | 88 fa 9b d2 e5 5a b0 85 a6 10 15 b7 21 1f 82 4c d4 84 14 5a b3
75 | ff 52 f1 fd a8 47 7b 0b 7a bc 90 db 78 e2 d3 3a 5c 14 1a 07 86
76 | 53 fa 6b ef 78 0c 5e a2 48 ee aa a7 85 c4 f3 94 ca b6 d3 0b be
77 | 8d 48 59 ee 51 1f 60 29 57 b1 54 11 ac 02 76 71 45 9e 46 44 5c
78 | 9e a5 8c 18 1e 81 8e 95 b8 c3 fb 0b f3 27 84 09 d3 be 15 2a 3d
79 | a5 04 3e 06 3d da 65 cd f5 ae a2 0d 53 df ac d4 2f 74 f3 14 00
80 | 00 20 9b 9b 14 1d 90 63 37 fb d2 cb dc e7 1d f4 de da 4a b4 2c
81 | 30 95 72 cb 7f ff ee 54 54 b7 8f 07 18 16`)
82 |
83 | result := conn.decryptRecord(input[:5], input[5:])
84 | equals(t, expect, result)
85 | }
86 |
87 | func TestCreateEncryptedRecord(t *testing.T) {
88 | conn := &TLSConn{}
89 | key := hexBytes(`db fa a6 93 d1 76 2c 5b 66 6a f5 d9 50 25 8d 01`)
90 | copy(conn.clientWriteKey[:], key)
91 | IV := hexBytes(`5b d3 c7 1b 83 6e 0b 76 bb 73 26 5f`)
92 | copy(conn.clientWriteIV[:], IV)
93 | conn.clientSeq = 0
94 |
95 | in := hexBytes(`14 00 00 20 a8 ec 43 6d 67 76 34 ae 52 5a
96 | c1 fc eb e1 1a 03 9e c1 76 94 fa c6 e9 85 27 b6 42 f2 ed d5 ce 61`)
97 | in = append(in, kREC_TYPE_HANDSHAKE)
98 | expected := hexBytes(`17 03 03 00 35 75 ec 4d c2 38 cc e6
99 | 0b 29 80 44 a7 1e 21 9c 56 cc 77 b0 51 7f e9 b9 3c 7a 4b fc 44
100 | d8 7f 38 f8 03 38 ac 98 fc 46 de b3 84 bd 1c ae ac ab 68 67 d7
101 | 26 c4 05 46`)
102 | result, err := conn.createEncryptedRecord(in)
103 | ok(t, err)
104 | equals(t, expected, result)
105 | }
106 |
--------------------------------------------------------------------------------
/tls/conn.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | type Conn interface {
4 | Read([]byte) (int, error)
5 | Write([]byte) (int, error)
6 | Close() error
7 | }
8 |
9 | const (
10 | kX25519KeyLen = 32
11 | kSHA256OutLen = 32
12 | kAES128KeyLen = 16
13 | kGCMIVLen = 12
14 | )
15 |
16 | type TLSConn struct {
17 | raw Conn
18 | clientRandom [32]byte
19 | clientPrivKey [kX25519KeyLen]byte
20 | clientPubKey [kX25519KeyLen]byte
21 | serverRandom [32]byte
22 | serverPubKey [kX25519KeyLen]byte
23 | transcript []byte
24 | lastTranscript []byte
25 | secret0 [32]byte
26 | masterSecret [kSHA256OutLen]byte
27 | serverSeq uint64
28 | clientSeq uint64
29 | clientWriteKey [kAES128KeyLen]byte
30 | serverWriteKey [kAES128KeyLen]byte
31 | clientWriteIV [kGCMIVLen]byte
32 | serverWriteIV [kGCMIVLen]byte
33 |
34 | clientHandshakeTrafficSecret [kSHA256OutLen]byte
35 | serverHandshakeTrafficSecret [kSHA256OutLen]byte
36 | clientApplicationTrafficSecret [kSHA256OutLen]byte
37 | serverApplicationTrafficSecret [kSHA256OutLen]byte
38 |
39 | readBuf []byte
40 | writeBuf []byte
41 | }
42 |
43 | type action int
44 |
45 | const (
46 | action_none = action(0)
47 | action_reset_sequence = action(1 << iota)
48 | action_send_finished = action(1 << iota)
49 | )
50 |
51 | func NewConn(raw Conn, hostname string) (Conn, error) {
52 | conn := &TLSConn{raw: raw}
53 | rec, err := makeClientHello(conn, hostname)
54 | if err != nil {
55 | panic(err)
56 | }
57 | err = writeHandshakeRecord(conn, rec)
58 | if err != nil {
59 | return nil, err
60 | }
61 |
62 | for {
63 | finished, err := conn.readRecord()
64 | if err != nil {
65 | panic(err)
66 | }
67 | if finished {
68 | break
69 | }
70 | }
71 | return conn, nil
72 | }
73 |
74 | func writeHandshakeRecord(conn *TLSConn, rec []byte) error {
75 | n, err := conn.raw.Write(rec)
76 | if err != nil {
77 | return err
78 | }
79 | if n != len(rec) {
80 | panic("short write")
81 | }
82 | conn.addToTranscript(rec[5:])
83 | return nil
84 | }
85 |
86 | func (conn *TLSConn) readRaw(b []byte) error {
87 | for len(b) > 0 {
88 | n, err := conn.raw.Read(b)
89 | b = b[n:]
90 | if err != nil {
91 | return err
92 | }
93 | }
94 | return nil
95 | }
96 |
97 | func (conn *TLSConn) writeRaw(b []byte) error {
98 | for len(b) > 0 {
99 | n, err := conn.raw.Write(b)
100 | b = b[n:]
101 | if err != nil {
102 | return err
103 | }
104 | }
105 | return nil
106 | }
107 |
108 | func (conn *TLSConn) Read(b []byte) (n int, err error) {
109 | if len(conn.readBuf) == 0 {
110 | _, err = conn.readRecord()
111 | if err != nil {
112 | return 0, err
113 | }
114 | }
115 | l := len(conn.readBuf)
116 | if l > len(b) {
117 | l = len(b)
118 | }
119 | copy(b[:l], conn.readBuf)
120 | conn.readBuf = conn.readBuf[l:]
121 | if len(conn.readBuf) == 0 {
122 | // reclaim memory
123 | conn.readBuf = nil
124 | }
125 | return l, nil
126 | }
127 |
128 | func (conn *TLSConn) readRecord() (handshakeFinished bool, err error) {
129 | hdrbuf := make([]byte, 5)
130 | err = conn.readRaw(hdrbuf)
131 | if err != nil {
132 | return false, err
133 | }
134 | typ := int(hdrbuf[0])
135 | length := readNum(16, hdrbuf[3:])
136 | payload := make([]byte, length)
137 | err = conn.readRaw(payload)
138 | if err != nil {
139 | return false, err
140 | }
141 | acts := conn.handleRecord(typ, hdrbuf, payload)
142 | conn.serverSeq++
143 | if acts&action_reset_sequence != 0 {
144 | conn.serverSeq = 0
145 | conn.clientSeq = 0
146 | }
147 | if acts&action_send_finished != 0 {
148 | rec, err := makeClientFinished(conn)
149 | if err != nil {
150 | panic(err)
151 | }
152 | err = writeHandshakeRecord(conn, rec)
153 | if err != nil {
154 | return false, err
155 | }
156 | computeClientApplicationKeys(conn)
157 | return true, err
158 | }
159 | return false, nil
160 | }
161 |
162 | func lastByte(bb []byte) (last byte, rest []byte) {
163 | if len(bb) == 0 {
164 | panic("lastbyte on empty record")
165 | }
166 | b := bb[len(bb)-1]
167 | return b, bb[:len(bb)-1]
168 | }
169 |
170 | func (conn *TLSConn) Write(b []byte) (n int, err error) {
171 | tosend := make([]byte, 0)
172 | tosend = append(tosend, b...)
173 | tosend = append(tosend, kREC_TYPE_APPLICATION_DATA)
174 | encrypted, err := conn.createEncryptedRecord(tosend)
175 | if err != nil {
176 | return 0, err
177 | }
178 | err = conn.writeRaw(encrypted)
179 | conn.clientSeq++
180 | if err != nil {
181 | return 0, err
182 | }
183 | return len(b), nil
184 | }
185 |
186 | func (conn *TLSConn) Close() (err error) {
187 | return conn.raw.Close()
188 | }
189 |
190 | func (conn *TLSConn) handleRecord(typ int, rechdr []byte, payload []byte) action {
191 | switch byte(typ) {
192 | case kREC_TYPE_CHANGE_CIPHER_SPEC:
193 | return handleChangeCipherSpec(conn, payload)
194 | case kREC_TYPE_ALERT:
195 | return handleAlert(conn, payload)
196 | case kREC_TYPE_HANDSHAKE:
197 | conn.addToTranscript(payload)
198 | return handleHandshake(conn, payload)
199 | case kREC_TYPE_APPLICATION_DATA:
200 | plain := conn.decryptRecord(rechdr, payload)
201 | return conn.dispatchRecordContents(rechdr, plain)
202 | default:
203 | panic("unrecognized handshake-context record type")
204 | }
205 | }
206 |
207 | // parses TLSInnerPlaintext
208 | func (conn *TLSConn) dispatchRecordContents(hdr []byte, inner []byte) action {
209 | for len(inner) != 0 && inner[len(inner)-1] == '\000' {
210 | inner = inner[:len(inner)-1]
211 | }
212 | overallType, inner := lastByte(inner)
213 |
214 | acts := action_none
215 | switch overallType {
216 | case kREC_TYPE_APPLICATION_DATA:
217 | conn.readBuf = append(conn.readBuf, inner...)
218 | acts |= action_none
219 | case kREC_TYPE_HANDSHAKE:
220 | // multiple handshake records conglommed together
221 | for len(inner) != 0 {
222 | len := readNum(24, inner[1:])
223 | payload := inner[:4+len]
224 | inner = inner[4+len:]
225 | acts |= conn.handleRecord(int(overallType), hdr, payload)
226 | }
227 | default:
228 | acts |= conn.handleRecord(int(overallType), hdr, inner)
229 | }
230 | return acts
231 | }
232 |
233 | func (conn *TLSConn) addToTranscript(hsr []byte) {
234 | conn.lastTranscript = conn.transcript
235 | conn.transcript = append(conn.transcript, hsr...)
236 | }
237 |
--------------------------------------------------------------------------------
/algo/sha256/sha256_test.go:
--------------------------------------------------------------------------------
1 | package sha256_test
2 |
3 | import (
4 | "encoding/hex"
5 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
6 | "strings"
7 | "testing"
8 | )
9 |
10 | func h(sum []byte) string {
11 | return hex.EncodeToString(sum)
12 | }
13 |
14 | func b(s string) []byte {
15 | return []byte(s)
16 | }
17 |
18 | func TestEmpty(t *testing.T) {
19 | s := sha256.New()
20 | equals(t, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", h(s.Sum()))
21 | }
22 |
23 | func TestOne(t *testing.T) {
24 | s := sha256.New()
25 | s.Add(b("a"))
26 | equals(t, "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", h(s.Sum()))
27 | }
28 |
29 | func TestReset(t *testing.T) {
30 | s := sha256.New()
31 | s.Add(b("a"))
32 | equals(t, "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", h(s.Sum()))
33 | s.Reset()
34 | s.Add(b("b"))
35 | equals(t, "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", h(s.Sum()))
36 | }
37 |
38 | func TestString(t *testing.T) {
39 | str := "()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm"
40 | s := sha256.New()
41 | s.Add(b(str))
42 | equals(t, "e1de062261d80b7a9d13bc0c0504a67cd97670a849e5de5c9d68ce458b1f8728", h(s.Sum()))
43 | }
44 |
45 | func TestBoundaries(t *testing.T) {
46 | str := "()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm"
47 | for i := 0; i < len(str); i++ {
48 | t.Log("testing", i)
49 | s := sha256.New()
50 | s.Add(b(str[:i]))
51 | s.Add(b(str[i:]))
52 | equals(t, "e1de062261d80b7a9d13bc0c0504a67cd97670a849e5de5c9d68ce458b1f8728", h(s.Sum()))
53 | }
54 | }
55 |
56 | func TestMults(t *testing.T) {
57 | str := "()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm"
58 | for mult := 1; mult < len(str)/2; mult++ {
59 | t.Log("testing", mult)
60 | s := sha256.New()
61 | in := str
62 | for len(in) > mult {
63 | s.Add(b(in[:mult]))
64 | in = in[mult:]
65 | }
66 | s.Add(b(in))
67 | equals(t, "e1de062261d80b7a9d13bc0c0504a67cd97670a849e5de5c9d68ce458b1f8728", h(s.Sum()))
68 | }
69 | }
70 |
71 | func TestAllInOne(t *testing.T) {
72 | in := []byte("foobarbaz")
73 | expected, _ := hex.DecodeString("97df3588b5a3f24babc3851b372f0ba71a9dcdded43b14b9d06961bfc1707d9d")
74 | equals(t, expected, sha256.SumData(in))
75 | }
76 |
77 | func TestBig(t *testing.T) {
78 | in := `
79 | 01 00 00 82 03 03 69 94 d7 ee f2 25 94 fa d5 b5
80 | a0 73 45 2c 9a a2 f9 1b 05 a6 dc f6 0c fe 2b 66
81 | a0 50 70 32 b8 a1 00 00 02 13 01 01 00 00 57 00
82 | 2b 00 03 02 03 04 00 0a 00 04 00 02 00 1d 00 33
83 | 00 26 00 24 00 1d 00 20 19 ae d3 3c fc b5 0e 45
84 | f9 21 af 0b ef 14 3d 74 18 82 33 69 1d de b7 81
85 | e0 99 81 fa 25 3f de 31 00 00 00 0e 00 0c 00 00
86 | 09 31 32 37 2e 30 2e 30 2e 31 00 0d 00 08 00 06
87 | 04 01 04 03 08 04 02 00 00 56 03 03 d9 83 34 af
88 | 56 5c b7 cc a6 03 ff 05 f2 bc e6 2d b3 09 51 c3
89 | 02 98 92 46 86 88 fb e4 53 24 01 b0 00 13 01 00
90 | 00 2e 00 33 00 24 00 1d 00 20 f5 b5 3b d7 bb 01
91 | 7d 91 ee aa ea 9a d5 09 5e c1 de 5d 39 1c cf 6a
92 | 98 a5 f2 e4 89 9c 80 01 1c 5c 00 2b 00 02 03 04
93 | 08 00 00 02 00 00 0b 00 02 e4 00 00 02 e0 00 02
94 | db 30 82 02 d7 30 82 01 bf a0 03 02 01 02 02 09
95 | 00 d5 38 3b 76 56 69 e0 a2 30 0d 06 09 2a 86 48
96 | 86 f7 0d 01 01 0b 05 00 30 17 31 15 30 13 06 03
97 | 55 04 03 0c 0c 65 61 38 35 35 32 65 64 64 63 30
98 | 66 30 1e 17 0d 31 38 31 30 32 35 32 33 30 38 33
99 | 34 5a 17 0d 32 38 31 30 32 32 32 33 30 38 33 34
100 | 5a 30 17 31 15 30 13 06 03 55 04 03 0c 0c 65 61
101 | 38 35 35 32 65 64 64 63 30 66 30 82 01 22 30 0d
102 | 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 82 01
103 | 0f 00 30 82 01 0a 02 82 01 01 00 f8 ba 42 6f 54
104 | ea a2 22 ea 02 dd 02 9d c4 7a 3d 3a 2b 63 ce 84
105 | c3 0e 62 03 e4 6b 9f ee 16 d7 a3 87 76 c6 b8 52
106 | 6c 77 bf c4 0c d0 16 53 47 00 f5 94 25 25 18 bd
107 | 40 40 b0 2e ed 60 c8 19 b1 98 22 b9 90 4d a5 d4
108 | 06 38 a3 8d 76 87 3a 25 7a 44 11 04 8a e8 c1 39
109 | 1b 53 cd 4e 60 e2 d7 ea 5e 83 92 58 3f a8 bd cd
110 | 52 1a 50 2f 25 27 39 c2 8b 93 0b 5d 53 cc a3 d5
111 | 5b 08 69 c5 a8 0c 5d 53 80 50 97 83 59 9d b5 3d
112 | f3 7c 25 c0 6b c0 00 eb bb 0d 68 64 e9 13 03 d4
113 | d6 b6 64 0e c1 74 de f1 c3 10 fe 66 a8 af 54 2e
114 | ca 9c 2f 24 eb c5 24 d4 59 cf 8b e1 74 88 aa 06
115 | df 37 cf 10 b7 3c da b3 85 34 ef 0d d1 06 8c 1d
116 | 6e eb 2c c9 8f e7 ca 79 4b be 7b ce 54 0d 17 f8
117 | 12 63 67 28 c7 fe ee 5c dc c4 ef 95 cd 23 fb 03
118 | ae 48 87 b4 48 40 52 e3 46 02 6d bc 94 f0 04 7f
119 | ec 3d 78 74 68 eb a9 df 94 95 95 02 03 01 00 01
120 | a3 26 30 24 30 09 06 03 55 1d 13 04 02 30 00 30
121 | 17 06 03 55 1d 11 04 10 30 0e 82 0c 65 61 38 35
122 | 35 32 65 64 64 63 30 66 30 0d 06 09 2a 86 48 86
123 | f7 0d 01 01 0b 05 00 03 82 01 01 00 05 2c eb f7
124 | 2f fd 6f bf af d0 7b c5 b1 ed 98 41 9f 99 eb 96
125 | 21 51 41 6c 15 cb 45 a4 59 00 d9 ae 34 02 dd 7a
126 | 30 62 63 4e 55 6d 0c aa 93 4f 74 09 03 9c 1a 53
127 | ab 87 cc 7f 24 96 5c 5a 16 51 1f 35 82 f8 c2 05
128 | bc 5b 75 69 44 c6 2a 35 97 bc b5 9e cf 82 f0 5d
129 | af 6d cd be 29 38 f2 3c e7 bc f6 4f 9e 8e db a0
130 | 9b 43 57 ea b2 20 9a 18 0e e6 f0 2a f9 6e 71 54
131 | 7d 2d fc de ab 89 ac 32 fe 8f 60 88 4f 65 b1 e3
132 | 27 ab 1b 09 a0 7c dd 7e 22 67 54 82 79 26 05 95
133 | 16 f7 a4 54 cd 55 e2 b7 06 01 4c 0b 84 a8 53 d1
134 | f2 82 1d 3a df 4b 90 3b 93 9f 44 fd d1 ec 91 bc
135 | 0b d0 99 77 17 a0 72 6f 63 97 a3 8a ae 35 d1 d4
136 | 3a 91 c2 14 d8 e8 dc 82 80 d6 91 79 35 7a 93 cc
137 | 12 95 4b 6b b6 05 61 1a 78 d7 96 4c 55 74 11 ca
138 | 39 9d 26 61 63 91 c8 45 1c 9f 66 dc ea 4b 55 fe
139 | ea 28 e0 71 37 81 01 75 ed b9 d3 5d 00 00 0f 00
140 | 01 04 08 04 01 00 e6 9d ac 54 de 84 40 97 51 6d
141 | 31 85 ea 38 29 7d 38 e6 85 ee 91 82 d9 ca d9 78
142 | 09 7b 63 55 f1 6a 4f ef 16 c3 36 a8 3f 4f 46 ba
143 | 74 3c 4d c8 44 e6 b4 86 76 be a0 f3 99 a8 2a f3
144 | 72 e5 92 43 1d 52 98 d3 52 8d 3d cf 0e 18 3c f1
145 | 96 28 55 bb 9a 51 ca 23 50 7b 50 15 64 0a 2c 76
146 | 4d 0f a9 75 8f 3a 6e d3 9a b0 0b 0a 37 25 56 b5
147 | f3 33 f1 4f 13 5b c6 80 8b 6d 66 b4 22 80 1c 37
148 | 28 f8 63 91 65 67 87 57 09 b3 5e 1c 21 07 d6 d3
149 | fa 5e 39 a5 e9 8a c8 85 14 91 f9 3c 3c 2d 07 86
150 | bf 0c a5 2e eb 0e 12 8d 1c ef c0 cb 94 84 63 23
151 | 41 3e 6c 1f ba 26 5b 73 ae 79 19 f1 5d e0 4a fb
152 | f4 82 ce 7d 0b 30 70 df 27 b4 30 fa ca 52 6c f7
153 | 72 d8 d3 5d 5e 51 a1 d4 eb c5 0b 5d 33 27 c2 25
154 | ca ce 67 c7 af 07 1b 87 6b ca 91 6b 88 6e a8 6c
155 | 27 ae f9 61 de df d1 cf 73 af b2 2c 1b 58 2f b4
156 | 7a 43 d5 47 5e 97 14 00 00 20 c2 c2 19 9d 55 c5
157 | eb 9d 2f 33 89 71 0f 12 f9 09 3b b2 56 ce 80 4c
158 | 81 df 36 87 e1 ab 22 c5 3c 1d`
159 | in = strings.Join(strings.Fields(in), "")
160 | b, _ := hex.DecodeString(in)
161 | expected, _ := hex.DecodeString("e4841d104d7f26ad1a13f01d0cd4d5b4e949ecb93f0d07a75b402b4e97154a15")
162 | equals(t, expected, sha256.SumData(b))
163 | }
164 |
--------------------------------------------------------------------------------
/algo/curve25519/coord_test.go:
--------------------------------------------------------------------------------
1 | package curve25519
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestCopy(t *testing.T) {
8 | a := newCoord(1)
9 | b := a.copy()
10 | equals(t, a, b)
11 | a[0]++
12 | assert(t, a[0] != b[0], "a and b don't seem to be copies")
13 | }
14 |
15 | func TestCoordToHex(t *testing.T) {
16 | a := newCoord(0)
17 | equals(t, "0x00000000", a.toHex())
18 |
19 | a = newCoord(1)
20 | equals(t, "0x00000001", a.toHex())
21 |
22 | a = newCoord(0xff)
23 | equals(t, "0x000000ff", a.toHex())
24 |
25 | a = newCoord(0xffffffff)
26 | equals(t, "0xffffffff", a.toHex())
27 | }
28 |
29 | func TestCoordAdd(t *testing.T) {
30 | a := newCoord(0xffffffffffffffff)
31 | b := newCoord(1)
32 | c := a.add(b)
33 | equals(t, "0x00000001_00000000_00000000", c.toHex())
34 | c = b.add(a)
35 | equals(t, "0x00000001_00000000_00000000", c.toHex())
36 | }
37 |
38 | func TestCoordAddCarry(t *testing.T) {
39 | a := newCoord(0xffffffffffffffff)
40 | b := newCoord(0xffffffffffffffff)
41 | c := a.add(b)
42 | equals(t, "0x00000001_ffffffff_fffffffe", c.toHex())
43 | }
44 |
45 | func TestCoordCompare(t *testing.T) {
46 | a := newCoord(0)
47 | b := newCoord(0)
48 | assert(t, a.compare(b) == 0, "a and b are not seen as equal")
49 | a = newCoord(1)
50 | assert(t, a.compare(b) > 0, "a not seen bigger than b")
51 | assert(t, b.compare(a) < 0, "a not seen bigger than b")
52 |
53 | a = newCoord(1)
54 | b = newCoord(0xFFFFFFFF)
55 | b = a.add(b)
56 | assert(t, b.compare(a) > 0, "a not seen bigger than b")
57 | assert(t, a.compare(b) < 0, "a not seen bigger than b")
58 | }
59 |
60 | func TestCoordRotateSmall(t *testing.T) {
61 | a := newCoord(0x01020304)
62 | a = a.rotl(8)
63 | equals(t, "0x00000001_02030400", a.toHex())
64 | a = a.rotr(8)
65 | equals(t, "0x01020304", a.toHex())
66 | a = a.rotl(4)
67 | equals(t, "0x10203040", a.toHex())
68 | }
69 |
70 | func TestCoordRotateLarge(t *testing.T) {
71 | a := newCoord(1)
72 | a = a.rotl(32)
73 | equals(t, "0x00000001_00000000", a.toHex())
74 | a = a.rotl(32)
75 | equals(t, "0x00000001_00000000_00000000", a.toHex())
76 | a = a.rotl(32)
77 | equals(t, "0x00000001_00000000_00000000_00000000", a.toHex())
78 | a = a.rotr(32)
79 | a = a.rotr(32)
80 | equals(t, "0x00000001_00000000", a.toHex())
81 | a = a.rotr(32)
82 | equals(t, "0x00000001", a.toHex())
83 | a = a.rotl(40)
84 | equals(t, "0x00000100_00000000", a.toHex())
85 | a = a.rotr(40)
86 | equals(t, "0x00000001", a.toHex())
87 | }
88 |
89 | func TestCoordSub(t *testing.T) {
90 | a := newCoord(10)
91 | b := newCoord(1)
92 | c := a.sub(b)
93 | equals(t, "0x00000009", c.toHex())
94 |
95 | a = newCoord(0)
96 | c = a.sub(newCoord(2))
97 | equals(t, "0xffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff"+
98 | "_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_fffffffe", c.toHex())
99 | }
100 |
101 | func TestCoordReduce(t *testing.T) {
102 | a := newCoord(0)
103 | a = a.reduce()
104 | equals(t, "0x00000000", a.toHex())
105 |
106 | a = newCoord(1)
107 | a = a.reduce()
108 | equals(t, "0x00000001", a.toHex())
109 |
110 | a = coordModulus.copy()
111 | a = a.reduce()
112 | equals(t, "0x00000000", a.toHex())
113 |
114 | a = coordModulus.sub(newCoord(1))
115 | a = a.reduce()
116 | equals(t, "0x7fffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffec", a.toHex())
117 |
118 | a = coordModulus.add(newCoord(1))
119 | a = a.reduce()
120 | equals(t, "0x00000001", a.toHex())
121 | }
122 |
123 | func TestCoordMult(t *testing.T) {
124 | a := newCoord(1)
125 | b := newCoord(2)
126 | c := a.mult(b)
127 | equals(t, "0x00000002", c.toHex())
128 |
129 | a = newCoord(0xabcd)
130 | b = newCoord(0x1f)
131 | c = a.mult(b)
132 | equals(t, "0x0014cdd3", c.toHex())
133 | }
134 |
135 | func TestCoordMultMax(t *testing.T) {
136 | a := newCoord(0xFFFFFFFF)
137 | a = a.mult(newCoord(2))
138 | equals(t, "0x00000001_fffffffe", a.toHex())
139 |
140 | a = newCoord(2)
141 | a = a.mult(newCoord(0xFFFFFFFF))
142 | equals(t, "0x00000001_fffffffe", a.toHex())
143 |
144 | a = newCoord(0xFFFFFFFF)
145 | a = a.mult(a)
146 | equals(t, "0xfffffffe_00000001", a.toHex())
147 |
148 | a = coordModulus.mult(coordModulus)
149 | equals(t, "0x3fffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffed"+
150 | "_00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000169", a.toHex())
151 | }
152 |
153 | func TestCoordModMults(t *testing.T) {
154 | a := newCoord(1).mult(coordModulus)
155 | equals(t, "0x7fffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffed", a.toHex())
156 | b := newCoord(2).mult(coordModulus)
157 | equals(t, "0xffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffda", b.toHex())
158 | c := newCoord(3).mult(coordModulus)
159 | equals(t, "0x00000001_7fffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffc7", c.toHex())
160 | d := newCoord(4).mult(coordModulus)
161 | equals(t, "0x00000001_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffff_ffffffb4", d.toHex())
162 | }
163 |
164 | func TestCoordReduceThree(t *testing.T) {
165 | a := newCoord(3).mult(coordModulus)
166 | a = a.reduce()
167 | equals(t, "0x00000000", a.toHex())
168 | }
169 |
170 | func TestCoordMultByAdd(t *testing.T) {
171 | a := coordModulus.mult(newCoord(3))
172 | b := coordModulus.mult(newCoord(2))
173 | b = b.add(coordModulus)
174 | equals(t, "0x00000000", a.sub(b).toHex())
175 | }
176 |
177 | func TestCoordMultCommutative(t *testing.T) {
178 | a := newCoord(3)
179 | b := newCoord(0xFFFFFFFFFFFFFFFF)
180 | c1 := a.mult(b)
181 | c2 := b.mult(a)
182 | assert(t, c1.compare(c2) == 0, "c1 and c2 not equal")
183 | equals(t, "0x00000000", c1.sub(c2).toHex())
184 | }
185 |
186 | func TestCoordBigSub(t *testing.T) {
187 | a := coordModulus.mult(newCoord(3))
188 | b := coordModulus.rotl(1)
189 | equals(t, coordModulus, a.sub(b))
190 | }
191 |
192 | func TestCoordMaxReduce(t *testing.T) {
193 | a := coordModulus
194 | a = a.reduce()
195 | equals(t, "0x00000000", a.toHex())
196 |
197 | a = coordModulus.mult(newCoord(2))
198 | a = a.reduce()
199 | equals(t, "0x00000000", a.toHex())
200 |
201 | a = coordModulus.mult(newCoord(3))
202 | a = a.reduce()
203 | equals(t, "0x00000000", a.toHex())
204 |
205 | for i := uint64(0); i < 10; i++ {
206 | t.Log("Testing", i)
207 | a = coordModulus.mult(newCoord(i))
208 | a = a.reduce()
209 | equals(t, "0x00000000", a.toHex())
210 | }
211 |
212 | a = coordModulus.mult(coordModulus)
213 | a = a.reduce()
214 | equals(t, "0x00000000", a.toHex())
215 | }
216 |
217 | func TestCoordNBit(t *testing.T) {
218 | a := newCoord(5)
219 | equals(t, 1, a.nbit(0))
220 | equals(t, 0, a.nbit(1))
221 | equals(t, 1, a.nbit(2))
222 | equals(t, 0, a.nbit(3))
223 |
224 | a = a.rotl(128)
225 | equals(t, 0, a.nbit(0))
226 | equals(t, 1, a.nbit(128))
227 | equals(t, 0, a.nbit(129))
228 | equals(t, 1, a.nbit(130))
229 | }
230 |
231 | func TestBytesToCoord(t *testing.T) {
232 | var b = [32]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
233 | 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20}
234 | c := bytesToCoord(b)
235 | equals(t, "0x201f1e1d_1c1b1a19_18171615_14131211_100f0e0d_0c0b0a09_08070605_04030201", c.toHex())
236 | }
237 |
238 | func TestCoordToBytes(t *testing.T) {
239 | var b = [32]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
240 | 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20}
241 | c := bytesToCoord(b)
242 | equals(t, b, c.toBytes())
243 | }
244 |
245 | func TestCoordReduceNegative(t *testing.T) {
246 | a := newCoord(0)
247 | b := newCoord(1)
248 | c := a.sub(b)
249 | t.Log("c is", c.toHex())
250 | d := c.reduce()
251 | e := coordModulus.sub(newCoord(1))
252 | equals(t, e, d)
253 | }
254 |
--------------------------------------------------------------------------------
/tls/computekeys_test.go:
--------------------------------------------------------------------------------
1 | package tls
2 |
3 | import (
4 | "encoding/hex"
5 | "github.com/syncsynchalt/tincan-tls/algo/hkdf"
6 | "github.com/syncsynchalt/tincan-tls/algo/sha256"
7 | "testing"
8 | )
9 |
10 | func TestHkdfExpandLabel(t *testing.T) {
11 | s := sha256.New()
12 | secret := hkdf.Extract(s, []byte{}, []byte{1})
13 | label := "label"
14 | context := []byte("context")
15 | expect, _ := hex.DecodeString("0d2bb3f622e426b79370b4c7d6de641fe0a63ae2657d006357dcf35a8796f2ff")
16 | keys := hkdfExpandLabel(secret, label, context, 32)
17 | equals(t, expect, keys)
18 | }
19 |
20 | // https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-07
21 | func generateTestRecords() map[string][]byte {
22 | records := make(map[string][]byte)
23 | records["client_hello"] = hexBytes(`01 00 00 c0 03 03 cb 34 ec b1 e7 81 63 ba
24 | 1c 38 c6 da cb 19 6a 6d ff a2 1a 8d 99 12 ec 18 a2 ef 62 83 02
25 | 4d ec e7 00 00 06 13 01 13 03 13 02 01 00 00 91 00 00 00 0b 00
26 | 09 00 00 06 73 65 72 76 65 72 ff 01 00 01 00 00 0a 00 14 00 12
27 | 00 1d 00 17 00 18 00 19 01 00 01 01 01 02 01 03 01 04 00 23 00
28 | 00 00 33 00 26 00 24 00 1d 00 20 99 38 1d e5 60 e4 bd 43 d2 3d
29 | 8e 43 5a 7d ba fe b3 c0 6e 51 c1 3c ae 4d 54 13 69 1e 52 9a af
30 | 2c 00 2b 00 03 02 03 04 00 0d 00 20 00 1e 04 03 05 03 06 03 02
31 | 03 08 04 08 05 08 06 04 01 05 01 06 01 02 01 04 02 05 02 06 02
32 | 02 02 00 2d 00 02 01 01 00 1c 00 02 40 01`)
33 | records["server_hello"] = hexBytes(`02 00 00 56 03 03 a6 af 06 a4 12 18 60
34 | dc 5e 6e 60 24 9c d3 4c 95 93 0c 8a c5 cb 14 34 da c1 55 77 2e
35 | d3 e2 69 28 00 13 01 00 00 2e 00 33 00 24 00 1d 00 20 c9 82 88
36 | 76 11 20 95 fe 66 76 2b db f7 c6 72 e1 56 d6 cc 25 3b 83 3d f1
37 | dd 69 b1 b0 4e 75 1f 0f 00 2b 00 02 03 04`)
38 | records["server_encrypted_extensions"] = hexBytes(`08 00 00 24 00 22 00 0a 00 14 00
39 | 12 00 1d 00 17 00 18 00 19 01 00 01 01 01 02 01 03 01 04 00 1c
40 | 00 02 40 01 00 00 00 00`)
41 | records["server_certificate"] = hexBytes(`0b 00 01 b9 00 00 01 b5 00 01 b0 30 82
42 | 01 ac 30 82 01 15 a0 03 02 01 02 02 01 02 30 0d 06 09 2a 86 48
43 | 86 f7 0d 01 01 0b 05 00 30 0e 31 0c 30 0a 06 03 55 04 03 13 03
44 | 72 73 61 30 1e 17 0d 31 36 30 37 33 30 30 31 32 33 35 39 5a 17
45 | 0d 32 36 30 37 33 30 30 31 32 33 35 39 5a 30 0e 31 0c 30 0a 06
46 | 03 55 04 03 13 03 72 73 61 30 81 9f 30 0d 06 09 2a 86 48 86 f7
47 | 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 b4 bb 49 8f
48 | 82 79 30 3d 98 08 36 39 9b 36 c6 98 8c 0c 68 de 55 e1 bd b8 26
49 | d3 90 1a 24 61 ea fd 2d e4 9a 91 d0 15 ab bc 9a 95 13 7a ce 6c
50 | 1a f1 9e aa 6a f9 8c 7c ed 43 12 09 98 e1 87 a8 0e e0 cc b0 52
51 | 4b 1b 01 8c 3e 0b 63 26 4d 44 9a 6d 38 e2 2a 5f da 43 08 46 74
52 | 80 30 53 0e f0 46 1c 8c a9 d9 ef bf ae 8e a6 d1 d0 3e 2b d1 93
53 | ef f0 ab 9a 80 02 c4 74 28 a6 d3 5a 8d 88 d7 9f 7f 1e 3f 02 03
54 | 01 00 01 a3 1a 30 18 30 09 06 03 55 1d 13 04 02 30 00 30 0b 06
55 | 03 55 1d 0f 04 04 03 02 05 a0 30 0d 06 09 2a 86 48 86 f7 0d 01
56 | 01 0b 05 00 03 81 81 00 85 aa d2 a0 e5 b9 27 6b 90 8c 65 f7 3a
57 | 72 67 17 06 18 a5 4c 5f 8a 7b 33 7d 2d f7 a5 94 36 54 17 f2 ea
58 | e8 f8 a5 8c 8f 81 72 f9 31 9c f3 6b 7f d6 c5 5b 80 f2 1a 03 01
59 | 51 56 72 60 96 fd 33 5e 5e 67 f2 db f1 02 70 2e 60 8c ca e6 be
60 | c1 fc 63 a4 2a 99 be 5c 3e b7 10 7c 3c 54 e9 b9 eb 2b d5 20 3b
61 | 1c 3b 84 e0 a8 b2 f7 59 40 9b a3 ea c9 d9 1d 40 2d cc 0c c8 f8
62 | 96 12 29 ac 91 87 b4 2b 4d e1 00 00`)
63 | records["server_certificate_verify"] = hexBytes(`0f 00 00 84 08 04 00 80 5a 74 7c
64 | 5d 88 fa 9b d2 e5 5a b0 85 a6 10 15 b7 21 1f 82 4c d4 84 14 5a
65 | b3 ff 52 f1 fd a8 47 7b 0b 7a bc 90 db 78 e2 d3 3a 5c 14 1a 07
66 | 86 53 fa 6b ef 78 0c 5e a2 48 ee aa a7 85 c4 f3 94 ca b6 d3 0b
67 | be 8d 48 59 ee 51 1f 60 29 57 b1 54 11 ac 02 76 71 45 9e 46 44
68 | 5c 9e a5 8c 18 1e 81 8e 95 b8 c3 fb 0b f3 27 84 09 d3 be 15 2a
69 | 3d a5 04 3e 06 3d da 65 cd f5 ae a2 0d 53 df ac d4 2f 74 f3`)
70 | records["server_finished"] = hexBytes(`14 00 00 20 9b 9b 14 1d 90 63 37 fb d2 cb
71 | dc e7 1d f4 de da 4a b4 2c 30 95 72 cb 7f ff ee 54 54 b7 8f 07 18`)
72 | records["client_finished"] = hexBytes(`14 00 00 20 a8 ec 43 6d 67 76 34 ae 52 5a
73 | c1 fc eb e1 1a 03 9e c1 76 94 fa c6 e9 85 27 b6 42 f2 ed d5 ce 61`)
74 | return records
75 | }
76 |
77 | // https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-07
78 | func TestHandshakeKeys(t *testing.T) {
79 | conn := &TLSConn{}
80 | recs := generateTestRecords()
81 | conn.addToTranscript(recs["client_hello"])
82 | conn.addToTranscript(recs["server_hello"])
83 |
84 | clientPriv := hexBytes(`49 af 42 ba 7f 79 94 85 2d 71 3e f2 78
85 | 4b cb ca a7 91 1d e2 6a dc 56 42 cb 63 45 40 e7 ea 50 05`)
86 | serverPub := hexBytes(`c9 82 88 76 11 20 95 fe 66 76 2b db f7 c6
87 | 72 e1 56 d6 cc 25 3b 83 3d f1 dd 69 b1 b0 4e 75 1f 0f`)
88 | copy(conn.clientPrivKey[:], clientPriv)
89 | copy(conn.serverPubKey[:], serverPub)
90 |
91 | computeHandshakeKeys(conn)
92 |
93 | expectClient := hexBytes(`b3 ed db 12 6e 06 7f 35 a7 80 b3 ab f4 5e
94 | 2d 8f 3b 1a 95 07 38 f5 2e 96 00 74 6a 0e 27 a5 5a 21`)
95 | equals(t, expectClient, conn.clientHandshakeTrafficSecret[:])
96 |
97 | expectServer := hexBytes(`b6 7b 7d 69 0c c1 6c 4e 75 e5 42 13 cb 2d
98 | 37 b4 e9 c9 12 bc de d9 10 5d 42 be fd 59 d3 91 ad 38`)
99 | equals(t, expectServer, conn.serverHandshakeTrafficSecret[:])
100 |
101 | expectMaster := hexBytes(`18 df 06 84 3d 13 a0 8b f2 a4 49 84 4c 5f 8a
102 | 47 80 01 bc 4d 4c 62 79 84 d5 a4 1d a8 d0 40 29 19`)
103 | equals(t, expectMaster, conn.masterSecret[:])
104 |
105 | expectCHKey := hexBytes(`db fa a6 93 d1 76 2c 5b 66 6a f5 d9 50 25 8d 01`)
106 | expectCHIV := hexBytes(`5b d3 c7 1b 83 6e 0b 76 bb 73 26 5f`)
107 | equals(t, expectCHKey, conn.clientWriteKey[:])
108 | equals(t, expectCHIV, conn.clientWriteIV[:])
109 | expectSHKey := hexBytes(`3f ce 51 60 09 c2 17 27 d0 f2 e4 e8 6e e4 03 bc`)
110 | expectSHIV := hexBytes(`5d 31 3e b2 67 12 76 ee 13 00 0b 30`)
111 | equals(t, expectSHKey, conn.serverWriteKey[:])
112 | equals(t, expectSHIV, conn.serverWriteIV[:])
113 | }
114 |
115 | // https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-07
116 | func TestServerApplicationKeys(t *testing.T) {
117 | conn := &TLSConn{}
118 | recs := generateTestRecords()
119 | conn.addToTranscript(recs["client_hello"])
120 | conn.addToTranscript(recs["server_hello"])
121 |
122 | clientPriv := hexBytes(`49 af 42 ba 7f 79 94 85 2d 71 3e f2 78
123 | 4b cb ca a7 91 1d e2 6a dc 56 42 cb 63 45 40 e7 ea 50 05`)
124 | serverPub := hexBytes(`c9 82 88 76 11 20 95 fe 66 76 2b db f7 c6
125 | 72 e1 56 d6 cc 25 3b 83 3d f1 dd 69 b1 b0 4e 75 1f 0f`)
126 | copy(conn.clientPrivKey[:], clientPriv)
127 | copy(conn.serverPubKey[:], serverPub)
128 |
129 | computeHandshakeKeys(conn)
130 |
131 | conn.addToTranscript(recs["server_encrypted_extensions"])
132 | conn.addToTranscript(recs["server_certificate"])
133 | conn.addToTranscript(recs["server_certificate_verify"])
134 | conn.addToTranscript(recs["server_finished"])
135 |
136 | computeServerApplicationKeys(conn)
137 |
138 | expectClientAppSecret := hexBytes(`9e 40 64 6c e7 9a 7f 9d c0 5a f8 88 9b ce
139 | 65 52 87 5a fa 0b 06 df 00 87 f7 92 eb b7 c1 75 04 a5`)
140 | expectServerAppSecret := hexBytes(`a1 1a f9 f0 55 31 f8 56 ad 47 11 6b 45 a9
141 | 50 32 82 04 b4 f4 4b fb 6b 3a 4b 4f 1f 3f cb 63 16 43`)
142 | equals(t, expectClientAppSecret, conn.clientApplicationTrafficSecret[:])
143 | equals(t, expectServerAppSecret, conn.serverApplicationTrafficSecret[:])
144 | expectServerWriteKey := hexBytes(`9f 02 28 3b 6c 9c 07 ef c2 6b b9 f2 ac 92 e3 56`)
145 | expectServerWriteIV := hexBytes(`cf 78 2b 88 dd 83 54 9a ad f1 e9 84`)
146 | equals(t, expectServerWriteKey, conn.serverWriteKey[:])
147 | equals(t, expectServerWriteIV, conn.serverWriteIV[:])
148 | expectClientWriteKey := hexBytes(`db fa a6 93 d1 76 2c 5b 66 6a f5 d9 50 25 8d 01`)
149 | expectClientWriteIV := hexBytes(`5b d3 c7 1b 83 6e 0b 76 bb 73 26 5f`)
150 | equals(t, expectClientWriteKey, conn.clientWriteKey[:])
151 | equals(t, expectClientWriteIV, conn.clientWriteIV[:])
152 | }
153 |
154 | func TestIllustratedHSKeys(t *testing.T) {
155 | conn := &TLSConn{}
156 | clientHello := hexBytes(`010000c20303000102030405060708090a0b0c0d0e0f101112
157 | 131415161718191a1b1c1d1e1f20e0e1e2e3e4e5e6e7e8e9eaebecedeeef
158 | f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff0006130113021303010000730000
159 | 001800160000136578616d706c652e756c666865696d2e6e6574000a0004
160 | 0002001d000d001400120403080404010503080505010806060102010033
161 | 00260024001d0020358072d6365880d1aeea329adf9121383851ed21a28e
162 | 3b75e965d0d2cd166254002d00020101002b0003020304`)
163 | serverHello := hexBytes(`020000760303707172737475767778797a7b7c7d7e7f808182
164 | 838485868788898a8b8c8d8e8f20e0e1e2e3e4e5e6e7e8e9eaebecedeeef
165 | f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff130100002e00330024001d00209f
166 | d7ad6dcff4298dd3f96d5b1b2af910a0535b1488d7f8fabb349a982880b6
167 | 15002b00020304`)
168 | conn.addToTranscript(clientHello)
169 | conn.addToTranscript(serverHello)
170 |
171 | clientPriv := hexBytes(`202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f`)
172 | serverPub := hexBytes(`9fd7ad6dcff4298dd3f96d5b1b2af910a0535b1488d7f8fabb349a982880b615`)
173 | copy(conn.clientPrivKey[:], clientPriv)
174 | copy(conn.serverPubKey[:], serverPub)
175 |
176 | computeHandshakeKeys(conn)
177 |
178 | expectClient := hexBytes(`66afa331b2e837d9ee285c12047b0a80a757f917ddbfa873e1abc579da297401`)
179 | equals(t, expectClient, conn.clientHandshakeTrafficSecret[:])
180 |
181 | expectServer := hexBytes(`a56045661f3bfed8ff504c40d0c49a6cb82aebfa185eb7f52f2a915b5a292754`)
182 | equals(t, expectServer, conn.serverHandshakeTrafficSecret[:])
183 |
184 | expectMaster := hexBytes(`7f2882bb9b9a46265941653e9c2f19067118151e21d12e57a7b6aca1f8150c8d`)
185 | equals(t, expectMaster, conn.masterSecret[:])
186 |
187 | expectCHKey := hexBytes(`bd75f8a10bf81727cba7b7930f2d2d08`)
188 | expectCHIV := hexBytes(`80852b60fb8bf887aa6a22d1`)
189 | equals(t, expectCHKey, conn.clientWriteKey[:])
190 | equals(t, expectCHIV, conn.clientWriteIV[:])
191 | expectSHKey := hexBytes(`b567abf4246f473edad4efd363c5c8ad`)
192 | expectSHIV := hexBytes(`99dc72e32ed29ca25ffe44a5`)
193 | equals(t, expectSHKey, conn.serverWriteKey[:])
194 | equals(t, expectSHIV, conn.serverWriteIV[:])
195 | }
196 |
--------------------------------------------------------------------------------
/algo/gcm/gcm_test.go:
--------------------------------------------------------------------------------
1 | package gcm
2 |
3 | import (
4 | "encoding/hex"
5 | "testing"
6 |
7 | "github.com/syncsynchalt/tincan-tls/algo/aes"
8 | )
9 |
10 | func TestUInt64ToBEBytes(t *testing.T) {
11 | b := uint64ToBEBytes(0x00)
12 | equals(t, []byte{0, 0, 0, 0, 0, 0, 0, 0}, b)
13 | b = uint64ToBEBytes(0x01)
14 | equals(t, []byte{0, 0, 0, 0, 0, 0, 0, 1}, b)
15 | b = uint64ToBEBytes(0x0102030405060708)
16 | equals(t, []byte{1, 2, 3, 4, 5, 6, 7, 8}, b)
17 | }
18 |
19 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
20 | func TestGCMEncryptGuzziEmpty(t *testing.T) {
21 | key, _ := hex.DecodeString("00000000000000000000000000000000")
22 | iv, _ := hex.DecodeString("000000000000000000000000")
23 | pt, _ := hex.DecodeString("")
24 | ct, _ := hex.DecodeString("")
25 | aad, _ := hex.DecodeString("")
26 | tag, _ := hex.DecodeString("58e2fccefa7e3061367f1d57a4e7455a")
27 |
28 | cipher := aes.New128(key)
29 | cout, tout := Encrypt(cipher, iv, pt, aad)
30 | equals(t, ct, cout)
31 | equals(t, tag, tout)
32 | }
33 |
34 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
35 | func TestGCMEncryptGuzzi0Block(t *testing.T) {
36 | key, _ := hex.DecodeString("00000000000000000000000000000000")
37 | iv, _ := hex.DecodeString("000000000000000000000000")
38 | pt, _ := hex.DecodeString("00000000000000000000000000000000")
39 | ct, _ := hex.DecodeString("0388dace60b6a392f328c2b971b2fe78")
40 | aad, _ := hex.DecodeString("")
41 | tag, _ := hex.DecodeString("ab6e47d42cec13bdf53a67b21257bddf")
42 |
43 | cipher := aes.New128(key)
44 | cout, tout := Encrypt(cipher, iv, pt, aad)
45 | equals(t, ct, cout)
46 | equals(t, tag, tout)
47 | }
48 |
49 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
50 | func TestGCMEncryptGuzziNoAAD(t *testing.T) {
51 | key, _ := hex.DecodeString("feffe9928665731c6d6a8f9467308308")
52 | iv, _ := hex.DecodeString("cafebabefacedbaddecaf888")
53 | pt, _ := hex.DecodeString("d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" +
54 | "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255")
55 | ct, _ := hex.DecodeString("42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" +
56 | "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091473f5985")
57 | aad, _ := hex.DecodeString("")
58 | tag, _ := hex.DecodeString("4d5c2af327cd64a62cf35abd2ba6fab4")
59 |
60 | cipher := aes.New128(key)
61 | cout, tout := Encrypt(cipher, iv, pt, aad)
62 | equals(t, ct, cout)
63 | equals(t, tag, tout)
64 | }
65 |
66 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
67 | func TestGCMEncryptGuzziAAD(t *testing.T) {
68 | key, _ := hex.DecodeString("feffe9928665731c6d6a8f9467308308")
69 | iv, _ := hex.DecodeString("cafebabefacedbaddecaf888")
70 | pt, _ := hex.DecodeString("d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" +
71 | "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39")
72 | ct, _ := hex.DecodeString("42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" +
73 | "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091")
74 | aad, _ := hex.DecodeString("feedfacedeadbeeffeedfacedeadbeefabaddad2")
75 | tag, _ := hex.DecodeString("5bc94fbc3221a5db94fae95ae7121a47")
76 |
77 | cipher := aes.New128(key)
78 | cout, tout := Encrypt(cipher, iv, pt, aad)
79 | equals(t, ct, cout)
80 | equals(t, tag, tout)
81 | }
82 |
83 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
84 | func TestGCMEncryptNISTEmpty(t *testing.T) {
85 | key, _ := hex.DecodeString("11754cd72aec309bf52f7687212e8957")
86 | iv, _ := hex.DecodeString("3c819d9a9bed087615030b65")
87 | pt, _ := hex.DecodeString("")
88 | ct, _ := hex.DecodeString("")
89 | aad, _ := hex.DecodeString("")
90 | tag, _ := hex.DecodeString("250327c674aaf477aef2675748cf6971")
91 |
92 | cipher := aes.New128(key)
93 | cout, tout := Encrypt(cipher, iv, pt, aad)
94 | equals(t, ct, cout)
95 | equals(t, tag, tout)
96 | }
97 |
98 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
99 | func TestGCMEncryptNISTAADOnly(t *testing.T) {
100 | key, _ := hex.DecodeString("77be63708971c4e240d1cb79e8d77feb")
101 | iv, _ := hex.DecodeString("e0e00f19fed7ba0136a797f3")
102 | pt, _ := hex.DecodeString("")
103 | ct, _ := hex.DecodeString("")
104 | aad, _ := hex.DecodeString("7a43ec1d9c0a5a78a0b16533a6213cab")
105 | tag, _ := hex.DecodeString("209fcc8d3675ed938e9c7166709dd946")
106 |
107 | cipher := aes.New128(key)
108 | cout, tout := Encrypt(cipher, iv, pt, aad)
109 | equals(t, ct, cout)
110 | equals(t, tag, tout)
111 | }
112 |
113 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
114 | func TestGCMEncryptPOnly(t *testing.T) {
115 | key, _ := hex.DecodeString("f00fdd018c02e03576008b516ea971ad")
116 | iv, _ := hex.DecodeString("3b3e276f9e98b1ecb7ce6d28")
117 | pt, _ := hex.DecodeString("2853e66b7b1b3e1fa3d1f37279ac82be")
118 | ct, _ := hex.DecodeString("55d2da7a3fb773b8a073db499e24bf62")
119 | aad, _ := hex.DecodeString("")
120 | tag, _ := hex.DecodeString("cba06bb4f6e097199250b0d19e6e4576")
121 |
122 | cipher := aes.New128(key)
123 | cout, tout := Encrypt(cipher, iv, pt, aad)
124 | equals(t, ct, cout)
125 | equals(t, tag, tout)
126 | }
127 |
128 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
129 | func TestGCMEncryptBigBoth(t *testing.T) {
130 | key, _ := hex.DecodeString("3bb66ab4c77c70c399d4988cf1130606")
131 | iv, _ := hex.DecodeString("fd5fe227d3d1bff3d1b23b76")
132 | pt, _ := hex.DecodeString("6b63c187ff5e0fa0ffffc6493b5de747")
133 | ct, _ := hex.DecodeString("0a41ac0d07f1e2064950701995dea905")
134 | aad, _ := hex.DecodeString("6b84fa6489858a474d4196959193d115adc4bf255077412" +
135 | "abb6ec8bf7449bcc0365ca092ddfa287a3b747a2ab9e17138")
136 | tag, _ := hex.DecodeString("20d2cd594bad3a31df8f2d75f481cad0")
137 |
138 | cipher := aes.New128(key)
139 | cout, tout := Encrypt(cipher, iv, pt, aad)
140 | equals(t, ct, cout)
141 | equals(t, tag, tout)
142 | }
143 |
144 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
145 | func TestGCMDecryptGuzziEmpty(t *testing.T) {
146 | key, _ := hex.DecodeString("00000000000000000000000000000000")
147 | iv, _ := hex.DecodeString("000000000000000000000000")
148 | pt, _ := hex.DecodeString("")
149 | ct, _ := hex.DecodeString("")
150 | aad, _ := hex.DecodeString("")
151 | tag, _ := hex.DecodeString("58e2fccefa7e3061367f1d57a4e7455a")
152 |
153 | cipher := aes.New128(key)
154 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
155 | equals(t, false, failed)
156 | equals(t, pt, dout)
157 | }
158 |
159 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
160 | func TestGCMDecryptGuzzi0Block(t *testing.T) {
161 | key, _ := hex.DecodeString("00000000000000000000000000000000")
162 | iv, _ := hex.DecodeString("000000000000000000000000")
163 | pt, _ := hex.DecodeString("00000000000000000000000000000000")
164 | ct, _ := hex.DecodeString("0388dace60b6a392f328c2b971b2fe78")
165 | aad, _ := hex.DecodeString("")
166 | tag, _ := hex.DecodeString("ab6e47d42cec13bdf53a67b21257bddf")
167 |
168 | cipher := aes.New128(key)
169 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
170 | equals(t, false, failed)
171 | equals(t, pt, dout)
172 | }
173 |
174 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
175 | func TestGCMDecryptGuzziNoAAD(t *testing.T) {
176 | key, _ := hex.DecodeString("feffe9928665731c6d6a8f9467308308")
177 | iv, _ := hex.DecodeString("cafebabefacedbaddecaf888")
178 | pt, _ := hex.DecodeString("d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" +
179 | "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255")
180 | ct, _ := hex.DecodeString("42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" +
181 | "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091473f5985")
182 | aad, _ := hex.DecodeString("")
183 | tag, _ := hex.DecodeString("4d5c2af327cd64a62cf35abd2ba6fab4")
184 |
185 | cipher := aes.New128(key)
186 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
187 | equals(t, false, failed)
188 | equals(t, pt, dout)
189 | }
190 |
191 | // from http://luca-giuzzi.unibs.it/corsi/Support/papers-cryptography/gcm-spec.pdf
192 | func TestGCMDecryptGuzziAAD(t *testing.T) {
193 | key, _ := hex.DecodeString("feffe9928665731c6d6a8f9467308308")
194 | iv, _ := hex.DecodeString("cafebabefacedbaddecaf888")
195 | pt, _ := hex.DecodeString("d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" +
196 | "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39")
197 | ct, _ := hex.DecodeString("42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" +
198 | "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091")
199 | aad, _ := hex.DecodeString("feedfacedeadbeeffeedfacedeadbeefabaddad2")
200 | tag, _ := hex.DecodeString("5bc94fbc3221a5db94fae95ae7121a47")
201 |
202 | cipher := aes.New128(key)
203 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
204 | equals(t, false, failed)
205 | equals(t, pt, dout)
206 | }
207 |
208 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
209 | func TestGCMDecryptNISTEmpty(t *testing.T) {
210 | key, _ := hex.DecodeString("11754cd72aec309bf52f7687212e8957")
211 | iv, _ := hex.DecodeString("3c819d9a9bed087615030b65")
212 | pt, _ := hex.DecodeString("")
213 | ct, _ := hex.DecodeString("")
214 | aad, _ := hex.DecodeString("")
215 | tag, _ := hex.DecodeString("250327c674aaf477aef2675748cf6971")
216 |
217 | cipher := aes.New128(key)
218 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
219 | equals(t, false, failed)
220 | equals(t, pt, dout)
221 | }
222 |
223 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
224 | func TestGCMDecryptNISTAADOnly(t *testing.T) {
225 | key, _ := hex.DecodeString("77be63708971c4e240d1cb79e8d77feb")
226 | iv, _ := hex.DecodeString("e0e00f19fed7ba0136a797f3")
227 | pt, _ := hex.DecodeString("")
228 | ct, _ := hex.DecodeString("")
229 | aad, _ := hex.DecodeString("7a43ec1d9c0a5a78a0b16533a6213cab")
230 | tag, _ := hex.DecodeString("209fcc8d3675ed938e9c7166709dd946")
231 |
232 | cipher := aes.New128(key)
233 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
234 | equals(t, false, failed)
235 | equals(t, pt, dout)
236 | }
237 |
238 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
239 | func TestGCMDecryptPOnly(t *testing.T) {
240 | key, _ := hex.DecodeString("f00fdd018c02e03576008b516ea971ad")
241 | iv, _ := hex.DecodeString("3b3e276f9e98b1ecb7ce6d28")
242 | pt, _ := hex.DecodeString("2853e66b7b1b3e1fa3d1f37279ac82be")
243 | ct, _ := hex.DecodeString("55d2da7a3fb773b8a073db499e24bf62")
244 | aad, _ := hex.DecodeString("")
245 | tag, _ := hex.DecodeString("cba06bb4f6e097199250b0d19e6e4576")
246 |
247 | cipher := aes.New128(key)
248 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
249 | equals(t, false, failed)
250 | equals(t, pt, dout)
251 | }
252 |
253 | // from https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
254 | func TestGCMDecryptBigBoth(t *testing.T) {
255 | key, _ := hex.DecodeString("3bb66ab4c77c70c399d4988cf1130606")
256 | iv, _ := hex.DecodeString("fd5fe227d3d1bff3d1b23b76")
257 | pt, _ := hex.DecodeString("6b63c187ff5e0fa0ffffc6493b5de747")
258 | ct, _ := hex.DecodeString("0a41ac0d07f1e2064950701995dea905")
259 | aad, _ := hex.DecodeString("6b84fa6489858a474d4196959193d115adc4bf255077412" +
260 | "abb6ec8bf7449bcc0365ca092ddfa287a3b747a2ab9e17138")
261 | tag, _ := hex.DecodeString("20d2cd594bad3a31df8f2d75f481cad0")
262 |
263 | cipher := aes.New128(key)
264 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
265 | equals(t, false, failed)
266 | equals(t, pt, dout)
267 | }
268 |
269 | func TestGCMDecryptFails(t *testing.T) {
270 | key, _ := hex.DecodeString("3bb66ab4c77c70c399d4988cf1130606")
271 | iv, _ := hex.DecodeString("fd5fe227d3d1bff3d1b23b76")
272 | pt, _ := hex.DecodeString("6b63c187ff5e0fa0ffffc6493b5de747")
273 | ct, _ := hex.DecodeString("0a41ac0d07f1e2064950701995dea905")
274 | aad, _ := hex.DecodeString("6b84fa6489858a474d4196959193d115adc4bf255077412" +
275 | "abb6ec8bf7449bcc0365ca092ddfa287a3b747a2ab9e17138")
276 | tag, _ := hex.DecodeString("20d2cd594bad3a31df8f2d75f481cad1")
277 |
278 | cipher := aes.New128(key)
279 | dout, failed := Decrypt(cipher, iv, ct, aad, tag)
280 | equals(t, true, failed)
281 | equals(t, []byte{}, dout)
282 | _ = pt
283 | }
284 |
--------------------------------------------------------------------------------