├── .gitignore ├── cmd ├── curvetls-genkeypair │ └── main.go ├── curvetls-pingpong-client │ └── main.go └── curvetls-pingpong-server │ └── main.go ├── .project ├── Makefile ├── curvetls.go ├── wrap_test.go ├── curvezmq_test.go ├── key.go ├── README.md ├── wrap.go ├── curvezmq.go └── COPYING /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | src 3 | pkg 4 | -------------------------------------------------------------------------------- /cmd/curvetls-genkeypair/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/Rudd-O/curvetls" 6 | "log" 7 | ) 8 | 9 | func main() { 10 | pr, pu, err := curvetls.GenKeyPair() 11 | if err != nil { 12 | log.Fatalf("Could not generate keypair: %s", err) 13 | } 14 | fmt.Printf("Private key: %s\n", pr) 15 | fmt.Printf("Public key: %s\n", pu) 16 | fmt.Println("Tip: Both keys are encoded in base64 format with a one-character key type prefix") 17 | } 18 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | curvetls 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 1474938461389 14 | 15 | 10 16 | 17 | org.eclipse.ui.ide.multiFilter 18 | 1.0-projectRelativePath-matches-false-false-pkg 19 | 20 | 21 | 22 | 1474938461395 23 | 24 | 10 25 | 26 | org.eclipse.ui.ide.multiFilter 27 | 1.0-projectRelativePath-matches-false-false-bin 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: deps fmt 2 | 3 | deplist = src/github.com/golang/crypto \ 4 | src/github.com/Rudd-O/curvetls 5 | 6 | objlist = bin/curvetls-genkeypair \ 7 | bin/curvetls-pingpong-client \ 8 | bin/curvetls-pingpong-server 9 | 10 | all: $(objlist) 11 | 12 | deps: $(deplist) 13 | 14 | src/github.com/Rudd-O/curvetls: 15 | mkdir -p `dirname $@` 16 | ln -s ../../.. $@ 17 | 18 | src/github.com/%: 19 | mkdir -p `dirname $@` 20 | cd `dirname $@` && git clone `echo $@ | sed 's|src/|https://|'` 21 | if [[ $@ == src/github.com/golang* ]] ; then mkdir -p src/golang.org/x ; ln -sf ../../../$@ src/golang.org/x/ ; fi 22 | 23 | bin/%: deps 24 | GOPATH=$(PWD) go install github.com/Rudd-O/curvetls/cmd/`echo $@ | sed 's|bin/||'` 25 | 26 | fmt: 27 | for f in *.go cmd/*/*.go ; do gofmt -w "$$f" || exit 1 ; done 28 | 29 | run-pingpong: all 30 | bin/curvetls-pingpong-server 127.0.0.1:9001 pb2GtjnuIuTH+hayKtRcTMg7O0fac7GP+/v9FgOqQd+w= PyDdLt+wYELY9U7NyxJZVuGcStGW7axlt6sfrBaqsvCo= & pid=$$! ; sleep 0.1 ; bin/curvetls-pingpong-client 127.0.0.1:9001 pJdaFzGD2eRN6z3DziBErbzGeriy9WK5kN+sEIiqMzpY= PiYnKerHceX2ePqRYOiKb/mDooP4RyfdIFljC6Fgw2Rg= PyDdLt+wYELY9U7NyxJZVuGcStGW7axlt6sfrBaqsvCo= ; wait $$pid 31 | 32 | test: 33 | GOPATH=$(PWD) go test 34 | 35 | bench: 36 | GOPATH=$(PWD) go test -bench=. 37 | -------------------------------------------------------------------------------- /curvetls.go: -------------------------------------------------------------------------------- 1 | // Package curvetls is a simple, robust transport encryption library. 2 | // 3 | // This is a pluggable wrapper (client / server) for network I/O, which 4 | // allows you to upgrade your regular network sockets to a protocol that 5 | // supports robust framing, transport security and authentication, 6 | // so long as your net.Conn is of any reliable kind (e.g. a TCP- or 7 | // file-backed net.Conn). 8 | // 9 | // Usage Instructions 10 | // 11 | // (a) Generate keypairs for clients and server, persisting them to disk if 12 | // you want to, so you can later load them again. 13 | // 14 | // (b) Distribute, however you see fit, the public keys of the server to the 15 | // clients, and the public keys of the clients to the server. 16 | // 17 | // (c) Generate one long nonce per server keypair, and one long nonce per 18 | // client keypair. You can do this at runtime. Never reuse the 19 | // same long nonce for two different keypairs. 20 | // 21 | // (d) Make your server Listen() on a TCP socket, and Accept() incoming 22 | // connections to obtain one or more server net.Conn. 23 | // 24 | // (e) Make your clients Connect() on a TCP socket to the Listen() address 25 | // of the server. 26 | // 27 | // (f) On your client, right after Connect(), wrap the net.Conn you received 28 | // by using WrapClient() on that client net.Conn, and giving it the client 29 | // keypair, its corresponding client long nonce, and the server public key. 30 | // WrapClient() will return an encrypted socket you can use to talk to 31 | // the server. 32 | // 33 | // (g) On your server, right after Accept(), wrap the net.Conn you received 34 | // by using WrapServer() on that server net.Conn, and giving it 35 | // the server keypair together with its corresponding server long nonce. 36 | // Use the authorizer and the public key that WrapServer() returns to 37 | // decide whether to call Allow() or Deny() on the authorizer. Allow() 38 | // will return an encrypted socket you can use to talk to the client. 39 | // 40 | // Congratulations, at this point you have a connection between peers that 41 | // is encrypted with (a limited version of) the CurveZMQ protocol. 42 | // 43 | // Sending and receiving traffic is covered by the documentation of the 44 | // Read(), ReadFrame() and Write() methods of EncryptedConn. Two 45 | // example programs are included in the cmd/ directory of this package. 46 | package curvetls 47 | -------------------------------------------------------------------------------- /cmd/curvetls-pingpong-client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Rudd-O/curvetls" 5 | "log" 6 | "net" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | if len(os.Args) < 5 { 12 | log.Fatalf("usage: curvetls-client ") 13 | } 14 | 15 | connect := os.Args[1] 16 | clientPrivkey, err := curvetls.PrivkeyFromString(os.Args[2]) 17 | if err != nil { 18 | log.Fatalf("Client: failed to parse client private key: %s", err) 19 | } 20 | clientPubkey, err := curvetls.PubkeyFromString(os.Args[3]) 21 | if err != nil { 22 | log.Fatalf("Client: failed to parse client public key: %s", err) 23 | } 24 | serverPubkey, err := curvetls.PubkeyFromString(os.Args[4]) 25 | if err != nil { 26 | log.Fatalf("Client: failed to parse server public key: %s", err) 27 | } 28 | 29 | socket, err := net.Dial("tcp4", connect) 30 | if err != nil { 31 | log.Fatalf("Client: failed to connect to socket: %s", err) 32 | } 33 | 34 | long_nonce, err := curvetls.NewLongNonce() 35 | if err != nil { 36 | log.Fatalf("Failed to generate nonce: %s", err) 37 | } 38 | ssocket, err := curvetls.WrapClient(socket, clientPrivkey, clientPubkey, serverPubkey, long_nonce) 39 | if err != nil { 40 | if curvetls.IsAuthenticationError(err) { 41 | log.Fatalf("Client: server says unauthorized: %s", err) 42 | } else { 43 | log.Fatalf("Client: failed to wrap socket: %s", err) 44 | } 45 | } 46 | 47 | if err == nil { 48 | _, err = ssocket.Write([]byte("ghi jkl")) 49 | if err != nil { 50 | log.Fatalf("Client: failed to write to wrapped socket: %s", err) 51 | } 52 | 53 | log.Printf("Client: wrote ghi jkl to wrapped socket") 54 | 55 | var packet [8]byte 56 | var smallPacket [8]byte 57 | 58 | _, err = ssocket.Read(packet[:]) 59 | if err != nil { 60 | log.Fatalf("Client: failed to read from wrapped socket: %s", err) 61 | } 62 | 63 | log.Printf("Client: the first received packet is %s", packet) 64 | 65 | _, err = ssocket.Write([]byte("GHI JKL STU VWX ")) 66 | if err != nil { 67 | log.Fatalf("Client: failed to write to wrapped socket: %s", err) 68 | } 69 | 70 | log.Printf("Client: wrote GHI JKL STU VWX to wrapped socket") 71 | 72 | n, err := ssocket.Read(smallPacket[:]) 73 | if err != nil { 74 | log.Fatalf("Client: failed to read from wrapped socket: %s", err) 75 | } 76 | 77 | log.Printf("Client: the second received first part of packet is %s", smallPacket[:n]) 78 | 79 | n, err = ssocket.Read(smallPacket[:]) 80 | if err != nil { 81 | log.Fatalf("Server: failed to read from wrapped socket: %s", err) 82 | } 83 | 84 | log.Printf("Client: the second received second part of packet is %s", smallPacket[:n]) 85 | 86 | _, err = ssocket.Write([]byte("SHORT")) 87 | if err != nil { 88 | log.Fatalf("Client: failed to write to wrapped socket: %s", err) 89 | } 90 | 91 | log.Printf("Client: wrote SHORT to wrapped socket") 92 | 93 | short, err := ssocket.ReadFrame() 94 | if err != nil { 95 | log.Fatalf("Client: failed to read from wrapped socket: %s", err) 96 | } 97 | 98 | log.Printf("Client: the frame received is %s", short) 99 | 100 | err = ssocket.Close() 101 | if err != nil { 102 | log.Fatalf("Client: failed to close socket: %s", err) 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /wrap_test.go: -------------------------------------------------------------------------------- 1 | package curvetls 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "testing" 7 | ) 8 | 9 | type Fataler interface { 10 | Fatal(...interface{}) 11 | } 12 | 13 | func keys(t Fataler) (sPriv Privkey, sPub Pubkey, 14 | cPriv Privkey, cPub Pubkey, 15 | sK precomputedKey, cK precomputedKey) { 16 | var err error 17 | sPriv, sPub, err = GenKeyPair() 18 | if err != nil { 19 | t.Fatal(err) 20 | } 21 | cPriv, cPub, err = GenKeyPair() 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | sK = precomputeKey(sPriv, sPub) 26 | cK = precomputeKey(cPriv, cPub) 27 | return 28 | } 29 | 30 | func nonces() (sN, cN *shortNonce) { 31 | sN, cN = newShortNonce(), newShortNonce() 32 | return 33 | } 34 | 35 | type parms struct { 36 | sPriv Privkey 37 | sPub Pubkey 38 | cPriv Privkey 39 | cPub Pubkey 40 | sK precomputedKey 41 | cK precomputedKey 42 | sN *shortNonce 43 | cN *shortNonce 44 | } 45 | 46 | func validParms(t Fataler) *parms { 47 | sPriv, sPub, cPriv, cPub, sK, cK := keys(t) 48 | sN, cN := nonces() 49 | return &parms{sPriv, sPub, cPriv, cPub, sK, cK, sN, cN} 50 | } 51 | 52 | func validMessageFrame(t *testing.T, p *parms, payload []byte) (f *messageCommand) { 53 | var err error 54 | 55 | f = &messageCommand{} 56 | err = f.build(p.sN, &p.sK, payload, true) 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | 61 | out, err := f.validate(p.cN, &p.cK, true) 62 | if err != nil { 63 | t.Fatal(err) 64 | } 65 | 66 | if bytes.Compare(payload, out) != 0 { 67 | t.Fatalf("%s != %s", payload, out) 68 | } 69 | return 70 | } 71 | 72 | // fixedNonce is a type of nonce that never increments. 73 | // 74 | // This allows me to supply it to functions that bump the nonce, but 75 | // have it never bump. 76 | type fixedNonce struct { 77 | sn *shortNonce 78 | fixedValue uint64 79 | } 80 | 81 | func (s *fixedNonce) prefixAndBump(prefix [16]byte) ([24]byte, [8]byte, error) { 82 | s.sn.counter = 0 83 | long, prev, err := s.sn.prefixAndBump(prefix) 84 | if err != nil { 85 | return long, prev, err 86 | } 87 | s.sn.counter = s.fixedValue 88 | binary.BigEndian.PutUint64(long[len(prefix):], s.fixedValue) 89 | binary.BigEndian.PutUint64(prev[:], s.fixedValue-1) 90 | return long, prev, nil 91 | } 92 | 93 | func newFixedNonce(val uint64) *fixedNonce { 94 | return &fixedNonce{newShortNonce(), val} 95 | } 96 | 97 | func TestMessageNonceOverflow(t *testing.T) { 98 | p := validParms(t) 99 | f := validMessageFrame(t, p, []byte("sup")) 100 | 101 | // Testing that message build fails when nonce overflows 102 | // Decrement the counter, which is at 1, to make it MAXUINT64-1 103 | p.sN.counter -= 2 104 | err := f.build(p.sN, &p.sK, []byte("sup"), true) 105 | if err != errNonceOverflow { 106 | t.Errorf("%s != %s", err, errNonceOverflow) 107 | } 108 | 109 | // Testing that message validate fails when nonce overflows 110 | // Fix the server counter so that the outgoing nonce is 0. 111 | sN := newFixedNonce(0) 112 | err = f.build(sN, &p.sK, []byte("sup"), true) 113 | if err != nil { 114 | t.Errorf("err != nil: %s", err) 115 | } 116 | // Then arrange such that the receiving side has a MAXUINT64-1 117 | // nonce. This should technically "overflow" to 0, but the 118 | // routine that does the work should detect that and raise an error. 119 | p.cN.counter = 0 120 | p.cN.counter -= 1 121 | _, err = f.validate(p.cN, &p.cK, true) 122 | if err != errNonceOverflow { 123 | t.Errorf("%s != %s", err, errNonceOverflow) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /cmd/curvetls-pingpong-server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Rudd-O/curvetls" 5 | "log" 6 | "net" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | if len(os.Args) < 4 || len(os.Args) > 5 { 12 | log.Fatalf("usage: curvetls-server [client pubkey]") 13 | } 14 | 15 | bind := os.Args[1] 16 | serverPrivkey, err := curvetls.PrivkeyFromString(os.Args[2]) 17 | if err != nil { 18 | log.Fatalf("Server: failed to parse server private key: %s", err) 19 | } 20 | serverPubkey, err := curvetls.PubkeyFromString(os.Args[3]) 21 | if err != nil { 22 | log.Fatalf("Server: failed to parse server public key: %s", err) 23 | } 24 | var noPubkey curvetls.Pubkey 25 | var clientPubkey curvetls.Pubkey 26 | if len(os.Args) == 5 { 27 | clientPubkey, err = curvetls.PubkeyFromString(os.Args[4]) 28 | if err != nil { 29 | log.Fatalf("Server: failed to parse client public key: %s", err) 30 | } 31 | } else { 32 | clientPubkey = noPubkey 33 | } 34 | 35 | listener, err := net.Listen("tcp4", bind) 36 | if err != nil { 37 | log.Fatalf("Server: could not run server: %s", err) 38 | } 39 | 40 | socket, err := listener.Accept() 41 | if err != nil { 42 | log.Fatalf("Server: failed to accept socket: %s", err) 43 | } 44 | 45 | long_nonce, err := curvetls.NewLongNonce() 46 | if err != nil { 47 | log.Fatalf("Server: failed to generate nonce: %s", err) 48 | } 49 | authorizer, clientpubkey, err := curvetls.WrapServer(socket, serverPrivkey, serverPubkey, long_nonce) 50 | if err != nil { 51 | log.Fatalf("Server: failed to wrap socket: %s", err) 52 | } 53 | log.Printf("Server: client's public key is %s", clientpubkey) 54 | 55 | var ssocket *curvetls.EncryptedConn 56 | 57 | var allowed bool 58 | if clientPubkey == noPubkey { 59 | ssocket, err = authorizer.Allow() 60 | allowed = true 61 | } else if clientPubkey == clientpubkey { 62 | ssocket, err = authorizer.Allow() 63 | allowed = true 64 | } else { 65 | err = authorizer.Deny() 66 | allowed = false 67 | } 68 | 69 | if err != nil { 70 | log.Fatalf("Server: failed to process authorization: %s", err) 71 | } 72 | 73 | if allowed { 74 | var packet [8]byte 75 | var smallPacket [8]byte 76 | 77 | _, err = ssocket.Read(packet[:]) 78 | if err != nil { 79 | log.Fatalf("Server: failed to read from wrapped socket: %s", err) 80 | } 81 | 82 | log.Printf("Server: the first received packet is %s", packet) 83 | 84 | _, err = ssocket.Write([]byte("abc def")) 85 | if err != nil { 86 | log.Fatalf("Server: failed to write to wrapped socket: %s", err) 87 | } 88 | 89 | log.Printf("Server: wrote abc def to wrapped socket") 90 | 91 | n, err := ssocket.Read(smallPacket[:]) 92 | if err != nil { 93 | log.Fatalf("Server: failed to read from wrapped socket: %s", err) 94 | } 95 | 96 | log.Printf("Server: the second received first part of packet is %s", smallPacket[:n]) 97 | 98 | n, err = ssocket.Read(smallPacket[:]) 99 | if err != nil { 100 | log.Fatalf("Server: failed to read from wrapped socket: %s", err) 101 | } 102 | 103 | log.Printf("Server: the second received second part of packet is %s", smallPacket[:n]) 104 | 105 | _, err = ssocket.Write([]byte("ABC DEF MNO PQR")) 106 | if err != nil { 107 | log.Fatalf("Server: failed to write to wrapped socket: %s", err) 108 | } 109 | 110 | log.Printf("Server: wrote ABC DEF MNO PQR to wrapped socket") 111 | 112 | short, err := ssocket.ReadFrame() 113 | if err != nil { 114 | log.Fatalf("Server: failed to read from wrapped socket: %s", err) 115 | } 116 | 117 | log.Printf("Server: the frame received is %s", short) 118 | 119 | _, err = ssocket.Write([]byte("SHORT")) 120 | if err != nil { 121 | log.Fatalf("Server: failed to write to wrapped socket: %s", err) 122 | } 123 | 124 | log.Printf("Server: wrote SHORT to wrapped socket") 125 | 126 | err = ssocket.Close() 127 | if err != nil { 128 | log.Fatalf("Server: failed to close socket: %s", err) 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /curvezmq_test.go: -------------------------------------------------------------------------------- 1 | package curvetls 2 | 3 | import ( 4 | "golang.org/x/crypto/nacl/box" 5 | "testing" 6 | ) 7 | 8 | func benchmarkMessageEncrypt(msgsize int, b *testing.B) { 9 | b.SetBytes(int64(msgsize)) 10 | p, f := validParms(b), &messageCommand{} 11 | in := make([]byte, msgsize) 12 | inS := in[:] 13 | var err error 14 | for n := 0; n < b.N; n++ { 15 | f.build(p.sN, &p.sK, inS, true) 16 | } 17 | if err != nil { 18 | b.Fatal(err) 19 | } 20 | } 21 | 22 | func benchmarkMessageDecrypt(msgsize int, b *testing.B) { 23 | b.SetBytes(int64(msgsize)) 24 | p, f := validParms(b), &messageCommand{} 25 | in := make([]byte, msgsize) 26 | f.build(p.sN, &p.sK, in[:], true) 27 | var err error 28 | for n := 0; n < b.N; n++ { 29 | _, err = f.validate(p.cN, &p.cK, true) 30 | p.cN.counter -= 1 31 | } 32 | if err != nil { 33 | b.Fatal(err) 34 | } 35 | } 36 | 37 | func benchmarkNaclKeypairEnc(msgsize int, precomputed bool, b *testing.B) { 38 | b.SetBytes(int64(msgsize)) 39 | p, _ := validParms(b), &messageCommand{} 40 | in := make([]byte, msgsize) 41 | var nonce [24]byte 42 | sPriv := [32]byte(p.sPriv) 43 | cPub := [32]byte(p.cPub) 44 | sK := [32]byte(p.sK) 45 | if precomputed { 46 | for n := 0; n < b.N; n++ { 47 | box.SealAfterPrecomputation(nil, in, &nonce, &sK) 48 | } 49 | } else { 50 | for n := 0; n < b.N; n++ { 51 | box.Seal(nil, in, &nonce, &sPriv, &cPub) 52 | } 53 | } 54 | } 55 | 56 | func benchmarkNaclKeypairDec(msgsize int, precomputed bool, b *testing.B) { 57 | b.SetBytes(int64(msgsize)) 58 | p, _ := validParms(b), &messageCommand{} 59 | in := make([]byte, msgsize+box.Overhead) 60 | var nonce [24]byte 61 | sPriv := [32]byte(p.sPriv) 62 | cPub := [32]byte(p.cPub) 63 | sK := [32]byte(p.sK) 64 | if precomputed { 65 | for n := 0; n < b.N; n++ { 66 | box.OpenAfterPrecomputation(nil, in, &nonce, &sK) 67 | } 68 | } else { 69 | for n := 0; n < b.N; n++ { 70 | box.Open(nil, in, &nonce, &sPriv, &cPub) 71 | } 72 | } 73 | } 74 | 75 | func BenchmarkMessageEncrypt1B(b *testing.B) { benchmarkMessageEncrypt(1, b) } 76 | func BenchmarkMessageEncrypt64B(b *testing.B) { benchmarkMessageEncrypt(64, b) } 77 | func BenchmarkMessageEncrypt1KB(b *testing.B) { benchmarkMessageEncrypt(1024, b) } 78 | func BenchmarkMessageEncrypt64KB(b *testing.B) { benchmarkMessageEncrypt(1024*64, b) } 79 | func BenchmarkMessageEncrypt1MB(b *testing.B) { benchmarkMessageEncrypt(1024*1024, b) } 80 | func BenchmarkMessageEncrypt64MB(b *testing.B) { benchmarkMessageEncrypt(64*1024*1024, b) } 81 | 82 | func BenchmarkMessageDecrypt1B(b *testing.B) { benchmarkMessageDecrypt(1, b) } 83 | func BenchmarkMessageDecrypt64B(b *testing.B) { benchmarkMessageDecrypt(64, b) } 84 | func BenchmarkMessageDecrypt1KB(b *testing.B) { benchmarkMessageDecrypt(1024, b) } 85 | func BenchmarkMessageDecrypt64KB(b *testing.B) { benchmarkMessageDecrypt(1024*64, b) } 86 | func BenchmarkMessageDecrypt1MB(b *testing.B) { benchmarkMessageDecrypt(1024*1024, b) } 87 | func BenchmarkMessageDecrypt64MB(b *testing.B) { benchmarkMessageDecrypt(64*1024*1024, b) } 88 | 89 | func BenchmarkNaclKeypairEnc1B(b *testing.B) { benchmarkNaclKeypairEnc(1, false, b) } 90 | func BenchmarkNaclKeypairEnc64KB(b *testing.B) { benchmarkNaclKeypairEnc(64*1024, false, b) } 91 | func BenchmarkNaclKeypairEnc64MB(b *testing.B) { benchmarkNaclKeypairEnc(64*1024*1024, false, b) } 92 | 93 | func BenchmarkNaclKeypairDec1B(b *testing.B) { benchmarkNaclKeypairDec(1, true, b) } 94 | func BenchmarkNaclKeypairDec64KB(b *testing.B) { benchmarkNaclKeypairDec(64*1024, true, b) } 95 | func BenchmarkNaclKeypairDec64MB(b *testing.B) { benchmarkNaclKeypairDec(64*1024*1024, true, b) } 96 | 97 | func BenchmarkNaclPrecomputedEnc1B(b *testing.B) { benchmarkNaclKeypairDec(1, true, b) } 98 | func BenchmarkNaclPrecomputedEnc64KB(b *testing.B) { benchmarkNaclKeypairDec(64*1024, true, b) } 99 | func BenchmarkNaclPrecomputedEnc64MB(b *testing.B) { benchmarkNaclKeypairDec(64*1024*1024, true, b) } 100 | 101 | func BenchmarkNaclPrecomputedDec1B(b *testing.B) { benchmarkNaclKeypairDec(1, true, b) } 102 | func BenchmarkNaclPrecomputedDec64KB(b *testing.B) { benchmarkNaclKeypairDec(64*1024, true, b) } 103 | func BenchmarkNaclPrecomputedDec64MB(b *testing.B) { benchmarkNaclKeypairDec(64*1024*1024, true, b) } 104 | -------------------------------------------------------------------------------- /key.go: -------------------------------------------------------------------------------- 1 | package curvetls 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/base64" 6 | "fmt" 7 | "golang.org/x/crypto/nacl/box" 8 | ) 9 | 10 | type key [32]byte 11 | 12 | func keyFromString(s string, t string) (p [32]byte, err error) { 13 | if len(s) < 1 { 14 | return p, fmt.Errorf("%s key is too short", t) 15 | } 16 | if t == "private" { 17 | if s[0] != 'p' { 18 | if s[0] == 'P' { 19 | return p, fmt.Errorf("%s key %s appears to be a public key", t, s) 20 | } 21 | return p, fmt.Errorf("%s key %s is not valid", t, s) 22 | } 23 | } else if t == "public" { 24 | if s[0] != 'P' { 25 | if s[0] == 'p' { 26 | return p, fmt.Errorf("%s key %s appears to be a private key", t, s) 27 | } 28 | return p, fmt.Errorf("%s key %s is not valid", t, s) 29 | } 30 | } 31 | s = s[1:] 32 | data, err := base64.StdEncoding.DecodeString(s) 33 | if err != nil { 34 | return p, err 35 | } 36 | if len(data) != 32 { 37 | return p, fmt.Errorf("%s key %s does not decode to 32 bytes", t, s) 38 | } 39 | copy(p[:], data) 40 | return p, nil 41 | } 42 | 43 | func keyFromSlice(s []byte, t string) (p [32]byte, err error) { 44 | if len(s) != 32 { 45 | return p, fmt.Errorf("%s key %s is not 32 bytes long", t, s) 46 | } 47 | copy(p[:], s) 48 | return p, nil 49 | } 50 | 51 | // Privkey is an opaque type representing a private key as used in curvetls. 52 | type Privkey key 53 | 54 | func privkeyFromSlice(s []byte) (p Privkey, err error) { 55 | return keyFromSlice(s, "private") 56 | } 57 | 58 | // PubkeyFromString deserializes a Pubkey as supplied in the string. 59 | // See Pubkey.String() for information on the string format of Pubkeys. 60 | // 61 | // String format of Privkey is the letter p plus a base64 rendering 62 | // of 32 bytes. 63 | func PubkeyFromString(s string) (p Pubkey, err error) { 64 | return keyFromString(s, "public") 65 | } 66 | 67 | // String format of Privkey is the letter "p" plus a base64 rendering 68 | // of 32 bytes. 69 | func (k Privkey) String() string { 70 | return "p" + base64.StdEncoding.EncodeToString(k[:]) 71 | } 72 | 73 | // Pubkey is an opaque type representing a public key as used in curvetls. 74 | type Pubkey key 75 | 76 | func pubkeyFromSlice(s []byte) (p Pubkey, err error) { 77 | return keyFromSlice(s, "public") 78 | } 79 | 80 | // PrivkeyFromString deserializes a Privkey as supplied in the string. 81 | // See Privkey.String() for information on the string format of Privkeys. 82 | func PrivkeyFromString(s string) (p Privkey, err error) { 83 | return keyFromString(s, "private") 84 | } 85 | 86 | // String format of Privkey is the letter "P" plus a base64 rendering 87 | // of 32 bytes. 88 | func (k Pubkey) String() string { 89 | return "P" + base64.StdEncoding.EncodeToString(k[:]) 90 | } 91 | 92 | // GenKeyPair generates a pair of private and public keys as 93 | // Privkey and Pubkey structs. 94 | // 95 | // It is safe to invoke this function concurrently. 96 | func GenKeyPair() (Privkey, Pubkey, error) { 97 | public, private, err := box.GenerateKey(rand.Reader) 98 | if err != nil { 99 | return Privkey{}, Pubkey{}, err 100 | } 101 | pu, err := pubkeyFromSlice(public[:]) 102 | if err != nil { 103 | return Privkey{}, Pubkey{}, err 104 | } 105 | pr, err := privkeyFromSlice(private[:]) 106 | if err != nil { 107 | return Privkey{}, Pubkey{}, err 108 | } 109 | return pr, pu, err 110 | } 111 | 112 | type permanentServerPrivkey Privkey 113 | 114 | type permanentServerPubkey Pubkey 115 | 116 | type permanentClientPrivkey Privkey 117 | 118 | type permanentClientPubkey Pubkey 119 | 120 | type ephemeralServerPrivkey Privkey 121 | 122 | type ephemeralServerPubkey Pubkey 123 | 124 | type ephemeralClientPrivkey Privkey 125 | 126 | type ephemeralClientPubkey Pubkey 127 | 128 | type precomputedKey key 129 | 130 | func genEphemeralClientKeyPair() (ephemeralClientPrivkey, ephemeralClientPubkey, error) { 131 | privk, pubk, err := GenKeyPair() 132 | return ephemeralClientPrivkey(privk), ephemeralClientPubkey(pubk), err 133 | } 134 | 135 | func genEphemeralServerKeyPair() (ephemeralServerPrivkey, ephemeralServerPubkey, error) { 136 | privk, pubk, err := GenKeyPair() 137 | return ephemeralServerPrivkey(privk), ephemeralServerPubkey(pubk), err 138 | } 139 | 140 | func precomputeKey(priv Privkey, pub Pubkey) precomputedKey { 141 | cpriv := [32]byte(priv) 142 | cpub := [32]byte(pub) 143 | var sk precomputedKey 144 | csk := [32]byte(sk) 145 | box.Precompute(&csk, &cpub, &cpriv) 146 | return sk 147 | } 148 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # curvetls: a simple, robust transport encryption package 2 | 3 | curvetls is a Go library that gives you a robust framing and encryption 4 | layer for your Go programs, striving to be secure, strict, and simple. 5 | 6 | With curvetls, it's dead easy to go from ordinary sockets to secure 7 | encrypted channels that support framing. This makes it trivial for you 8 | to write secure, robust clients and servers that do not need to implement 9 | low-level control flow. curvetls does not use large or unproven libraries, 10 | avoids unsafe C bindings, follows well-documented specifications, practices 11 | well-understood cryptography, and avoids placing undue trust in peers, 12 | even authenticated ones. 13 | 14 | This library gives you a layered, stackable wrapper (client / server) for 15 | network I/O, which allows you to upgrade regular network sockets to the 16 | curvetls protocol. All the wrapper needs is a key pair, a random nonce, 17 | and a socket whose underlying transport is of any reliable kind (e.g. 18 | a TCP- or file-backed `net.Conn`). 19 | 20 | curvetls is documented with developers' interests in mind. 21 | [Take a look at the documentation online](https://godoc.org/github.com/Rudd-O/curvetls). 22 | Alternatively, clone this repository, then run `godoc` against it. 23 | 24 | ## Features 25 | 26 | * Simple and robust 27 | [elliptic curve encryption](https://godoc.org/golang.org/x/crypto/nacl/box) 28 | of communications between peers. 29 | * Well-defined, robust framing scheme for reliable delivery of whole messages, 30 | based on the 31 | [ZeroMQ ZMTP specification](https://rfc.zeromq.org/spec:37/ZMTP/). 32 | * Robust public key authentication scheme to let servers decide which clients 33 | are authorized to proceed, based on the 34 | [CurveZMQ spec](https://rfc.zeromq.org/spec:37/ZMTP/). 35 | * Straightforward use of the library in your network clients and servers. 36 | 37 | ## Test client programs 38 | 39 | In addition to the library, this project ships three demon programs, 40 | which can show you how to use the library: 41 | 42 | * `curvetls-genkeypair` generates keypairs for the use of the other 43 | command-line programs 44 | * `curvetls-pingpong-server` implements a test ping-pong server 45 | * `curvetls-pingpong-client` implements a test ping-pong client 46 | 47 | To run these programs, you can simply compile the library after 48 | cloning it to the local directory: 49 | 50 | [user@host ~]$ cd /path/to/curvetls 51 | [user@host curvetls]$ make 52 | [user@host curvetls]$ 53 | 54 | Generate some key pairs: 55 | 56 | [user@host curvetls]$ bin/curvetls-genkeypair # note these for the server 57 | Private key: pT6GGmPNgSPsGKD8UTPdVN50xOGeZr+eb53gfAYoeVm4= 58 | Public key: Puwo38S2npQijFuh5cuShYpTnQ+ZupkwveS/A1HjjkSY= 59 | Tip: Both keys are encoded in base64 format with a one-character key type prefix 60 | [user@host curvetls]$ bin/curvetls-genkeypair # note these for the client 61 | Private key: paICEhaq2fBJkCRoIMbncQ2sv+LolEvjgM43DYcrQpqM= 62 | Public key: Pr59DbWYjUHlj0Z8kAY9LUyP/8hUi5kC+ByX6xvPKIwc= 63 | Tip: Both keys are encoded in base64 format with a one-character key type prefix 64 | [user@host curvetls]$ 65 | 66 | Run the server (in the background): 67 | 68 | [user@host curvetls]$ bin/curvetls-pingpong-server 127.0.0.1:9001 \ 69 | pT6GGmPNgSPsGKD8UTPdVN50xOGeZr+eb53gfAYoeVm4= \ 70 | Puwo38S2npQijFuh5cuShYpTnQ+ZupkwveS/A1HjjkSY= \ 71 | Pr59DbWYjUHlj0Z8kAY9LUyP/8hUi5kC+ByX6xvPKIwc= & 72 | 73 | Run the client: 74 | 75 | [user@host curvetls]$ bin/curvetls-pingpong-client 127.0.0.1:9001 \ 76 | paICEhaq2fBJkCRoIMbncQ2sv+LolEvjgM43DYcrQpqM= \ 77 | Pr59DbWYjUHlj0Z8kAY9LUyP/8hUi5kC+ByX6xvPKIwc= \ 78 | Puwo38S2npQijFuh5cuShYpTnQ+ZupkwveS/A1HjjkSY= 79 | 80 | And see the ping-pong happen. The server will exit as soon as it is 81 | done with the first connection. 82 | 83 | Feel free to Wireshark the programs as 84 | they execute, to verify that data is, in fact, being encrypted as it 85 | goes from program to program. 86 | 87 | Run the programs with no arguments to get usage information. 88 | 89 | ## Quality, testing and benchmarking 90 | 91 | To run the tests: 92 | 93 | make test 94 | 95 | To run a variety of benchmarks (such as message encryption and decryption): 96 | 97 | make bench 98 | 99 | curvetls releases should not come with failing tests. If a test fails, 100 | that is a problem and you should report it as an issue right away. 101 | 102 | ## Goals and motivations 103 | 104 | As security software, curvetls has the following goals: 105 | 106 | * To enable users of this library to depend on as little code as possible, 107 | with special emphasis on reducing unsafe code. 108 | * To give implementors a simple way to enable encryption between two peers, 109 | with as little effort as possible. 110 | * To make sure that implementors do not have to deal with any low-level 111 | details that they may screw up, compromising the security of their programs. 112 | * To ensure that users of this library do not have to deal with hidden 113 | surprises, such as servers allowing clients to allocate unbound resources. 114 | 115 | curvetls focuses on getting the low-level security details right, so that 116 | you do not have to. 117 | 118 | ### Why curvetls instead of `net.tls`? 119 | 120 | Some people have asked why this library needs to exist, given that Go has 121 | `net/tls`, which is a high-performance crypto library. 122 | 123 | The answer is that `net/tls` is much, much more than just a crypto library, 124 | and that has implications for security and complexity. There's a niche in 125 | communications where TLS is overkill but plain TCP is irresponsible, and 126 | that is a niche which many packages have attempted to fill, from CurveCP 127 | to tcpcrypt. curvetls fills this niche quite nicely. 128 | 129 | The list-form, practical answer to why you may want to avoid `net/tls`: 130 | 131 | * A PKI system with certificates imposes on the implementor the additional 132 | burden of having to manage the certificate authority that emits the 133 | certificates, possibly a revocation infrastructure, both for clients and 134 | servers. 135 | * PKI as implemented in the modern world, including in `net/tls`, is a 136 | bit of a mess in that you have to write extra code if you want to do 137 | something that's outside the norm, but still perfectly sensible for certain 138 | use cases. Like, say, have clients reject certificates not signed by 139 | VeriSign, or have full cert validation without domain name validation. 140 | This demands configuration code that you *must* get right in your program. 141 | * X.509 certificates are very complex compared to simple base64 142 | strings (what this library uses). There have been vulnerabilities, 143 | sometimes years-old, in certificate parsing code. 144 | * TLS itself is highly complex, because of backwards compatibility reasons 145 | and the need to support many ciphers. This complexity has given rise to 146 | many security issues as well as many opportunities for the implementor 147 | to shoot himself on the foot. This is 100% unneeded complexity if all you 148 | want is to send / receive well-encrypted data between two private peers. 149 | 150 | TLS is fine and dandy, very well supported in Go via the `net/tls` package, 151 | and many use cases effectively require you to use TLS. However, TLS brings 152 | in a *lot* more complexity than just handshake plus NaCL encryption, and 153 | that increases the attack surface. Sometimes all you need is a simple 154 | drop-in implementation of peer-to-peer public key crypto. That's what 155 | curvetls aims to do well. I think four lines of (non-error handling) code 156 | — one for creating a keypair, one for creating a nonce, one for driving 157 | the handshake, and one for authorizing the client — is as simple as it can 158 | get, and the code that runs underneath is far less complex than anything 159 | you get with invoking any of `net.tls` for the same use case. 160 | 161 | ### Why are you rolling your own crypto code / protocol? 162 | 163 | Let's be 100% blunt: curvetls does *not* roll its own crypto. The crypto 164 | in curvetls is the same crypto as the NaCL library, which is fast, 165 | well-tested and presumed to be strong. 166 | 167 | curvetls also does *not* roll its own protocol. One of the goals of curvetls 168 | is to be interoperable with CurveZMQ DEALER sockets in reliable mode 169 | (e.g. TCP). As such, we implement the pertinent specification, which are 170 | very good specifications — 100% unambiguous — and enjoy many implementations 171 | from competing entities. 172 | 173 | curvetls users also enjoy the client / server handshake and send / receive 174 | framing that is the great work of the ZeroMQ folks (to my knowledge, 175 | primarily Pieter Hintjens). In practical terms, this means you, as a user 176 | of curvetls, do not have to worry about authentication / authorization 177 | state machines or incomplete messages. A peer is either authorized or not. 178 | A message is either fully-received or not. 179 | 180 | ### Why not CurveZMQ instead? 181 | 182 | ZeroMQ is great software, but it has three problems, one Go-specific and 183 | two more in general w.r.t. security: 184 | 185 | **Problem numero uno**: you can't really send on a ZeroMQ socket in a 186 | goroutine while receiving on that same socket in another goroutine. 187 | [Your program will crash if you do](https://github.com/pebbe/zmq3/issues/21#issuecomment-68414300). 188 | This is fundamental if you want to have a program that sends and 189 | receives at the same time, without having to "take turns", HTTP style. 190 | There's ways you can get around that — 191 | [PAIR inproc socket pairs](http://stackoverflow.com/questions/36437799/how-to-deal-with-zmq-sockets-lack-of-thread-safety) 192 | for in-process communication, pairs of DEALER sockets on each peer, 193 | [poll loops and reactors](https://stackoverflow.com/a/36438543) — but all 194 | of these ways impose extra complexity and a very unnatural and non-idiomatic 195 | programming regime for Go programs. 196 | 197 | curvetls sockets, in contrast, are safe to `Read()` from one goroutine 198 | while another goroutine `Write()`s to them. They work in the expected manner 199 | and do not require you to implement any bespoke multiplexing solutions. 200 | 201 | **Problem numero dos**: if you use the existing ZeroMQ implementations, 202 | then you are bringing into your process a lot of unsafe code, plus a lot 203 | of code you don't need just to do peer-to-peer encryption and authentication. 204 | 205 | curvetls effectively implements the most basic use case of ZeroMQ plus 206 | CurveZMQ, without the extra dependency of ZeroMQ, or any unsafe C code. 207 | This package depends on no unsafe libraries, beyond perhaps the Go NaCL 208 | implementation or the Go standard library itself. 209 | 210 | **Problem numero tres**: did you know that ZeroMQ happily lets clients 211 | send 1 GB buffers, and allocates that memory on the server to receive 212 | them? 213 | 214 | We have a high-priority item on our roadmap which involves giving 215 | implementors a knob that lets them limit the amount of memory a single frame 216 | can consume. Because in ZeroMQ a frame can be effectively as large as you 217 | can imagine, and the frame will not be delivered to the peer until the 218 | peer has read all of it into memory, malicious clients which have 219 | successfully completed the handshake — perhaps they stole a keypair, 220 | perhaps the server `Allow`()s all peers — can bring a server down by making 221 | it allocate inordinately large amounts of memory. 222 | 223 | Additionally, curvetls — unlike CurveZMQ — will not accept any metadata 224 | from a peer during the handshake (which happens *before* the peer has been 225 | authenticated). CurveZMQ metadata is effectively specified to be as big as 226 | you can imagine, which lets clients (and servers!) fill memory on your 227 | server before the CurveZMQ handshake completes. On the roadmap we have 228 | an item which involves adding support for metadata during handshake, but 229 | not before we can provide you, the implementor, with a knob that limits 230 | the amount of metadata a peer is allowed to send. 231 | 232 | **Problem numero cuatro**: ZeroMQ happily accepts as many connections as peers, 233 | including hostile peers, will send its way. You are not in control of the 234 | `Accept()` call — your code only gets notified of *messages*, not of 235 | peer connections and disconnections. These are some odd socket semantics 236 | which work well in many use cases that involve trustworthy peers, but 237 | these semantics work badly outside of it. Additionally, you have to write 238 | extra code in order to track identities — ZeroMQ will not, by default, 239 | let you track of peers by key identity, mostly assuming that a message is a 240 | message is a message, irrespective of which peer is sending it. Effectively, 241 | you have reduced control over the low-level connection and authentication 242 | process, when you implement a ZeroMQ server. You *can* solve the 243 | authentication and authorization issue, but the low-level connection 244 | acceptance and throttling part is strictly off-limits to you as a programmer. 245 | 246 | In curvetls, you are in charge of connecting / listening / accepting / 247 | tracking / closing sockets. This lets you implement custom throttling 248 | policies based on which peer is connecting *prior* to the handshake itself, 249 | and it lets you know verifiably which peer has connected as soon as the 250 | handshake is over. You *want* these properties when writing robust servers. 251 | Have a traffic storm or more clients than your program wants to handle? 252 | Throttle the socket `Accept()`. Have a peer that is already active and 253 | authenticated but wants to connect for a second time? Close the socket 254 | on it as soon as the handshake is over. Have a peer that is relentlessly 255 | connecting when you don't want it to? Close the socket on it as soon as 256 | the `Accept()` returns, or run a firewall rule change — you have the peer's 257 | IP address right after `Accept()`, after all. 258 | 259 | These were the security concerns I needed to address when I set out to write 260 | curvetls, and I'm happy to report they have either been addressed or been 261 | considered high-priority and active work. 262 | 263 | ### Why not CurveCP? 264 | 265 | The first reason is that there are no complete implementations of CurveCP 266 | for Go. You can take the existing implementation and write a binding for it, 267 | but that was much more work than implementing a well-documented specification 268 | in a memory-safe language. 269 | 270 | The second reason is that, even if you do a binding to CurveCP, the full power 271 | of the CurveCP security mechanism would then be available to implementors 272 | but with the burden of having to rely on unsafe code that is basically 273 | abandoned. 274 | 275 | The third reason: CurveCP brings with it the extra code of implementing a 276 | reliable protocol over UDP. This aspect of CurveCP is truly a noble project 277 | that can revolutionize the Internet — if it hasn't already, as CurveCP was 278 | the forefather of Google's QUIC — but it's still extra code that is less 279 | tested than TCP, and it puts more complexity in the path between peer and 280 | your program's processing code. 281 | 282 | ### Why not (this thing I haven't heard of)? 283 | 284 | I'm happy to read the code of that thing and talk to you about it. Who knows, 285 | maybe that thing will render curvetls entirely unnecessary? 286 | 287 | ## Technical and compatibility information 288 | 289 | Compatibility: 290 | 291 | * The robust framing is compliant with the ZeroMQ framing scheme as documented 292 | in https://rfc.zeromq.org/spec:37/ZMTP/ 293 | * The transport security handshake is compliant with the CurveZMQ specification 294 | as documented in available at http://curvezmq.org/ 295 | 296 | Any deviations from the CurveZMQ handshake specification, or interoperability 297 | problems with CurveZMQ implementations, as well as deviations and problems 298 | from / with the ZeroMQ framing scheme, are bugs. You should report them, 299 | so we can fix them. 300 | 301 | Note that, if you choose to use unreliable transports such as UDP, you must 302 | roll your own congestion and retransmission features on each net.Conn you 303 | intend to wrap. Perhaps the right way to go about it, is to write a similar 304 | wrapping library which will wrap (let's say, UDP) network I/O sockets using 305 | the CurveCP congestion algorithm as specified in its documentation. Such a 306 | wrapper, if it returns net.Conn instances, will be compatible with this work. 307 | 308 | ## Legal information 309 | 310 | The license of this library is GPLv3 or later. See file `COPYING` 311 | for details. For relicensing inquiries, contact the author. 312 | -------------------------------------------------------------------------------- /wrap.go: -------------------------------------------------------------------------------- 1 | package curvetls 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "net" 7 | ) 8 | 9 | // NewLongNonce generates a long nonce for use with curvetls.WrapServer 10 | // and curvetls.WrapClient. 11 | // A long nonce is needed and must be unique per long-term private key, 12 | // whether the private key belongs to the server or the client. 13 | // Long nonces must not be reused for new private keys. 14 | func NewLongNonce() (*longNonce, error) { 15 | var nonce longNonce 16 | n, err := rand.Reader.Read(nonce[:]) 17 | if err != nil { 18 | return nil, fmt.Errorf("error reading entropy while generating long nonce: %s", err) 19 | } 20 | if n != len(nonce) { 21 | return nil, fmt.Errorf("short entropy read while generating long nonce") 22 | } 23 | return &nonce, nil 24 | } 25 | 26 | // EncryptedConn is the opaque structure representing an encrypted connection. 27 | // 28 | // On the client, use WrapClient() to obtain one. On the server, use 29 | // WrapServer() to obtain an Authorizer and then invoke Allow() on 30 | // the authorizer to obtain an EncryptedConn. 31 | // 32 | // Then, use the EncryptedConn methods to engage in secure communication. 33 | // 34 | // EncryptedConn implemenets the net.Conn interface. 35 | // 36 | // Lifecycle Information 37 | // 38 | // In general, it is not thread safe to perform reads or writes on an 39 | // EncryptedConn while any part of a handshake (WrapClient(), WrapServer(), 40 | // Allow() or Deny()) is going on in a different goroutine. You should 41 | // complete the handshakes on a single goroutine. It is also not safe to 42 | // perform reads simultaneously on two or more goroutines. It is also not 43 | // safe to perform writes simultaneously on two or more goroutines. It is 44 | // also not safe to intersperse calls to Read() and ReadFrame(), even from 45 | // the same goroutine. 46 | // 47 | // Concurrent things that are safe: (1) one read and one write each on a 48 | // distinct goroutine (2) same as (1) while Close() is invoked on another 49 | // goroutine (the ongoing read and write should return normally with an EOF 50 | // or UnexpectedEOF in that case). (3) performing any operation on one 51 | // EncryptedConn in a single goroutine, while any other operation on 52 | // another EncryptedConn is ongoing in another goroutine. There is no 53 | // global mutable state shared among EncryptedConn instances. 54 | type EncryptedConn struct { 55 | net.Conn // FIXME reorg struct to make it more efficient, and that which is accessed frequenly should be clustered together, and measure perf diff 56 | myNonce *shortNonce 57 | theirNonce *shortNonce 58 | sharedKey precomputedKey 59 | isServer bool 60 | recvFrame []byte 61 | recvMessageCmd *messageCommand 62 | sendMessageCmd *messageCommand 63 | } 64 | 65 | func closeAndBail(conn net.Conn, e error) error { 66 | // These are unrecoverable errors. We close the socket. 67 | conn.Close() 68 | return e 69 | } 70 | 71 | func iE(conn net.Conn, frameName string, e error) error { 72 | return closeAndBail(conn, newProtocolError("invalid %s: %s", frameName, e)) 73 | } 74 | 75 | func pE(conn net.Conn, frameName string, e error) error { 76 | return closeAndBail(conn, newInternalError("cannot build %s: %s", frameName, e)) 77 | } 78 | 79 | // WrapServer wraps an existing, connected net.Conn with encryption and framing. 80 | // 81 | // Returned Values 82 | // 83 | // An Authorizer object with two methods Allow() and Deny(), one of which you 84 | // must call. Allow() will return an EncryptedConn (a net.Conn compatible 85 | // object) that you can use to send and receive data. See the documentation 86 | // of Authorizer for more information. 87 | // 88 | // The public key of the client; use this key to authenticate the client 89 | // and decide whether it is authorized to continue the conversation, then 90 | // either call Allow() to signal to the client that it is authorized, or 91 | // call Deny() to signal to the client that it is not authorized 92 | // and terminate the connection. 93 | // 94 | // An error. It can be an underlying socket error, an internal error produced 95 | // by a bug in the library, or a protocol error indicating that the 96 | // communication encountered corrupt or malformed data from the peer. 97 | // 98 | // Lifecycle Information 99 | // 100 | // If WrapServer() returns an error, the passed socket will have been closed 101 | // by the time this function returns. 102 | // 103 | // If you read or write any data to the underlying socket rather 104 | // than go through the returned socket, your data will be transmitted 105 | // in plaintext and the endpoint will become confused and close the 106 | // connection. Don't do that. 107 | func WrapServer(conn net.Conn, 108 | serverprivkey Privkey, 109 | serverpubkey Pubkey, 110 | long_nonce *longNonce) (*Authorizer, Pubkey, error) { 111 | 112 | // According to my reading of the ZeroMQ 4.x source, it appears to be 113 | // the case that if any part of the handshake fails, their stream 114 | // handler error() method is called, which simply disconnects 115 | // the underlying socket altogether. This we found out after 116 | // our code had already implemented that behavior. 117 | // See https://github.com/zeromq/zeromq4-1/blob/d8732929d507d59dd8d877d35a81308d4ddb1e71/src/stream_engine.cpp#L925 118 | myNonce := newShortNonce() 119 | clientNonce := newShortNonce() 120 | 121 | /* Do greeting. */ 122 | var mygreeting, theirgreeting, expectedgreeting greeting 123 | mygreeting.asServer() 124 | expectedgreeting.asClient() 125 | 126 | if err := wrc(conn, mygreeting[:], theirgreeting[:]); err != nil { 127 | return nil, Pubkey{}, closeAndBail(conn, err) 128 | } 129 | 130 | if theirgreeting != expectedgreeting { 131 | return nil, Pubkey{}, closeAndBail(conn, newProtocolError("malformed greeting")) 132 | } 133 | 134 | /* Read and validate hello. */ 135 | var helloCmd helloCommand 136 | if err := readFrame(conn, &helloCmd); err != nil { 137 | return nil, Pubkey{}, closeAndBail(conn, err) 138 | } 139 | 140 | ephClientPubkey, err := helloCmd.validate(clientNonce, permanentServerPrivkey(serverprivkey)) 141 | if err != nil { 142 | return nil, Pubkey{}, pE(conn, "HELLO", err) 143 | } 144 | 145 | /* Build and send welcome. */ 146 | var welcomeCmd welcomeCommand 147 | cookieKey, err := welcomeCmd.build(long_nonce, ephClientPubkey, permanentServerPrivkey(serverprivkey)) 148 | // FIXME: wipe memory of cookiekey after 60 seconds 149 | // FIXME: wipe memory of cookie, and all the ephemeral server keys at this point 150 | if err != nil { 151 | return nil, Pubkey{}, iE(conn, "WELCOME", err) 152 | } 153 | 154 | if err := writeFrame(conn, &welcomeCmd); err != nil { 155 | return nil, Pubkey{}, closeAndBail(conn, err) 156 | } 157 | 158 | /* Read and validate initiate. */ 159 | var initiateCmd initiateCommand 160 | if err := readFrame(conn, &initiateCmd); err != nil { 161 | return nil, Pubkey{}, closeAndBail(conn, err) 162 | } 163 | 164 | permClientPubkey, ephClientPubkey, ephServerPrivkey, err := initiateCmd.validate(clientNonce, permanentServerPubkey(serverpubkey), cookieKey) 165 | if err != nil { 166 | return nil, Pubkey{}, pE(conn, "INITIATE", err) 167 | } 168 | 169 | return &Authorizer{&EncryptedConn{ 170 | Conn: conn, 171 | myNonce: myNonce, 172 | theirNonce: clientNonce, 173 | sharedKey: precomputeKey(Privkey(ephServerPrivkey), Pubkey(ephClientPubkey)), 174 | isServer: true, 175 | }}, Pubkey(permClientPubkey), nil 176 | } 177 | 178 | // Authorizer is returned by WrapServer() together with the connecting 179 | // client's public key. It lets your server make an authorization decision 180 | // with respect to the client. 181 | // 182 | // By the time the caller of WrapServer() has received the authorizer 183 | // and the client's public key, the client has been authenticated 184 | // (to mean: the server knows the client truthfully holds its keypair). 185 | // At that point your server can invoke an authorization service of your choice 186 | // to decide whether the client is authorized to proceed. 187 | // 188 | // To signal to the client that it is authorized to proceed, call 189 | // Allow() on the authorizer. This returns an EncryptedConn that 190 | // lets your server communicate with the client securely. 191 | // 192 | // Conversely, to signal to the client that it is not authorized, 193 | // call Deny() on the authorizer. 194 | // 195 | // You must call one of the two methods. Failure to do so will leave 196 | // the client hanging, and will leak file descriptors on the server. 197 | // 198 | // See the documentation of Allow() and Deny() for important information. 199 | type Authorizer struct { 200 | encryptedConn *EncryptedConn 201 | } 202 | 203 | // Allow signals the client that it is authorized, finishing the handshake 204 | // and returning an EncryptedConn to talk to the client. 205 | // 206 | // Returned Values 207 | // 208 | // An EncryptedConn (a net.Conn compatible object) that you can use to send 209 | // and receive data. Data sent and received will be framed and encrypted. 210 | // 211 | // Upon successful return of this function, the Close() method of the returned 212 | // net.Conn will also Close() the underlying net.Conn. 213 | // 214 | // Lifecycle Information 215 | // 216 | // If Allow() returns an error, the passed socket will 217 | // have been closed by the time this function returns. 218 | func (c *Authorizer) Allow() (*EncryptedConn, error) { 219 | /* Build and send ready. */ 220 | var readyCmd readyCommand 221 | if err := readyCmd.build(c.encryptedConn.myNonce, &c.encryptedConn.sharedKey); err != nil { 222 | return nil, iE(c.encryptedConn.Conn, "READY", err) 223 | } 224 | 225 | if err := writeFrame(c.encryptedConn.Conn, &readyCmd); err != nil { 226 | return nil, closeAndBail(c.encryptedConn.Conn, err) 227 | } 228 | 229 | return c.encryptedConn, nil 230 | } 231 | 232 | // Deny, signals the client that it is not authorized to continue, 233 | // and closes the underlying socket passed to WrapServer. 234 | // 235 | // Lifecycle Information 236 | // 237 | // When Deny() returns, the underlying socket will have been closed too. 238 | // 239 | // Clients which receive a Deny() denial SHALL NOT reconnect with 240 | // the same credentials, but wise implementors know that hostile 241 | // clients can do what they want, so they will need to implement 242 | // throttling based on public key. WrapServer() returns the 243 | // verified public key of the client before the server has made 244 | // an authentication policy decision, so the server can implement 245 | // throttling based on client public key. 246 | func (c *Authorizer) Deny() error { 247 | /* Build and send error. */ 248 | var errorCmd errorCommand 249 | if err := errorCmd.build("unauthorized"); err != nil { 250 | return iE(c.encryptedConn.Conn, "ERROR", err) 251 | } 252 | 253 | if err := writeFrame(c.encryptedConn.Conn, &errorCmd); err != nil { 254 | return closeAndBail(c.encryptedConn.Conn, err) 255 | } 256 | 257 | err := c.encryptedConn.Close() 258 | return err 259 | } 260 | 261 | // WrapClient wraps an existing, connected net.Conn with encryption and framing. 262 | // 263 | // Returned Values 264 | // 265 | // An EncryptedConn (a net.Conn compatible object) that you can use to send 266 | // and receive data. Data sent and received will be framed and encrypted. 267 | // 268 | // An error. It can be an underlying socket error, an internal error produced 269 | // by a bug in the library, a protocol error indicating that the 270 | // communication encountered corrupt or malformed data from the peer, or an 271 | // authentication error. A method to distinguish authentication errors 272 | // is provided by the IsAuthenticationError() function. No method is provided 273 | // to distinguish among the other errors because the only sane thing to do at 274 | // that point is to close the connection. 275 | // 276 | // Lifecycle Information 277 | // 278 | // If WrapClient() returns an error, the passed socket will have been closed 279 | // by the time this function returns. 280 | // 281 | // Upon successful return of this function, the Close() method of the returned 282 | // net.Conn will also Close() the passed net.Conn. 283 | // 284 | // Upon unauthorized use (the server Authorizer rejects the client with Deny()) 285 | // this function will return an error which can be checked with 286 | // the function IsAuthenticationError(). See note on Deny() 287 | // to learn more about reconnection policy. 288 | // 289 | // If you read or write any data to the underlying socket rather 290 | // than go through the returned socket, your data will be transmitted 291 | // in plaintext and the endpoint will become confused and close the 292 | // connection. Don't do that. 293 | func WrapClient(conn net.Conn, 294 | clientprivkey Privkey, clientpubkey Pubkey, 295 | permServerPubkey Pubkey, 296 | long_nonce *longNonce) (*EncryptedConn, error) { 297 | 298 | myNonce := newShortNonce() 299 | serverNonce := newShortNonce() 300 | 301 | /* Generate ephemeral keypair for this connection. */ 302 | ephClientPrivkey, ephClientPubkey, err := genEphemeralClientKeyPair() 303 | if err != nil { 304 | return nil, closeAndBail(conn, newInternalError("cannot generate ephemeral keypair", err)) 305 | } 306 | 307 | /* Do greeting. */ 308 | var mygreeting, theirgreeting, expectedgreeting greeting 309 | mygreeting.asClient() 310 | expectedgreeting.asServer() 311 | 312 | if err := wrc(conn, mygreeting[:], theirgreeting[:]); err != nil { 313 | return nil, closeAndBail(conn, err) 314 | } 315 | 316 | if theirgreeting != expectedgreeting { 317 | return nil, closeAndBail(conn, newProtocolError("malformed greeting")) 318 | } 319 | 320 | /* Build and send hello. */ 321 | var helloCmd helloCommand 322 | if err := helloCmd.build(myNonce, ephClientPrivkey, ephClientPubkey, permanentServerPubkey(permServerPubkey)); err != nil { 323 | return nil, iE(conn, "HELLO", err) 324 | } 325 | 326 | if err := writeFrame(conn, &helloCmd); err != nil { 327 | return nil, closeAndBail(conn, err) 328 | } 329 | 330 | /* Receive and validate welcome. */ 331 | var welcomeCmd welcomeCommand 332 | if err := readFrame(conn, &welcomeCmd); err != nil { 333 | return nil, closeAndBail(conn, err) 334 | } 335 | 336 | ephServerPubkey, sCookie, err := welcomeCmd.validate(ephClientPrivkey, permanentServerPubkey(permServerPubkey)) 337 | if err != nil { 338 | return nil, pE(conn, "WELCOME", err) 339 | } 340 | 341 | /* Build and send initiate. */ 342 | var initiateCmd initiateCommand 343 | if err := initiateCmd.build(myNonce, 344 | long_nonce, 345 | sCookie, 346 | permanentClientPrivkey(clientprivkey), 347 | permanentClientPubkey(clientpubkey), 348 | permanentServerPubkey(permServerPubkey), 349 | ephServerPubkey, 350 | ephClientPrivkey, 351 | ephClientPubkey); err != nil { 352 | return nil, iE(conn, "INITIATE", err) 353 | } 354 | 355 | if err := writeFrame(conn, &initiateCmd); err != nil { 356 | return nil, closeAndBail(conn, err) 357 | } 358 | 359 | /* Receive and validate ready. */ 360 | var genericCmd genericCommand 361 | if err := readFrame(conn, &genericCmd); err != nil { 362 | return nil, closeAndBail(conn, err) 363 | } 364 | 365 | specificCmd, err := genericCmd.convert() 366 | if err != nil { 367 | return nil, pE(conn, "READY or ERROR", err) 368 | } 369 | 370 | sharedKey := precomputeKey(Privkey(ephClientPrivkey), Pubkey(ephServerPubkey)) 371 | 372 | switch cmd := specificCmd.(type) { 373 | case *readyCommand: 374 | if err := cmd.validate(serverNonce, &sharedKey); err != nil { 375 | return nil, pE(conn, "READY", err) 376 | } 377 | case *errorCommand: 378 | reason, err := cmd.validate() 379 | if err != nil { 380 | return nil, pE(conn, "ERROR", err) 381 | } 382 | return nil, closeAndBail(conn, newAuthenticationError(reason)) 383 | default: 384 | return nil, pE(conn, "unknown command", err) 385 | } 386 | 387 | return &EncryptedConn{ 388 | Conn: conn, 389 | myNonce: myNonce, 390 | theirNonce: serverNonce, 391 | sharedKey: sharedKey, 392 | isServer: false, 393 | }, nil 394 | } 395 | 396 | // Read reads one frame from the other side, decrypts the encrypted frame, 397 | // then copies the bytes read to the passed slice. 398 | // 399 | // If the destination buffer is not large enough to contain the whole 400 | // received frame, then a partial read is made and written to the buffer, 401 | // and subsequent Read() calls will continue reading the remainder 402 | // of that frame. 403 | // 404 | // When the peer has closed the socket, Read() will return a standard EOF. 405 | // 406 | // Lifecycle Information 407 | // 408 | // If Read() returns an error, the socket remains technically open, but 409 | // (much like TLS) it is highly unlikely that, after your program receives 410 | // the error, the connection will continue working. 411 | // 412 | // It is an error to invoke an EncryptedConn's Read() from a goroutine 413 | // while another goroutine is invoking Read() or ReadFrame() on the same 414 | // EncryptedConn. Even with plain old sockets, you'd get nothing but 415 | // corrupted reads that way. It should, however, be safe to invoke Read() 416 | // on an EncryptedConn within one goroutine while another goroutine invokes 417 | // Write() on the same EncryptedConn. 418 | func (w *EncryptedConn) Read(b []byte) (int, error) { 419 | if w.recvFrame == nil { 420 | frame, err := w.ReadFrame() 421 | if err != nil { 422 | return 0, nil 423 | } 424 | w.recvFrame = frame 425 | } 426 | n := copy(b, w.recvFrame) 427 | w.recvFrame = w.recvFrame[n:] 428 | if len(w.recvFrame) == 0 { 429 | w.recvFrame = nil 430 | } 431 | return n, nil 432 | } 433 | 434 | // ReadFrame reads one frame from the other side, decrypts the encrypted frame, 435 | // then returns the whole frame as a slice of bytes. 436 | // 437 | // When the peer has closed the socket, ReadFrame() will return a standard EOF. 438 | // 439 | // Lifecycle Information 440 | // 441 | // If ReadFrame() returns an error, the socket remains technically open, but 442 | // (much like TLS) it is highly unlikely that, after your program receives 443 | // the error, the connection will continue working. 444 | // 445 | // It is an error to call ReadFrame when a previous Read was only partially 446 | // written to its output buffer. 447 | // 448 | // It is an error to invoke an EncryptedConn's ReadFrame() from a goroutine 449 | // while another goroutine is invoking ReadFrame() or Read() on the same 450 | // EncryptedConn. Even with plain old sockets, you'd get nothing but 451 | // corruption that way. It should, however, be safe to invoke ReadFrame() 452 | // on an EncryptedConn within one goroutine while another goroutine invokes 453 | // Write() on the same EncryptedConn. 454 | func (w *EncryptedConn) ReadFrame() ([]byte, error) { 455 | if w.recvFrame != nil { 456 | return nil, newInternalError("cannot read a frame while there is a prior partial frame buffered") 457 | } 458 | /* Read and validate message. */ 459 | 460 | // The following chunk altering w is safe so long as it is never 461 | // invoked simultaneously from two goroutines. 462 | // 463 | // Two things change within w (and linked members) when this code runs: 464 | // 465 | // 1. 8 bytes in w itself, when w gets written to, in order to 466 | // store the buffer. Changes to this part of w do not need 467 | // to be visible in causal order to goroutines running 468 | // Write()s in order for those Write()s to execute successfully. 469 | // 2. 0 bytes in w proper, but an uint64 value pointed to by 470 | // the theirNonce member does get incremented. Again, this does 471 | // not affect w, or concurrent Write()s. 472 | 473 | if w.recvMessageCmd == nil { 474 | w.recvMessageCmd = &messageCommand{} 475 | } 476 | if err := readFrame(w.Conn, w.recvMessageCmd); err != nil { 477 | return nil, err 478 | } 479 | 480 | data, err := w.recvMessageCmd.validate(w.theirNonce, &w.sharedKey, !w.isServer) 481 | if err != nil { 482 | return nil, pE(w.Conn, "MESSAGE", err) 483 | } 484 | return data, nil 485 | } 486 | 487 | // Write frames, encrypts and sends to the other side the passed bytes. 488 | // 489 | // If this function returns an error, the socket remains open, but 490 | // (much like TLS) it is highly unlikely that, after returning an error, 491 | // the connection will continue working. 492 | // 493 | // It is an error to invoke Write() on the same EncryptedConn simultaneously 494 | // from two goroutines. Even with plain old sockets, you'd get nothing but 495 | // corruption that way. It should, however, be safe to invoke Write() 496 | // on an EncryptedConn within one goroutine while another goroutine invokes 497 | // Read() or ReadFrame() on the same EncryptedConn. 498 | func (w *EncryptedConn) Write(b []byte) (int, error) { 499 | /* Build and send message. */ 500 | 501 | // The following chunk altering w is safe so long as it is never 502 | // invoked simultaneously from two goroutines. 503 | // 504 | // Two things change within w (and linked members) when this code runs: 505 | // 506 | // 1. 8 bytes in w itself, when w gets written to, in order to 507 | // store the buffer. Changes to this part of w do not need 508 | // to be visible in causal order to goroutines running 509 | // ReadFrame()s in order for those ReadFrame()s to run correctly. 510 | // 2. 0 bytes in w proper, but an uint64 value pointed to by 511 | // the myNonce member does get incremented. Again, this does 512 | // not affect w, or concurrent ReadFrame()s. 513 | if w.sendMessageCmd == nil { 514 | w.sendMessageCmd = &messageCommand{} 515 | } 516 | err := w.sendMessageCmd.build(w.myNonce, &w.sharedKey, b, w.isServer) 517 | if err != nil { 518 | return 0, iE(w.Conn, "MESSAGE", err) 519 | } 520 | 521 | if err := writeFrame(w.Conn, w.sendMessageCmd); err != nil { 522 | return 0, err 523 | } 524 | return len(b), nil 525 | } 526 | 527 | // IsAuthenticationError returns true when the error returned by 528 | // WrapClient() was caused by the server rejecting the client 529 | // for authentication reasons with Deny(). 530 | func IsAuthenticationError(e error) bool { 531 | _, ok := e.(*authenticationError) 532 | return ok 533 | } 534 | -------------------------------------------------------------------------------- /curvezmq.go: -------------------------------------------------------------------------------- 1 | package curvetls 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "encoding/binary" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "golang.org/x/crypto/nacl/box" 11 | "golang.org/x/crypto/nacl/secretbox" 12 | "net" 13 | ) 14 | 15 | var greetingTemplate = [64]byte{ 16 | '\xFF', 17 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', 18 | '\x7F', 19 | '\x03', '\x01', 20 | 'C', 'U', 'R', 'V', 'E', 21 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', 22 | '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', 23 | '\x00', 24 | } 25 | 26 | type greeting [64]byte 27 | 28 | func (g *greeting) asServer() { 29 | copy(g[:], greetingTemplate[:]) 30 | g[32] = '\x01' 31 | } 32 | 33 | func (g *greeting) asClient() { 34 | copy(g[:], greetingTemplate[:]) 35 | g[32] = '\x00' 36 | } 37 | 38 | var helloNoncePrefix = [16]byte{'C', 'u', 'r', 'v', 'e', 'Z', 'M', 'Q', 'H', 'E', 'L', 'L', 'O', '-', '-', '-'} 39 | var welcomeNoncePrefix = [8]byte{'W', 'E', 'L', 'C', 'O', 'M', 'E', '-'} 40 | var cookieNoncePrefix = [8]byte{'C', 'O', 'O', 'K', 'I', 'E', '-', '-'} 41 | var initiateNoncePrefix = [16]byte{'C', 'u', 'r', 'v', 'e', 'Z', 'M', 'Q', 'I', 'n', 'i', 't', 'i', 'a', 't', 'e'} 42 | var vouchNoncePrefix = [8]byte{'V', 'O', 'U', 'C', 'H', '-', '-', '-'} 43 | var readyNoncePrefix = [16]byte{'C', 'u', 'r', 'v', 'e', 'Z', 'M', 'Q', 'R', 'E', 'A', 'D', 'Y', '-', '-', '-'} 44 | var serverMessageNoncePrefix = [16]byte{'C', 'u', 'r', 'v', 'e', 'Z', 'M', 'Q', 'M', 'E', 'S', 'S', 'A', 'G', 'E', 'S'} 45 | var clientMessageNoncePrefix = [16]byte{'C', 'u', 'r', 'v', 'e', 'Z', 'M', 'Q', 'M', 'E', 'S', 'S', 'A', 'G', 'E', 'C'} 46 | 47 | const maxUint = ^uint(0) 48 | const maxFrameSize = int(maxUint >> 1) 49 | 50 | func rc(conn net.Conn, buf []byte) error { 51 | _, err := io.ReadFull(conn, buf) 52 | return err 53 | } 54 | 55 | func wc(conn net.Conn, data []byte) error { 56 | // Note for myself about the net.Conn Write() protocol. 57 | // I read online somewhere that, if Write(buf) is called, and the returned n 58 | // is smaller than len(buf), the implementation of Write() must guarantee 59 | // that err is non-nil. 60 | // The message was titled "Re: io.MultiWriter has an extra check to bytes written", 61 | // available at https://groups.google.com/d/msg/golang-nuts/WoEP93-Bzn8/5Ij2VTraAgAJ 62 | _, err := conn.Write(data) 63 | return err 64 | } 65 | 66 | func wrc(conn net.Conn, dataToWrite []byte, bufToReadInto []byte) error { 67 | err := wc(conn, dataToWrite) 68 | if err == nil { 69 | err = rc(conn, bufToReadInto) 70 | } 71 | return err 72 | } 73 | 74 | type shortNonce struct { 75 | counter uint64 76 | } 77 | 78 | type shortNoncer interface { 79 | prefixAndBump(prefix [16]byte) ([24]byte, [8]byte, error) 80 | } 81 | 82 | func newShortNonce() *shortNonce { 83 | return &shortNonce{} 84 | } 85 | 86 | func readShortNonce(data []byte) (*shortNonce, error) { 87 | if len(data) != 8 { 88 | return nil, fmt.Errorf("invalid nonce read") 89 | } 90 | var n shortNonce 91 | n.counter = binary.BigEndian.Uint64(data) 92 | return &n, nil 93 | } 94 | 95 | func (s *shortNonce) prefixAndBump(prefix [16]byte) ([24]byte, [8]byte, error) { 96 | var contents [24]byte 97 | var previousNonceContents [8]byte 98 | copy(contents[:], prefix[:]) 99 | binary.BigEndian.PutUint64(contents[len(prefix):], s.counter) 100 | binary.BigEndian.PutUint64(previousNonceContents[:], s.counter) 101 | s.counter += 1 102 | if s.counter == 0 { 103 | return contents, previousNonceContents, errNonceOverflow 104 | } 105 | return contents, previousNonceContents, nil 106 | } 107 | 108 | type longNonce [16]byte 109 | 110 | func (s *longNonce) prefix(prefix [8]byte) [24]byte { 111 | /* Return a 24-byte combined prefix and long nonce. */ 112 | var fullNonce [24]byte 113 | copy(fullNonce[:8], prefix[:]) 114 | copy(fullNonce[8:], s[:]) 115 | return fullNonce 116 | } 117 | 118 | func (s *longNonce) writeUnprefixed(dest []byte) error { 119 | /* Write the 16-byte long nonce write to dest. */ 120 | if len(dest) != 16 { 121 | return fmt.Errorf("incorrect nonce destination length") 122 | } 123 | if copy(dest, s[:]) != len(s) { 124 | return fmt.Errorf("short nonce generation") 125 | } 126 | return nil 127 | } 128 | 129 | func readLongNonce(src []byte) (*longNonce, error) { 130 | if len(src) != 16 { 131 | return nil, fmt.Errorf("invalid nonce read") 132 | } 133 | var n longNonce 134 | copy(n[:], src) 135 | return &n, nil 136 | } 137 | 138 | func (s *shortNonce) uint64() uint64 { 139 | return s.counter 140 | } 141 | 142 | func (s *shortNonce) same(s2 *shortNonce) bool { 143 | return s.counter == s2.counter 144 | } 145 | 146 | type serverCookie [96]byte 147 | type serverCookieKey [32]byte 148 | 149 | func getCookieKey() (k serverCookieKey, err error) { 150 | // FIXME move everything to pointers and clear cookie key, ephemeral server keys. 151 | n, err := rand.Reader.Read(k[:]) 152 | if err != nil { 153 | return k, fmt.Errorf("error reading entropy while generating cookie key: %s", err) 154 | } 155 | if n != len(k) { 156 | return k, fmt.Errorf("short entropy read while generating cookie key") 157 | } 158 | return k, nil 159 | } 160 | 161 | func newServerCookie(ln *longNonce, cpub ephemeralClientPubkey, spriv ephemeralServerPrivkey) (serverCookie, serverCookieKey, error) { 162 | var s serverCookie 163 | var unenccookiebox [64]byte 164 | copy(unenccookiebox[:32], cpub[:]) 165 | copy(unenccookiebox[32:], spriv[:]) 166 | cookieKey, err := getCookieKey() 167 | if err != nil { 168 | return s, [32]byte{}, err 169 | } 170 | prefixedNonce := ln.prefix(cookieNoncePrefix) 171 | ck := [32]byte(cookieKey) 172 | enccookiebox := secretbox.Seal(nil, unenccookiebox[:], &prefixedNonce, &ck) 173 | if err := ln.writeUnprefixed(s[:16]); err != nil { 174 | return s, [32]byte{}, err 175 | } 176 | copy(s[16:], enccookiebox) 177 | return s, cookieKey, nil 178 | } 179 | 180 | func (s *serverCookie) decrypt(cookieKey [32]byte) (ephemeralClientPubkey, ephemeralServerPrivkey, bool, error) { 181 | ln, err := readLongNonce(s[:16]) 182 | if err != nil { 183 | return ephemeralClientPubkey{}, ephemeralServerPrivkey{}, false, err 184 | } 185 | prefixedNonce := ln.prefix(cookieNoncePrefix) 186 | unenccookiebox, ok := secretbox.Open(nil, s[16:], &prefixedNonce, &cookieKey) 187 | if !ok { 188 | return ephemeralClientPubkey{}, ephemeralServerPrivkey{}, false, nil 189 | } 190 | var cpub ephemeralClientPubkey 191 | var spriv ephemeralServerPrivkey 192 | copy(cpub[:], unenccookiebox[:32]) 193 | copy(spriv[:], unenccookiebox[32:]) 194 | return cpub, spriv, true, nil 195 | } 196 | 197 | type clientVouch [96]byte 198 | 199 | func newClientVouch(ln *longNonce, 200 | ecp ephemeralClientPubkey, 201 | psp permanentServerPubkey, 202 | esp ephemeralServerPubkey, 203 | pcp permanentClientPrivkey) (clientVouch, error) { 204 | var s clientVouch 205 | var unenckeybox [64]byte 206 | copy(unenckeybox[:32], ecp[:]) 207 | copy(unenckeybox[32:], psp[:]) 208 | prefixedNonce := ln.prefix(vouchNoncePrefix) 209 | Sprime := [32]byte(esp) 210 | C := [32]byte(pcp) 211 | enckeybox := box.Seal(nil, unenckeybox[:], &prefixedNonce, &Sprime, &C) 212 | if err := ln.writeUnprefixed(s[:16]); err != nil { 213 | return s, err 214 | } 215 | copy(s[16:], enckeybox) 216 | return s, nil 217 | } 218 | 219 | func (c *clientVouch) decrypt(pc permanentClientPubkey, 220 | es ephemeralServerPrivkey) (ephemeralClientPubkey, permanentServerPubkey, bool, error) { 221 | ln, err := readLongNonce(c[:16]) 222 | if err != nil { 223 | return ephemeralClientPubkey{}, permanentServerPubkey{}, false, err 224 | } 225 | prefixedNonce := ln.prefix(vouchNoncePrefix) 226 | C := [32]byte(pc) 227 | Sprime := [32]byte(es) 228 | unencvouchbox, ok := box.Open(nil, c[16:], &prefixedNonce, &C, &Sprime) 229 | if !ok { 230 | return ephemeralClientPubkey{}, permanentServerPubkey{}, false, nil 231 | } 232 | var ecp ephemeralClientPubkey 233 | var spub permanentServerPubkey 234 | copy(ecp[:], unencvouchbox[:32]) 235 | copy(spub[:], unencvouchbox[32:]) 236 | return ecp, spub, true, nil 237 | } 238 | 239 | type protocolError struct { 240 | reason string 241 | } 242 | 243 | func newProtocolError(reason string, additional ...interface{}) error { 244 | return &protocolError{fmt.Sprintf(reason, additional...)} 245 | } 246 | 247 | func (p *protocolError) Error() string { 248 | return p.reason 249 | } 250 | 251 | type internalError struct { 252 | reason string 253 | } 254 | 255 | func newInternalError(reason string, additional ...interface{}) error { 256 | return &internalError{fmt.Sprintf(reason, additional...)} 257 | } 258 | 259 | func (p *internalError) Error() string { 260 | return p.reason 261 | } 262 | 263 | type authenticationError struct { 264 | reason string 265 | } 266 | 267 | func newAuthenticationError(reason string) error { 268 | return &authenticationError{reason} 269 | } 270 | 271 | func (p *authenticationError) Error() string { 272 | return p.reason 273 | } 274 | 275 | // errTooBig is returned when realloc cannot grow the buffer to the 276 | // requested value. 277 | var errTooBig = errors.New("requested buffer cannot be that big") 278 | 279 | // errNonceOverflow is returned when the nonce for this side of the connection 280 | // has overflown (gone back to zero). 281 | var errNonceOverflow = errors.New("nonce overflow") 282 | 283 | type frame interface { 284 | getBuffer() []byte 285 | // realloc attempts to reallocate the buffer associated with getBuffer 286 | // and returns one of three tuples: 287 | // 288 | // * false, nil when the buffer is fixed and may not be reallocated 289 | // * true, non-nil when the buffer cannot attain the requested size 290 | // * true, nil when the buffer was successfully reallocated 291 | // 292 | // After reallocation, any previous references taken to the result of 293 | // previous getBuffer() calls are invalid and will be unsafe to use. 294 | realloc(uint64) (bool, error) 295 | } 296 | 297 | func readFrame(conn net.Conn, dest frame) error { 298 | var ftype [1]byte 299 | if err := rc(conn, ftype[:]); err != nil { 300 | return err 301 | } 302 | var uint64len uint64 303 | if ftype[0] == '\004' { 304 | var length [1]uint8 305 | if err := rc(conn, length[:]); err != nil { 306 | return err 307 | } 308 | uint64len = uint64(length[0]) 309 | } else if ftype[0] == '\006' { 310 | var length [8]byte 311 | if err := rc(conn, length[:]); err != nil { 312 | return err 313 | } 314 | uint64len = binary.BigEndian.Uint64(length[:]) 315 | } else { 316 | return newProtocolError("unsupported frame type %d", uint8(ftype[0])) 317 | } 318 | buf := dest.getBuffer() 319 | if uint64(len(buf)) != uint64len { 320 | canRealloc, err := dest.realloc(uint64len) 321 | // Replicated in genericFrame.convert(). FIXME dedup. 322 | if !canRealloc { 323 | return newProtocolError("sender says frame is %d bytes, buffer is %d bytes", uint64len, len(buf)) 324 | } 325 | if err != nil { 326 | return newProtocolError("realloc for destination buffer from %d to %d failed: %s", len(buf), uint64len, err) 327 | } 328 | /* At this point, the buffer has been reallocated */ 329 | buf = dest.getBuffer() 330 | } 331 | if err := rc(conn, buf); err != nil { 332 | return err 333 | } 334 | return nil 335 | } 336 | 337 | func writeFrame(conn net.Conn, src frame) error { 338 | buf := src.getBuffer() 339 | length := len(buf) 340 | if length < 256 { 341 | /* Short frame send routine */ 342 | if err := wc(conn, []byte{'\004'}); err != nil { 343 | return err 344 | } 345 | var uintlength uint8 346 | uintlength = uint8(length) 347 | if err := wc(conn, []byte{uintlength}); err != nil { 348 | return err 349 | } 350 | if err := wc(conn, buf); err != nil { 351 | return err 352 | } 353 | return nil 354 | } 355 | if err := wc(conn, []byte{'\006'}); err != nil { 356 | return err 357 | } 358 | var uintlength [8]byte 359 | binary.BigEndian.PutUint64(uintlength[:], uint64(length)) 360 | if err := wc(conn, uintlength[:]); err != nil { 361 | return err 362 | } 363 | if err := wc(conn, buf); err != nil { 364 | return err 365 | } 366 | return nil 367 | } 368 | 369 | type helloCommand struct { 370 | buf [200]byte 371 | } 372 | 373 | func (h *helloCommand) getBuffer() []byte { 374 | return h.buf[:] 375 | } 376 | 377 | func (h *helloCommand) realloc(uint64) (bool, error) { 378 | return false, nil 379 | } 380 | 381 | // build Builds a HELLO command, incrementing the passed nonce. 382 | // This executes on the client and its result is sent to the server. 383 | // Arguments: 384 | // clientShortNonce: the short nonce associated with the client, 385 | // which gets incremented as this function executes. 386 | // ephClientPrivkey: the ephemeral client private key 387 | // ephClientPubkey: the ephemeral client public key 388 | // permServerPubkey: the permanent server public key 389 | // Returns: 390 | // error: an error 391 | func (h *helloCommand) build( 392 | clientShortNonce shortNoncer, 393 | ephClientPrivkey ephemeralClientPrivkey, 394 | ephClientPubkey ephemeralClientPubkey, 395 | permServerPubkey permanentServerPubkey) error { 396 | 397 | destHeader := h.buf[:8] 398 | destEphClientPubkey := h.buf[80 : 80+32] 399 | destUnprefixedNonce := h.buf[80+32 : 80+32+8] 400 | destEncHelloBox := h.buf[80+32+8 : 80+32+8+80] 401 | 402 | prefixedNonce, unprefixedNonce, err := clientShortNonce.prefixAndBump(helloNoncePrefix) 403 | if err != nil { 404 | return err 405 | } 406 | 407 | Cprime := [32]byte(ephClientPrivkey) 408 | S := [32]byte(permServerPubkey) 409 | var helloBox [64]byte 410 | encHelloBox := box.Seal(nil, helloBox[:], &prefixedNonce, &S, &Cprime) 411 | 412 | copy(destHeader, []byte{5, 'H', 'E', 'L', 'L', 'O', 1, 0}) 413 | copy(destEphClientPubkey, ephClientPubkey[:]) 414 | copy(destUnprefixedNonce, unprefixedNonce[:]) 415 | copy(destEncHelloBox, encHelloBox) 416 | 417 | return nil 418 | } 419 | 420 | func (h *helloCommand) validate(expectedClientShortNonce *shortNonce, 421 | permServerPrivkey permanentServerPrivkey) (ephemeralClientPubkey, error) { 422 | /* 423 | Validates a read HELLO command, incrementing the passed nonce. 424 | This executes on the server 425 | */ 426 | 427 | srcHeader := h.buf[:8] 428 | srcPadding := h.buf[8:80] 429 | srcEphClientPubkey := h.buf[80 : 80+32] 430 | srcUnprefixedNonce := h.buf[80+32 : 80+32+8] 431 | srcEncHelloBox := h.buf[80+32+8 : 80+32+8+80] 432 | 433 | if bytes.Compare(srcHeader, []byte{5, 'H', 'E', 'L', 'L', 'O', 1, 0}) != 0 { 434 | return ephemeralClientPubkey{}, fmt.Errorf("malformed HELLO header") 435 | } 436 | var pa [72]byte 437 | if bytes.Compare(srcPadding, pa[:]) != 0 { 438 | return ephemeralClientPubkey{}, fmt.Errorf("malformed HELLO padding") 439 | } 440 | pk, err := pubkeyFromSlice(srcEphClientPubkey) 441 | if err != nil { 442 | return ephemeralClientPubkey{}, fmt.Errorf("invalid ephemeral client public key") 443 | } 444 | ephClientPubkey := ephemeralClientPubkey(pk) 445 | 446 | cn, err := readShortNonce(srcUnprefixedNonce) 447 | if err != nil { 448 | return ephemeralClientPubkey{}, err 449 | } 450 | if !expectedClientShortNonce.same(cn) { 451 | return ephemeralClientPubkey{}, fmt.Errorf("client nonce not in sequence: %d != %d", expectedClientShortNonce.uint64(), cn) 452 | } 453 | prefixedNonce, _, err := expectedClientShortNonce.prefixAndBump(helloNoncePrefix) 454 | if err != nil { 455 | return ephemeralClientPubkey{}, err 456 | } 457 | 458 | Cprime := [32]byte(ephClientPubkey) 459 | S := [32]byte(permServerPrivkey) 460 | helloBox, ok := box.Open(nil, srcEncHelloBox, &prefixedNonce, &Cprime, &S) 461 | if !ok { 462 | return ephemeralClientPubkey{}, fmt.Errorf("cannot validate client hello box") 463 | } 464 | var expectedHelloBox [64]byte 465 | if bytes.Compare(helloBox, expectedHelloBox[:]) != 0 { 466 | return ephemeralClientPubkey{}, fmt.Errorf("client box contains unexpected contents") 467 | } 468 | 469 | return ephClientPubkey, nil 470 | } 471 | 472 | type welcomeCommand struct { 473 | buf [168]byte 474 | } 475 | 476 | func (c *welcomeCommand) getBuffer() []byte { 477 | return c.buf[:] 478 | } 479 | 480 | func (h *welcomeCommand) realloc(uint64) (bool, error) { 481 | return false, nil 482 | } 483 | 484 | // Builds a WELCOME command. 485 | // This executes in the server. 486 | func (c *welcomeCommand) build( 487 | serverLongNonce *longNonce, 488 | ephClientPubkey ephemeralClientPubkey, 489 | permServerPrivkey permanentServerPrivkey) (serverCookieKey, error) { 490 | 491 | destHeader := c.buf[:8] 492 | destUnprefixedLongNonce := c.buf[8 : 8+16] 493 | destEncWelcomeBox := c.buf[8+16 : 168] 494 | 495 | ephServerPrivkey, p, err := genEphemeralServerKeyPair() 496 | if err != nil { 497 | return serverCookieKey{}, fmt.Errorf("cannot generate ephemeral keypair", err) 498 | } 499 | ephServerPubkey := ephemeralServerPubkey(p) 500 | 501 | cookie, cookieKey, err := newServerCookie(serverLongNonce, ephClientPubkey, ephServerPrivkey) 502 | if err != nil { 503 | return serverCookieKey{}, err 504 | } 505 | 506 | var unencwelcomebox [32 + 96]byte 507 | copy(unencwelcomebox[:32], ephServerPubkey[:]) 508 | copy(unencwelcomebox[32:], cookie[:]) 509 | 510 | Cprime := [32]byte(ephClientPubkey) 511 | S := [32]byte(permServerPrivkey) 512 | prefixedNonce := serverLongNonce.prefix(welcomeNoncePrefix) 513 | encWelcomeBox := box.Seal(nil, unencwelcomebox[:], &prefixedNonce, &Cprime, &S) 514 | 515 | copy(destHeader, []byte{7, 'W', 'E', 'L', 'C', 'O', 'M', 'E'}) 516 | if err := serverLongNonce.writeUnprefixed(destUnprefixedLongNonce); err != nil { 517 | return serverCookieKey{}, err 518 | } 519 | copy(destEncWelcomeBox, encWelcomeBox) 520 | 521 | return cookieKey, nil 522 | } 523 | 524 | // Validates a read WELCOME command, incrementing the passed nonce. 525 | // This is executed in the client. 526 | // Returns: 527 | // the ephemeral server public key 528 | // the server cookie 529 | // any error that may have happened 530 | func (c *welcomeCommand) validate(ephclientprivkey ephemeralClientPrivkey, 531 | permServerPubkey permanentServerPubkey) (ephemeralServerPubkey, serverCookie, error) { 532 | srcHeader := c.buf[:8] 533 | srcUnprefixedLongNonce := c.buf[8 : 8+16] 534 | srcEncWelcomeBox := c.buf[8+16 : 168] 535 | 536 | if bytes.Compare(srcHeader, []byte{7, 'W', 'E', 'L', 'C', 'O', 'M', 'E'}) != 0 { 537 | return ephemeralServerPubkey{}, serverCookie{}, fmt.Errorf("malformed HELLO header") 538 | } 539 | 540 | serverLongNonce, err := readLongNonce(srcUnprefixedLongNonce) 541 | if err != nil { 542 | return ephemeralServerPubkey{}, serverCookie{}, err 543 | } 544 | Cprime := [32]byte(permServerPubkey) 545 | S := [32]byte(ephclientprivkey) 546 | prefixedNonce := serverLongNonce.prefix(welcomeNoncePrefix) 547 | welcomeBox, ok := box.Open(nil, srcEncWelcomeBox, &prefixedNonce, &Cprime, &S) 548 | if !ok { 549 | return ephemeralServerPubkey{}, serverCookie{}, nil 550 | } 551 | srcEphServerPubkey := welcomeBox[:32] 552 | srcCookie := welcomeBox[32:] 553 | var ephServerPubkey ephemeralServerPubkey 554 | var sCookie serverCookie 555 | copy(ephServerPubkey[:], srcEphServerPubkey) 556 | copy(sCookie[:], srcCookie) 557 | 558 | return ephServerPubkey, sCookie, nil 559 | } 560 | 561 | type initiateCommand struct { 562 | // FIXME: to support metadata, bump the size of this buffer. 563 | buf [257]byte 564 | curlen uint64 565 | } 566 | 567 | func (c *initiateCommand) getBuffer() []byte { 568 | return c.buf[:c.curlen] 569 | } 570 | 571 | func (c *initiateCommand) realloc(l uint64) (bool, error) { 572 | if l > uint64(len(c.buf)) { 573 | return true, errTooBig 574 | } 575 | c.curlen = l 576 | return true, nil 577 | } 578 | 579 | // Builds an INITIATE command, incrementing the passed nonce. 580 | // This executes on the client. 581 | func (c *initiateCommand) build(clientShortNonce shortNoncer, 582 | clientLongNonce *longNonce, 583 | cookie serverCookie, 584 | permClientPrivkey permanentClientPrivkey, 585 | permClientPubkey permanentClientPubkey, 586 | permServerPubkey permanentServerPubkey, 587 | ephServerPubkey ephemeralServerPubkey, 588 | ephClientPrivkey ephemeralClientPrivkey, 589 | ephClientPubkey ephemeralClientPubkey) error { 590 | 591 | // FIXME: to support metadata, bump the size of this buffer. 592 | _, err := c.realloc(257) 593 | if err != nil { 594 | return err 595 | } 596 | 597 | destHeader := c.buf[:9] 598 | destCookie := c.buf[9 : 9+96] 599 | destUnprefixedNonce := c.buf[9+96 : 9+96+8] 600 | destEncInitiateBox := c.buf[9+96+8 : 9+96+8+144] 601 | 602 | prefixedNonce, unprefixedNonce, err := clientShortNonce.prefixAndBump(initiateNoncePrefix) 603 | if err != nil { 604 | return err 605 | } 606 | 607 | vouch, err := newClientVouch(clientLongNonce, ephClientPubkey, permServerPubkey, ephServerPubkey, permClientPrivkey) 608 | if err != nil { 609 | return err 610 | } 611 | 612 | var initiateBox [32 + 96]byte 613 | copy(initiateBox[:32], permClientPubkey[:]) 614 | copy(initiateBox[32:], vouch[:]) 615 | 616 | Cprime := [32]byte(ephClientPrivkey) 617 | Sprime := [32]byte(ephServerPubkey) 618 | 619 | encInitiateBox := box.Seal(nil, initiateBox[:], &prefixedNonce, &Sprime, &Cprime) 620 | 621 | copy(destHeader, []byte{8, 'I', 'N', 'I', 'T', 'I', 'A', 'T', 'E'}) 622 | copy(destCookie, cookie[:]) 623 | copy(destUnprefixedNonce, unprefixedNonce[:]) 624 | copy(destEncInitiateBox, encInitiateBox) 625 | 626 | return nil 627 | } 628 | 629 | // Validates a read WELCOME command, incrementing the passed nonce. 630 | // This is executed in the server. 631 | func (c *initiateCommand) validate(expectedClientShortNonce *shortNonce, expectedPermServerPubkey permanentServerPubkey, 632 | cookieKey [32]byte) (permanentClientPubkey, ephemeralClientPubkey, ephemeralServerPrivkey, error) { 633 | 634 | // FIXME: to support metadata, bump the size of this buffer. 635 | if c.curlen != 257 { 636 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("wrong INITIATE length %d", c.curlen) 637 | } 638 | 639 | srcHeader := c.buf[:9] 640 | srcReceivedCookie := c.buf[9 : 9+96] 641 | srcUnprefixedNonce := c.buf[9+96 : 9+96+8] 642 | srcEncInitiateBox := c.buf[9+96+8 : 9+96+8+144] 643 | 644 | /* Validate the header. */ 645 | if bytes.Compare(srcHeader, []byte{8, 'I', 'N', 'I', 'T', 'I', 'A', 'T', 'E'}) != 0 { 646 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("malformed INITIATE header") 647 | } 648 | 649 | /* Check the nonce. */ 650 | cn, err := readShortNonce(srcUnprefixedNonce) 651 | if err != nil { 652 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, err 653 | } 654 | if !expectedClientShortNonce.same(cn) { 655 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("client nonce not in sequence: %d != %d", expectedClientShortNonce.uint64(), cn) 656 | } 657 | prefixedNonce, _, err := expectedClientShortNonce.prefixAndBump(initiateNoncePrefix) 658 | if err != nil { 659 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, err 660 | } 661 | 662 | /* Decrypt the cookie, get client's ephemeral pubkey and my own ephemeral privkey . */ 663 | var cookie serverCookie 664 | copy(cookie[:], srcReceivedCookie) 665 | ephClientPubkeyFromCookie, ephServerPrivkeyFromCookie, ok, err := cookie.decrypt(cookieKey) 666 | if err != nil { 667 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, err 668 | } 669 | if !ok { 670 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("cannot validate cookie") 671 | } 672 | 673 | /* Decrypt the initiate box. */ 674 | Cprime := [32]byte(ephClientPubkeyFromCookie) 675 | Sprime := [32]byte(ephServerPrivkeyFromCookie) 676 | initiateBox, ok := box.Open(nil, srcEncInitiateBox, &prefixedNonce, &Cprime, &Sprime) 677 | if !ok { 678 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("cannot validate client initiate box") 679 | } 680 | 681 | /* Get permanent client pubkey aend encrypted vouch from initiate box */ 682 | var permClientPubkey permanentClientPubkey 683 | var vouch clientVouch 684 | copy(permClientPubkey[:], initiateBox[:32]) 685 | copy(vouch[:], initiateBox[32:]) 686 | 687 | /* Decrypt the vouch, get client's ephemeral pubkey and server's permanent pubkey. */ 688 | ephClientPubkeyFromVouch, permServerPubkeyFromVouch, ok, err := vouch.decrypt(permClientPubkey, ephServerPrivkeyFromCookie) 689 | if err != nil { 690 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, err 691 | } 692 | if !ok { 693 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("cannot validate client vouch") 694 | } 695 | 696 | /* Validate keys. */ 697 | if ephClientPubkeyFromCookie != ephClientPubkeyFromVouch { 698 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("ephemeral client public keys differ between cookie and vouch") 699 | } 700 | if permServerPubkeyFromVouch != expectedPermServerPubkey { 701 | return permanentClientPubkey{}, ephemeralClientPubkey{}, ephemeralServerPrivkey{}, fmt.Errorf("permanent server public keys differ between cookie and vouch") 702 | } 703 | 704 | return permClientPubkey, ephClientPubkeyFromVouch, ephServerPrivkeyFromCookie, nil 705 | } 706 | 707 | type readyCommand struct { 708 | // FIXME: to support metadata, bump the size of this buffer. 709 | buf [30]byte 710 | curlen uint64 711 | } 712 | 713 | func (c *readyCommand) getBuffer() []byte { 714 | return c.buf[:c.curlen] 715 | } 716 | 717 | func (c *readyCommand) realloc(l uint64) (bool, error) { 718 | if l > uint64(len(c.buf)) { 719 | return true, errTooBig 720 | } 721 | c.curlen = l 722 | return true, nil 723 | } 724 | 725 | // Builds a READY command, incrementing the passed nonce. 726 | // This executes on the client. 727 | func (c *readyCommand) build(serverShortNonce shortNoncer, sk *precomputedKey) error { 728 | 729 | // FIXME: to support metadata, bump the size of this buffer. 730 | _, err := c.realloc(30) 731 | if err != nil { 732 | return err 733 | } 734 | 735 | destHeader := c.buf[:6] 736 | destUnprefixedNonce := c.buf[6 : 6+8] 737 | destEncReadyBox := c.buf[6+8 : 6+8+16] 738 | 739 | prefixedNonce, unprefixedNonce, err := serverShortNonce.prefixAndBump(readyNoncePrefix) 740 | if err != nil { 741 | return err 742 | } 743 | 744 | encReadyBox := box.SealAfterPrecomputation(nil, []byte{}, &prefixedNonce, (*[32]byte)(sk)) 745 | 746 | copy(destHeader, []byte{5, 'R', 'E', 'A', 'D', 'Y'}) 747 | copy(destUnprefixedNonce, unprefixedNonce[:]) 748 | copy(destEncReadyBox, encReadyBox) 749 | 750 | return nil 751 | } 752 | 753 | // Validates a read READY command, incrementing the passed nonce. 754 | // This executes in the client. 755 | func (c *readyCommand) validate(expectedServerShortNonce *shortNonce, sk *precomputedKey) error { 756 | 757 | // FIXME: to support metadata, bump the size of this buffer. 758 | if c.curlen != 30 { 759 | return fmt.Errorf("wrong READY length %d", c.curlen) 760 | } 761 | 762 | srcHeader := c.buf[:6] 763 | srcUnprefixedNonce := c.buf[6 : 6+8] 764 | srcEncReadyBox := c.buf[6+8 : 6+8+16] 765 | 766 | /* Validate the header. */ 767 | if bytes.Compare(srcHeader, []byte{5, 'R', 'E', 'A', 'D', 'Y'}) != 0 { 768 | return fmt.Errorf("malformed READY header") 769 | } 770 | 771 | /* Check the nonce. */ 772 | cn, err := readShortNonce(srcUnprefixedNonce) 773 | if err != nil { 774 | return err 775 | } 776 | if !expectedServerShortNonce.same(cn) { 777 | return fmt.Errorf("server nonce not in sequence: %d != %d", expectedServerShortNonce.uint64(), cn) 778 | } 779 | prefixedNonce, _, err := expectedServerShortNonce.prefixAndBump(readyNoncePrefix) 780 | if err != nil { 781 | return err 782 | } 783 | 784 | /* Decrypt the ready box. */ 785 | _, ok := box.OpenAfterPrecomputation(nil, srcEncReadyBox, &prefixedNonce, (*[32]byte)(sk)) 786 | if !ok { 787 | return fmt.Errorf("cannot validate server ready box") 788 | } 789 | 790 | return nil 791 | } 792 | 793 | type errorCommand struct { 794 | buf [256 + 6]byte 795 | curlen uint64 796 | } 797 | 798 | func (c *errorCommand) getBuffer() []byte { 799 | return c.buf[:c.curlen] 800 | } 801 | 802 | func (c *errorCommand) realloc(l uint64) (bool, error) { 803 | if l > uint64(len(c.buf)) { 804 | return true, errTooBig 805 | } 806 | c.curlen = l 807 | return true, nil 808 | } 809 | 810 | // Builds an ERROR command. 811 | // This executes on the server. 812 | func (c *errorCommand) build(reason string) error { 813 | 814 | if len(reason) > 255 { 815 | return fmt.Errorf("error message too long") 816 | } 817 | 818 | size := 6 + 1 + len(reason) 819 | _, err := c.realloc(uint64(size)) 820 | if err != nil { 821 | return err 822 | } 823 | copy(c.buf[:6], []byte{5, 'E', 'R', 'R', 'O', 'R'}) 824 | c.buf[6] = uint8(len(reason)) 825 | copy(c.buf[7:size], []byte(reason)) 826 | 827 | return nil 828 | } 829 | 830 | // Validates a read ERROR command, incrementing the passed nonce. 831 | // This executes on the client. 832 | func (c *errorCommand) validate() (string, error) { 833 | 834 | if c.curlen > 256+6 { 835 | return "", fmt.Errorf("invalid ERROR length %d", c.curlen) 836 | } 837 | if c.curlen < 7 { 838 | return "", fmt.Errorf("invalid ERROR length %d", c.curlen) 839 | } 840 | 841 | srcHeader := c.buf[:6] 842 | srcReasonSize := c.buf[6:7] 843 | srcReason := c.buf[7:c.curlen] 844 | 845 | /* Validate the header. */ 846 | if bytes.Compare(srcHeader, []byte{5, 'E', 'R', 'R', 'O', 'R'}) != 0 { 847 | return "", fmt.Errorf("malformed ERROR header") 848 | } 849 | 850 | reasonSize := uint8(srcReasonSize[0]) 851 | if int(reasonSize) != len(srcReason) { 852 | return "", fmt.Errorf("unexpected length for the reason: %d != %d", reasonSize, len(srcReason)) 853 | } 854 | 855 | reason := string(srcReason) 856 | 857 | return reason, nil 858 | } 859 | 860 | type messageCommand struct { 861 | buf []byte 862 | } 863 | 864 | func (c *messageCommand) getBuffer() []byte { 865 | return c.buf 866 | } 867 | 868 | func (c *messageCommand) realloc(sz uint64) (bool, error) { 869 | if sz > uint64(maxFrameSize) { 870 | return true, errTooBig 871 | } 872 | 873 | if c.buf == nil { 874 | c.buf = make([]byte, sz) 875 | return true, nil 876 | } 877 | if uint64(cap(c.buf)) < sz { 878 | c.buf = make([]byte, sz) 879 | return true, nil 880 | } 881 | if uint64(len(c.buf)) != sz { 882 | c.buf = c.buf[:sz] 883 | } 884 | return true, nil 885 | } 886 | 887 | // Builds a MESSAGE command. 888 | // This executes on both the server and the client. 889 | func (c *messageCommand) build(sn shortNoncer, sk *precomputedKey, data []byte, sentByServer bool) error { 890 | 891 | total := uint64(8 + 8 + 16 + 1) 892 | total += uint64(len(data)) 893 | 894 | _, err := c.realloc(total) 895 | if err != nil { 896 | return err 897 | } 898 | 899 | destHeader := c.buf[:8] 900 | destUnprefixedNonce := c.buf[8:16] 901 | destEncMessageBox := c.buf[16:total] 902 | 903 | var prefix [16]byte 904 | if sentByServer { 905 | prefix = serverMessageNoncePrefix 906 | } else { 907 | prefix = clientMessageNoncePrefix 908 | } 909 | prefixedNonce, unprefixedNonce, err := sn.prefixAndBump(prefix) 910 | if err != nil { 911 | return err 912 | } 913 | 914 | payload := append([]byte{0}, data...) 915 | encMessageBox := box.SealAfterPrecomputation(nil, payload, &prefixedNonce, (*[32]byte)(sk)) 916 | 917 | copy(destHeader, []byte{7, 'M', 'E', 'S', 'S', 'A', 'G', 'E'}) 918 | copy(destUnprefixedNonce, unprefixedNonce[:]) 919 | copy(destEncMessageBox, encMessageBox) 920 | 921 | return nil 922 | } 923 | 924 | // Validates a read MESSAGE command, incrementing the passed nonce. 925 | // This executes on both the server and the client. 926 | func (c *messageCommand) validate(expectedNonce *shortNonce, sk *precomputedKey, sentByServer bool) ([]byte, error) { 927 | 928 | if len(c.buf) < 33 { 929 | return nil, fmt.Errorf("short or malformed MESSAGE") 930 | } 931 | 932 | srcHeader := c.buf[:8] 933 | srcUnprefixedNonce := c.buf[8:16] 934 | srcEncMessageBox := c.buf[16:] 935 | 936 | /* Validate the header. */ 937 | if bytes.Compare(srcHeader, []byte{7, 'M', 'E', 'S', 'S', 'A', 'G', 'E'}) != 0 { 938 | return nil, fmt.Errorf("malformed MESSAGE header") 939 | } 940 | 941 | /* Check the nonce. */ 942 | cn, err := readShortNonce(srcUnprefixedNonce) 943 | if err != nil { 944 | return nil, err 945 | } 946 | if !expectedNonce.same(cn) { 947 | return nil, fmt.Errorf("nonce not in sequence: %d != %d", expectedNonce.uint64(), cn) 948 | } 949 | 950 | var prefix [16]byte 951 | if sentByServer { 952 | prefix = serverMessageNoncePrefix 953 | } else { 954 | prefix = clientMessageNoncePrefix 955 | } 956 | prefixedNonce, _, err := expectedNonce.prefixAndBump(prefix) 957 | if err != nil { 958 | return nil, err 959 | } 960 | 961 | payload, ok := box.OpenAfterPrecomputation(nil, srcEncMessageBox, &prefixedNonce, (*[32]byte)(sk)) 962 | if !ok { 963 | return nil, fmt.Errorf("malformed MESSAGE payload") 964 | } 965 | if len(payload) == 0 { 966 | return nil, fmt.Errorf("malformed MESSAGE payload") 967 | } 968 | if payload[0] != 0 { 969 | return nil, fmt.Errorf("unsupported payload flags %d", payload[0]) 970 | } 971 | data := payload[1:] 972 | 973 | return data, nil 974 | } 975 | 976 | type genericCommand struct { 977 | buf [4088]byte 978 | curlen uint64 979 | } 980 | 981 | func (c *genericCommand) getBuffer() []byte { 982 | return c.buf[:c.curlen] 983 | } 984 | 985 | func (c *genericCommand) realloc(l uint64) (bool, error) { 986 | if l > uint64(len(c.buf)) { 987 | return true, errTooBig 988 | } 989 | c.curlen = l 990 | return true, nil 991 | } 992 | 993 | func (c *genericCommand) convert() (frame, error) { 994 | var realCmd frame 995 | if c.curlen >= 30 && bytes.Compare(c.buf[:6], []byte{5, 'R', 'E', 'A', 'D', 'Y'}) == 0 { 996 | realCmd = &readyCommand{} 997 | } else if c.curlen >= 7 && bytes.Compare(c.buf[:6], []byte{5, 'E', 'R', 'R', 'O', 'R'}) == 0 { 998 | realCmd = &errorCommand{} 999 | } else { 1000 | return nil, fmt.Errorf("unknown command") 1001 | } 1002 | 1003 | buf := realCmd.getBuffer() 1004 | if uint64(len(buf)) != c.curlen { 1005 | // Replicated in readFrame(). FIXME dedup. 1006 | canRealloc, err := realCmd.realloc(c.curlen) 1007 | if !canRealloc { 1008 | return nil, fmt.Errorf("sender says frame is %d bytes, buffer is %d bytes", c.curlen, len(buf)) 1009 | } 1010 | if err != nil { 1011 | return nil, fmt.Errorf("realloc for destination buffer from %d to %d failed: %s", len(buf), c.curlen, err) 1012 | } 1013 | } 1014 | buf = realCmd.getBuffer() 1015 | copy(realCmd.getBuffer(), c.getBuffer()) 1016 | return realCmd, nil 1017 | } 1018 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------