├── .gitignore ├── LICENSE ├── Makefile ├── NOTICE ├── README.md ├── config.go ├── docs ├── config.md ├── cryptoauth.md └── design.md ├── error.go ├── glisp.go ├── main.go ├── server.go ├── tun ├── LICENSE ├── NOTICE ├── tun.go ├── tun_darwin.go ├── tun_linux.go └── util.go ├── types.go ├── udp.go └── util.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | *.pcap 6 | *.orig 7 | *.new 8 | kestrel 9 | # Folders 10 | _obj 11 | _test 12 | _vendor 13 | # Architecture specific extensions/prefixes 14 | *.[568vq] 15 | [568vq].out 16 | 17 | *.cgo1.go 18 | *.cgo2.c 19 | _cgo_defun.c 20 | _cgo_gotypes.go 21 | _cgo_export.* 22 | 23 | _testmain.go 24 | 25 | *.exe 26 | *.test 27 | *.prof 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Based on http://zduck.com/2014/go-project-structure-and-dependencies/ 2 | 3 | .PHONY: build doc fmt lint run test vendor_clean vendor_get vendor_update vet 4 | 5 | # Prepend our _vendor directory to the system GOPATH 6 | # so that import path resolution will prioritize 7 | # our third party snapshots. 8 | ORIGINAL_GOPATH := ${GOPATH} 9 | export ORIGINAL_GOPATH 10 | GOPATH := ${PWD}/_vendor:${GOPATH} 11 | export GOPATH 12 | 13 | default: vendor_get build install 14 | 15 | build: 16 | GOPATH=${PWD}/_vendor go build -v 17 | 18 | # Install package to original GOPATH 19 | install: 20 | go install -v 21 | 22 | doc: 23 | godoc -http=:6060 -index 24 | 25 | # http://golang.org/cmd/go/#hdr-Run_gofmt_on_package_sources 26 | fmt: 27 | go fmt 28 | 29 | # https://github.com/golang/lint 30 | # go get github.com/golang/lint/golint 31 | lint: 32 | golint 33 | 34 | test: 35 | go test 36 | 37 | vendor_clean: 38 | rm -dRf ./_vendor/src 39 | 40 | # We have to set GOPATH to just the _vendor 41 | # directory to ensure that `go get` doesn't 42 | # update packages in our primary GOPATH instead. 43 | # This will happen if you already have the package 44 | # installed in GOPATH since `go get` will use 45 | # that existing location as the destination. 46 | vendor_get: vendor_clean 47 | GOPATH=${PWD}/_vendor go get -d -u -v \ 48 | github.com/sirupsen/logrus \ 49 | github.com/BurntSushi/toml \ 50 | github.com/codegangsta/cli \ 51 | github.com/adampresley/sigint \ 52 | github.com/nsjph/cryptoauth \ 53 | github.com/zhemao/glisp \ 54 | golang.org/x/crypto/ssh/terminal \ 55 | golang.org/x/crypto/ssh 56 | 57 | vendor_update: vendor_get 58 | rm -rf `find ./_vendor/src -type d -name .git` \ 59 | && rm -rf `find ./_vendor/src -type d -name .hg` \ 60 | && rm -rf `find ./_vendor/src -type d -name .bzr` \ 61 | && rm -rf `find ./_vendor/src -type d -name .svn` 62 | 63 | # http://godoc.org/code.google.com/p/go.tools/cmd/vet 64 | # go get code.google.com/p/go.tools/cmd/vet 65 | vet: 66 | go vet ./src/... 67 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Software Credits 2 | The development of this software was made possible using the following components: 3 | 4 | govpn by Jay True (Unknown License) 5 | An OpenVPN clone written in go 6 | https://github.com/glacjay/govpn 7 | 8 | netlink by Vish Ishaya (Apache License 2.0) 9 | Simple netlink library for go. 10 | https://github.com/vishvananda 11 | 12 | 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![A picture of a Kestrel](https://i.imgur.com/r6iIFxd.jpg) 2 | 3 | Kestrel 4 | ======= 5 | 6 | Another cjdns router implementation. 7 | 8 | ## Background 9 | 10 | Cjdns is the name of a [meshnet routing protocol](https://github.com/cjdelisle/cjdns/blob/master/doc/Whitepaper.md) and [router implementation](https://github.com/cjdelisle/cjdns) from [cjd](https://github.com/cjdelisle). 11 | 12 | Kestrel is an attempt at a new, simpler cjdns router in Golang. 13 | 14 | Why a new router? Because I think simpler routers will make it easier to debug, troubleshoot and develop cjdns. 15 | 16 | ## Known Issues/Limitations 17 | 18 | 1. I'm writing Kestrel in Golang. I have no experience with Golang prior to this project 19 | 2. Cjdns is an encrypted network protocol. I haven't implemented encrypted network protocols 20 | 2. Kestrel is being written first for Linux/x64. If you need multiplatform support, stick with cjdroute. If you would like to help make Kestrel work on other platforms, please get in contact. 21 | 22 | ## FAQ 23 | 24 | **Q: Is this a fork of cjdns?** 25 | 26 | *A: No. This is an attempt at an interoperable cjdns router in golang.* 27 | 28 | **Q: What is the status of Kestrel?** 29 | 30 | *A: Kestrel is not ready for testing or production use as of Q1 2015* 31 | 32 | **Q: Why not work on cjdroute instead?** 33 | 34 | *A: 1) I felt like learning Golang, and 2) writing Kestrel is a great way to learn how the cjdns protocol works by implementing it from the ground up.* 35 | 36 | **Q: Why not insert other language here?** 37 | 38 | *A: Golang felt like the sweet spot for porting a C-based network daemon (there's many success stories of companies porting network services to Golang). The combination of static-typing, garbage collection and C-like syntax makes code more readable and significantly harder to screw up than C.* 39 | 40 | **Q: What's with the name Kestrel? Will you change the name again?** 41 | 42 | *A: I like birds. Pray I do not change the name further.* 43 | 44 | **Q: Why did you move this repo from github.com/jphackworth to github.com/nsjph? Is it the same dev?** 45 | 46 | *A: Yes it's the same author. I changed it because jphackworth is too long, and nsjph matches my twitter.* 47 | 48 | ## For Developers 49 | 50 | There's not much to see at the moment. 51 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 JPH 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "bytes" 19 | "encoding/hex" 20 | "fmt" 21 | "github.com/BurntSushi/toml" 22 | "github.com/codegangsta/cli" 23 | "github.com/nsjph/cryptoauth" 24 | "io/ioutil" 25 | "net" 26 | "os" 27 | ) 28 | 29 | // type tomlConfig struct { 30 | // Server serverConfig 31 | // } 32 | 33 | // type serverConfig struct { 34 | // Listen string `toml:"listen"` 35 | // Device string `toml:"device"` 36 | // PublicKey string `toml:"public_key"` 37 | // PrivateKey string `toml:"private_key"` 38 | // IPv6 string `toml:"ipv6"` 39 | // } 40 | 41 | // getApp is used to configure the command-line defaults, arguments and flags of kestrel 42 | // 43 | // It uses the cli package from https://github.com/codegangsta/cli 44 | func getApp() *cli.App { 45 | app := cli.NewApp() 46 | app.Name = "kestrel" 47 | app.Usage = "An experimental cjdns router" 48 | app.Author = "JPH" 49 | app.Email = "jph@hackworth.be" 50 | app.Version = "0.1.0a" 51 | app.Commands = []cli.Command{ 52 | { 53 | Name: "genconf", 54 | Usage: "generate a new config", 55 | Action: func(c *cli.Context) { 56 | generateConfig() 57 | }, 58 | }, 59 | } 60 | 61 | app.Flags = []cli.Flag{ 62 | cli.StringFlag{ 63 | Name: "config, c", 64 | Value: "/etc/kestrel/kestrel.toml", 65 | Usage: "Config file location", 66 | }, 67 | } 68 | 69 | app.Action = func(c *cli.Context) { 70 | 71 | //config := readConfigFile(c.String("config")) 72 | run(c.String("config")) 73 | println("hi!") 74 | } 75 | return app 76 | } 77 | 78 | // Reads the kestrel config file and decodes into tomlConfig 79 | func readConfigFile(configPath string) TomlConfig { 80 | configData, err := ioutil.ReadFile(configPath) 81 | if err != nil { 82 | fmt.Fprintf(os.Stderr, "Fatal error %s\n", err) 83 | os.Exit(1) 84 | } 85 | 86 | var conf TomlConfig 87 | _, err = toml.Decode(string(configData), &conf) 88 | check(err) 89 | return conf 90 | } 91 | 92 | // Checks that the config has the minimum info to start kestrel: 93 | // - public key 94 | // - private key 95 | // - valid ipv6 96 | // - valid listen address 97 | func validateConfig(config TomlConfig) { 98 | 99 | } 100 | 101 | // Creates a new kestrel config and prints to stdout 102 | func generateConfig() error { 103 | conf := TomlConfig{} 104 | keys, err := cryptoauth.NewIdentityKeys() 105 | checkFatal(err) 106 | conf.Server.IPv6 = keys.IPv6.String() 107 | conf.Server.PublicKey = fmt.Sprintf("%s.k", cryptoauth.Base32Encode(keys.PublicKey[:])[:52]) 108 | conf.Server.PrivateKey = hex.EncodeToString(keys.PrivateKey[:]) 109 | conf.Server.Listen = generateListenAddress() 110 | conf.Server.Device = "tun1" 111 | buf := new(bytes.Buffer) 112 | err = toml.NewEncoder(buf).Encode(conf) 113 | checkFatal(err) 114 | fmt.Println(buf.String()) 115 | return nil 116 | } 117 | 118 | // Creates a local UDP IPv4 address host:port combination for kestrel to use 119 | // 120 | // By default, set to listen on all IPv4 interfaces (0.0.0.0) 121 | // Will attempt to listen on a random high port temporarily and will assign this if successful. 122 | // 123 | // Returns a string in the format of "host:port", for example "0.0.0.0:30000" 124 | func generateListenAddress() (listenAddress string) { 125 | addr, err := net.ResolveUDPAddr("udp4", "0.0.0.0:0") 126 | check(err) 127 | conn, err := net.ListenUDP("udp4", addr) 128 | check(err) 129 | listenAddress = conn.LocalAddr().String() 130 | conn.Close() 131 | return listenAddress 132 | } 133 | -------------------------------------------------------------------------------- /docs/config.md: -------------------------------------------------------------------------------- 1 | # kestrel Config Files 2 | 3 | ## Overview 4 | 5 | kestrel config files are separated into two groups. 6 | 7 | /etc/kestrel/kestrel.conf (TOML format) 8 | /etc/kestrel/peers.json 9 | 10 | By separating the files, we can continue to support and interoperate with users of cjdns via the standard json-formatted peer credentials, but move new functionality into the human-readable TOML formatted main config file. 11 | 12 | ## kestrel.conf 13 | 14 | This file is [TOML](https://github.com/toml-lang/toml)-formatted. 15 | 16 | It has the following sections: 17 | 18 | * Server 19 | * Auth 20 | * UDPInterface 21 | * Admin 22 | * Logging 23 | 24 | ### Server section 25 | 26 | The server section has the following minimum sections 27 | * public_key 28 | * private_key 29 | * ipv6_address 30 | * daemonize 31 | 32 | Example: 33 | 34 | [server] 35 | public_key = "..." 36 | private_key = "..." 37 | ipv6_address = "..." 38 | daemonize = true 39 | 40 | ### Auth section 41 | 42 | This section contains passwords for remote peers. 43 | 44 | Example: 45 | 46 | [auth.peer1] 47 | password = "something very secure" 48 | 49 | Other information can be included optionally: 50 | 51 | [auth.peer2] 52 | password = "something very secure" 53 | email = "peer2@example.com" 54 | 55 | 56 | ### Admin section 57 | 58 | This section manages the admin RPC interface for kestrel. 59 | 60 | TBC 61 | 62 | ### Logging section 63 | 64 | This section manages log-related configuration 65 | 66 | Example: 67 | 68 | [logging] 69 | enable = true 70 | level = info 71 | logger = file # or stderr 72 | path = /var/log/kestrel.log 73 | 74 | ## peers.json 75 | 76 | TBC -------------------------------------------------------------------------------- /docs/cryptoauth.md: -------------------------------------------------------------------------------- 1 | # CryptoAuth Protocol 2 | 3 | ## Introduction 4 | 5 | CryptoAuth is the section of the cjdns protocol stack used for establishing and 6 | communicating between peers across untrusted networks. This is a document to 7 | describe the various parts of CryptoAuth and provide a rough guide for implementors. 8 | 9 | ### Notes to implementors 10 | 11 | * There is not one single, universal packet type to cryptoauth, but several, dependant on the state of the connection between peers 12 | * Everything sent across the wire is BigEndian. Remember to convert 13 | 14 | # Handshake Packets 15 | 16 | A handshake packet is used when establishing an encrypted session between two peers. 17 | 18 | A handshake has five states. These are canonically defined in cjdns/crypto/cryptoauth.h. Handshake packets include the state to enable the remote peer to understand what response is expected. 19 | 20 | * (**0**) A new CryptoAuth session, has not sent or received anything 21 | * (**1**) Sent a hello message, waiting for a reply 22 | * (**2**) Received a hello message, sent a key message, waiting for the session to complete 23 | * (**3**) Sent a hello message and received a key message but have not gotten a data message yet 24 | * (**4**) The handshake is successful and received at least one message 25 | 26 | 27 | ## 0. Connect to Me Packet 28 | 29 | A connect to me packet is an uncommon state, where a remote peer knows your IP, but doesn't know your permanent public key. It's not clear when that state will occur, as modern cjdroute installations require(?) at minimum a host, port, password and public key to be present in the connectTo section of cjdroute.conf. 30 | 31 | Since the remote peer doesn't know your permanent public key, it asks for it. 32 | 33 | ### Packet Structure 34 | 35 | ## 1. Hello Packet (Sending) 36 | 37 | The sending node is attempting to establish a cryptoauth session, and sends a handshake packet with the session state set to uint32(1) and their own permanent public key. 38 | 39 | The other fields in the Handshake packet structure should be random bytes. The only important fields are the session state and permanent public key. 40 | 41 | ### Packet Structure 42 | 43 | A hello packet (sending) uses the following structure: 44 | 45 | 1 2 3 46 | 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 47 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 48 | 0 | Session State (1) - uint32 | 49 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 50 | 4 | | 51 | + + 52 | 8 | Random 36 bytes | 53 | + (replacing challenge and handshake nonce) + 54 | 12 | | 55 | + + 56 | 16 | | 57 | + + 58 | 20 | | 59 | + + 60 | 24 | | 61 | + + 62 | 28 | | 63 | + + 64 | 32 | | 65 | + + 66 | 36 | | 67 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 68 | 40 | | 69 | + + 70 | 44 | | 71 | + + 72 | 48 | | 73 | + + 74 | 52 | | 75 | + Permanent Public Key + 76 | 56 | 32 bytes / uint8 | 77 | + + 78 | 60 | | 79 | + + 80 | 64 | | 81 | + + 82 | 68 | | 83 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 84 | 72 | | 85 | + + 86 | 76 | | 87 | + Random 48 bytes + 88 | 80 | (replaces authenticator and temp pub key) | 89 | + + 90 | 84 | | 91 | + + 92 | 88 | | 93 | + + 94 | 92 | | 95 | + + 96 | 96 | | 97 | + + 98 | 100 | | 99 | + + 100 | 104 | | 101 | + + 102 | 108 | | 103 | + + 104 | 112 | | 105 | + + 106 | 116 | | 107 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 108 | | | 109 | + Variable Length Encrypted/Authenticated Content + 110 | | | 111 | 112 | 113 | ## 2. Hello Packet (Acknowledgement), Key Packet (Sending) 114 | 115 | ### Packet Structure 116 | 117 | 118 | ## 3. Key Packet (Acknowledgement), Data Message not received 119 | 120 | ## 4. Handshake successful 121 | 122 | ## 123 | 124 | # Data Packet 125 | 126 | # Message Packet 127 | 128 | # Handshakes 129 | 130 | # References 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /docs/design.md: -------------------------------------------------------------------------------- 1 | # Design 2 | 3 | ## Goals 4 | 5 | The following are the design goals for kestrel. There are some differences from cjdroute. 6 | 7 | 1. Interoperate with existing cjdroute 8 | 2. Linux support first. Others platforms are secondary 9 | 3. Daemon process can open files. Rely on apparmor/SELinux profiles for security. 10 | 4. Stability over speed. 11 | 5. Writing clean / standard code wherever possible. No hacks without good reason. 12 | 13 | ## Architecture 14 | 15 | TBC 16 | 17 | ## Startup / Daemonization 18 | 19 | TBC 20 | 21 | ## Logging / Debugging 22 | 23 | TBC 24 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | const ( 4 | ERROR_NONE = 0 5 | ERROR_MALFORMED_ADDRESS = 1 6 | ERROR_FLOOD = 2 7 | ERROR_LINK_LIMIT_EXCEEDED = 3 8 | ERROR_OVERSIZE_MESSAGE = 4 9 | ERROR_UNDERSIZE_MESSAGE = 5 10 | ERROR_AUTHENTICATION = 6 11 | ERROR_INVALID = 7 12 | ERROR_UNDELIVERABLE = 8 13 | ERROR_LOOP_ROUTE = 9 14 | ERROR_RETURN_PATH_INVALID = 10 15 | ERROR_UNKNOWN = 11 16 | ERROR_NOT_IMPLEMENTED = 12 17 | ) 18 | 19 | var ( 20 | cjdnsErrors = map[int]string{ 21 | 0: "ERROR_NONE", 22 | 1: "ERROR_MALFORMED_ADDRESS", 23 | 2: "ERROR_FLOOD", 24 | 3: "ERROR_LINK_LIMIT_EXCEEDED", 25 | 4: "ERROR_OVERSIZE_MESSAGE", 26 | 5: "ERROR_UNDERSIZE_MESSAGE", 27 | 6: "ERROR_AUTHENTICATION", 28 | 7: "ERROR_INVALID", 29 | 8: "ERROR_UNDELIVERABLE", 30 | 9: "ERROR_LOOP_ROUTE", 31 | 10: "ERROR_RETURN_PATH_INVALID", 32 | 11: "ERROR_UNKNOWN", 33 | 12: "ERROR_NOT_IMPLEMENTED", 34 | } 35 | errNone = newError(0, "No error") 36 | errMalformedAddress = newError(1, "Malformed address") 37 | errFlood = newError(2, "Traffic flood") 38 | errLinkLimitExceeded = newError(3, "Link limit exceeded") 39 | errOverSizeMessage = newError(4, "Oversize message") 40 | errUndersizeMessage = newError(5, "Undersize message") 41 | errAuthentication = newError(6, "Authentication error") 42 | errInvalid = newError(7, "Invalid") // TODO: check what/when raises this type of error 43 | errUndeliverable = newError(8, "Undeliverable") 44 | errLoopRoute = newError(9, "Invalid route due to loop") 45 | errReturnPathInvalid = newError(10, "Invalid return path") 46 | errUnknown = newError(11, "Unknown Error") 47 | errNotImplemented = newError(12, "Feature not implemented") 48 | ) 49 | 50 | // type protocolError interface { 51 | // error 52 | // Timeout() bool 53 | // Temporary() bool 54 | // } 55 | 56 | // type OpError struct { 57 | // Op string // type of operation being performed at time of error 58 | // Addr Addr // peer Address where this occured 59 | // Err error 60 | // } 61 | 62 | // Still experimenting with the right approach to handling cjdns-related errors in an 63 | // extensible way. Expect change and placeholders. 64 | 65 | type cjdnsError struct { 66 | Code int 67 | Message string 68 | Details string 69 | Timeout bool // is error a timeout? 70 | Temporary bool // is error temporary? 71 | Err error 72 | } 73 | 74 | //func newError(errcode int, errmsg string, isTimeoutError bool, isTemporaryError bool) *cjdnsError { 75 | 76 | func newError(errcode int, errmsg string) *cjdnsError { 77 | err := &cjdnsError{ 78 | Code: errcode, 79 | Message: errmsg, 80 | Details: "", 81 | Timeout: false, 82 | Temporary: false, 83 | } 84 | 85 | return err 86 | } 87 | 88 | func (err *cjdnsError) Error() string { 89 | return err.Message 90 | } 91 | 92 | // addDetails lets you leverage an existing default message type, such as 93 | // errUndeliverable, but allows you to add extra details to the error message 94 | // 95 | // TODO: Check if this is performant, or if there's a better way to do same thing 96 | // 97 | // example: return errUndeliverable.addDetails("decryption failed") 98 | func (err cjdnsError) addDetails(details string) *cjdnsError { 99 | detailedErr := err 100 | detailedErr.Details = details 101 | return &detailedErr 102 | } 103 | 104 | func (err *cjdnsError) isTimeout() bool { 105 | return err.Timeout 106 | } 107 | 108 | func (err *cjdnsError) isTemporary() bool { 109 | return err.Temporary 110 | } 111 | -------------------------------------------------------------------------------- /glisp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/zhemao/glisp" 5 | "golang.org/x/crypto/ssh" 6 | ) 7 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 JPH 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "github.com/adampresley/sigint" 19 | "os" 20 | "time" 21 | ) 22 | 23 | var server *ServerInfo 24 | 25 | func run(configFile string) { 26 | sleepInterval := 60 27 | 28 | config := readConfigFile(configFile) 29 | udpServer := config.Server.newUDPServer() 30 | udpServer.start() 31 | 32 | for { 33 | //udpServer.log.Debug("Main thread sleeping for %d seconds\n", sleepInterval) 34 | time.Sleep(time.Duration(sleepInterval) * time.Second) 35 | } 36 | } 37 | 38 | func main() { 39 | 40 | sigint.ListenForSIGINT(func() { 41 | server.Shutdown() 42 | }) 43 | 44 | app := getApp() 45 | app.Run(os.Args) 46 | 47 | } 48 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/hex" 5 | "github.com/nsjph/cryptoauth" 6 | "log" 7 | "os" 8 | ) 9 | 10 | // func startServer(c TomlConfig) *ServerInfo { 11 | // s := &ServerInfo{Server: startUDPServer(c.Server.Listen), 12 | // TunDevice: startTunDevice(c)} 13 | 14 | // return s 15 | // } 16 | 17 | func (s *ServerInfo) Shutdown() { 18 | log.Printf("shutting down") 19 | os.Exit(0) 20 | } 21 | 22 | func (c *ServerConfig) getServerKeyPair() *KeyPair { 23 | 24 | kp := &KeyPair{} 25 | 26 | pubkey, err := cryptoauth.Base32Decode([]byte(c.PublicKey[:52])) 27 | check(err) 28 | copy(kp.publicKey[:], pubkey[:32]) 29 | 30 | _, err = hex.Decode(kp.privateKey[:], []byte(c.PrivateKey)) 31 | check(err) 32 | 33 | return kp 34 | 35 | } 36 | -------------------------------------------------------------------------------- /tun/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 JPH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /tun/NOTICE: -------------------------------------------------------------------------------- 1 | Software Credits 2 | The development of this software was made possible using the following components: 3 | 4 | govpn by Jay True (Unknown License) 5 | An OpenVPN clone written in go 6 | https://github.com/glacjay/govpn 7 | 8 | netlink by Vish Ishaya (Apache License 2.0) 9 | Simple netlink library for go. 10 | https://github.com/vishvananda 11 | 12 | 13 | -------------------------------------------------------------------------------- /tun/tun.go: -------------------------------------------------------------------------------- 1 | package tun 2 | 3 | import ( 4 | "fmt" 5 | "github.com/vishvananda/netlink" 6 | "log" 7 | "os" 8 | ) 9 | 10 | type Tun struct { 11 | fd *os.File 12 | link netlink.Link 13 | actualName string 14 | ReadCh chan []byte 15 | WriteCh chan []byte 16 | } 17 | 18 | func (tun *Tun) Name() string { 19 | return tun.actualName 20 | } 21 | 22 | func New() *Tun { 23 | tun := &Tun{ReadCh: make(chan []byte), WriteCh: make(chan []byte)} 24 | return tun 25 | } 26 | 27 | func (tun *Tun) Start() { 28 | go tun.readLoop() 29 | go tun.writeLoop() 30 | } 31 | 32 | func (tun *Tun) writeLoop() { 33 | for { 34 | buf := <-tun.WriteCh 35 | _, err := tun.fd.Write(buf) 36 | if err != nil { 37 | log.Printf("[EROR] TUN/TAP: write failed: %v: %v", err, buf) 38 | tun.fd.Close() 39 | return 40 | } 41 | } 42 | } 43 | 44 | func (tun *Tun) ReadPacket() { 45 | var buf [4096]byte 46 | log.Println("about to read from fd") 47 | nread, err := tun.fd.Read(buf[:]) 48 | //log.Println(nread) 49 | if nread > 0 { 50 | b := make([]byte, nread) 51 | copy(b, buf[:nread]) 52 | fmt.Printf("x %x", b) 53 | tun.ReadCh <- b 54 | } 55 | if nread == 0 { 56 | log.Printf("closing tun fd") 57 | tun.fd.Close() 58 | return 59 | } 60 | if err != nil { 61 | log.Printf("[EROR] TUN/TAP: read failed: %v", err) 62 | tun.fd.Close() 63 | return 64 | } 65 | } 66 | 67 | func (tun *Tun) readLoop() { 68 | var buf [4096]byte 69 | for { 70 | nread, err := tun.fd.Read(buf[:]) 71 | if nread > 0 { 72 | b := make([]byte, nread) 73 | copy(b, buf[:nread]) 74 | fmt.Printf("x %x", b) 75 | tun.ReadCh <- b 76 | } 77 | if nread == 0 { 78 | log.Printf("closing tun fd") 79 | tun.fd.Close() 80 | return 81 | } 82 | if err != nil { 83 | log.Printf("[EROR] TUN/TAP: read failed: %v", err) 84 | tun.fd.Close() 85 | return 86 | } 87 | } 88 | } 89 | 90 | func (tun *Tun) Stop() { 91 | tun.fd.Close() 92 | } 93 | -------------------------------------------------------------------------------- /tun/tun_darwin.go: -------------------------------------------------------------------------------- 1 | package tun 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "os/exec" 8 | ) 9 | 10 | func (tun *Tun) Open() { 11 | dynamicOpened := false 12 | dynamicName := "" 13 | for i := 0; i < 16; i++ { 14 | tunName := fmt.Sprintf("/dev/tun%d", i) 15 | dynamicName = fmt.Sprintf("tun%d", i) 16 | fd, err := os.OpenFile(tunName, os.O_RDWR, 0) 17 | if err == nil { 18 | tun.fd = fd 19 | dynamicOpened = true 20 | break 21 | } 22 | log.Printf("[WARN] Failed to open TUN/TAP device '%s': %v", dynamicName, err) 23 | } 24 | if !dynamicOpened { 25 | log.Fatalf("[CRIT] Cannot allocate TUN/TAP device dynamically.") 26 | } 27 | 28 | tun.actualName = dynamicName 29 | log.Printf("[INFO] TUN/TAP device %s opened.", tun.actualName) 30 | } 31 | 32 | func (tun *Tun) SetupAddress(addr, mask string) { 33 | cmd := exec.Command("/sbin/ifconfig", tun.actualName, "delete") 34 | _ = cmd.Run() 35 | log.Printf("[INFO] NOTE: Tried to delete pre-existing TUN/TAP instance -- no problem if failed.") 36 | 37 | cmd = exec.Command("/sbin/ifconfig", tun.actualName, 38 | addr, addr, "netmask", mask, "mtu", "1500", "up") 39 | output, err := cmd.CombinedOutput() 40 | if err != nil { 41 | log.Fatalf("[CRIT] Mac OS X ifconfig failed: %v: %s", err, output) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tun/tun_linux.go: -------------------------------------------------------------------------------- 1 | package tun 2 | 3 | import ( 4 | _ "fmt" 5 | "github.com/vishvananda/netlink" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | const ( 16 | IFF_NO_PI = 0x10 17 | IFF_TUN = 0x01 18 | IFF_TAP = 0x02 19 | TUNSETIFF = 0x400454CA 20 | ) 21 | 22 | func (tun *Tun) Open() { 23 | deviceFile := "/dev/net/tun" 24 | fd, err := os.OpenFile(deviceFile, os.O_RDWR, 0) 25 | if err != nil { 26 | log.Fatalf("[CRIT] Note: Cannot open TUN/TAP dev %s: %v", deviceFile, err) 27 | } 28 | tun.fd = fd 29 | //tun.link = netlink.LinkByName(string(ifr)) 30 | 31 | ifr := make([]byte, 18) 32 | ifr[17] = IFF_NO_PI 33 | ifr[16] = IFF_TUN 34 | _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, 35 | uintptr(tun.fd.Fd()), uintptr(TUNSETIFF), 36 | uintptr(unsafe.Pointer(&ifr[0]))) 37 | if errno != 0 { 38 | log.Fatalf("[CRIT] Cannot ioctl TUNSETIFF: %v", errno) 39 | } 40 | 41 | tun.actualName = string(ifr) 42 | tun.actualName = tun.actualName[:strings.Index(tun.actualName, "\000")] 43 | tun.link, err = netlink.LinkByName(tun.actualName) 44 | check(err) 45 | log.Printf("[INFO] TUN/TAP device %s opened.", tun.actualName) 46 | } 47 | 48 | func (tun *Tun) SetupAddress(newAddr string, newMTU int) { 49 | 50 | cmd1 := exec.Command("/sbin/ip", "link", "set", "dev", tun.actualName, "up") 51 | log.Printf("[DEBG] ip(8) command: %v", strings.Join(cmd1.Args, " ")) 52 | err := cmd1.Run() 53 | check(err) 54 | 55 | log.Printf("mtu is %s", strconv.Itoa(newMTU)) 56 | 57 | cmd2 := exec.Command("/sbin/ip", "link", "set", "dev", tun.actualName, "mtu", strconv.Itoa(newMTU)) 58 | log.Printf("[DEBG] ip(8) command: %v", strings.Join(cmd2.Args, " ")) 59 | err = cmd2.Run() 60 | check(err) 61 | 62 | cmd3 := exec.Command("/sbin/ip", "-6", "addr", "add", newAddr, "dev", tun.actualName) 63 | log.Printf("[DEBG] ip(8) command: %v", strings.Join(cmd3.Args, " ")) 64 | err = cmd3.Run() 65 | check(err) 66 | 67 | //tun.AddAddress(newAddr) 68 | //tun.SetMTU(newMTU) 69 | } 70 | 71 | //func (tun *Tun) AddAddress(newAddr string) { 72 | // addr_with_mask := fmt.Sprintf("%s/8", newAddr) 73 | // fmt.Println(addr_with_mask) 74 | 75 | // addr, err := netlink.ParseAddr(fmt.Sprintf("%s/8", newAddr)) 76 | // if err != nil { 77 | // log.Fatalf("Cannot parse address: %s", addr_with_mask) 78 | // } 79 | // fmt.Printf("Assigning address to %s\n", tun.link.Attrs().Name) 80 | // log.Printf("Assigning %s to %s", addr_with_mask, tun.link.Attrs().Name) 81 | // err = netlink.AddrAdd(tun.link, addr) 82 | // check(err) 83 | // } 84 | 85 | // func (tun *Tun) SetMTU(newMTU int) { 86 | // log.Printf("Setting %s MTU to %d", tun.link.Attrs().Name, newMTU) 87 | // err := netlink.LinkSetMTU(tun.link, newMTU) 88 | // check(err) 89 | // } 90 | 91 | // func (tun *Tun) SetupAddress2(addr, mask string) { 92 | // cmd := exec.Command("ifconfig", tun.actualName, addr, 93 | // "netmask", mask, "mtu", "1500") 94 | // log.Printf("[DEBG] ifconfig command: %v", strings.Join(cmd.Args, " ")) 95 | // err := cmd.Run() 96 | // if err != nil { 97 | // log.Printf("[EROR] Linux ifconfig failed: %v.", err) 98 | // } 99 | // } 100 | -------------------------------------------------------------------------------- /tun/util.go: -------------------------------------------------------------------------------- 1 | package tun 2 | 3 | func check(e error) { 4 | if e != nil { 5 | panic(e) 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/sirupsen/logrus" 5 | "net" 6 | ) 7 | 8 | type ServerInfo struct { 9 | //Conn *net.UDPConn 10 | Server *UDPServer 11 | Peers []PeerInfo 12 | } 13 | 14 | type Account struct { 15 | username []byte 16 | password string 17 | secret [32]byte 18 | secondHash [32]byte 19 | restrictedToIPv6 *net.Addr 20 | } 21 | 22 | // TODO: Move the server-side credentials away from the *Peer 23 | // particularly the accounts 24 | type CryptoAuth_Auth struct { 25 | //accounts []*Account 26 | accounts map[[32]byte]*Account // key is the hashed version of the password 27 | keyPair *KeyPair 28 | log *logrus.Logger // go-logging 29 | } 30 | 31 | type PeerInfo struct { 32 | PublicAddress *net.IPAddr 33 | CjdnsAddress *net.IPAddr 34 | Conn *net.UDPConn 35 | Password []byte 36 | PublicKey []byte 37 | SharedKey []byte 38 | } 39 | 40 | type TomlConfig struct { 41 | Server ServerConfig 42 | } 43 | 44 | type ServerConfig struct { 45 | Listen string `toml:"listen"` 46 | Device string `toml:"device"` 47 | PublicKey string `toml:"public_key"` 48 | PrivateKey string `toml:"private_key"` 49 | IPv6 string `toml:"ipv6"` 50 | Password string `toml:"password"` 51 | } 52 | 53 | type UDPServer struct { 54 | conn *net.UDPConn 55 | keyPair *KeyPair 56 | config *ServerConfig 57 | bufsz int 58 | padsz int 59 | log *logrus.Logger 60 | //log *logging.Logger // go-logging 61 | peers map[string]*Peer 62 | accounts []*Account 63 | auth *CryptoAuth_Auth 64 | } 65 | 66 | type InterfaceController struct { 67 | ifaces []*UDPServer 68 | } 69 | 70 | // type Router struct { 71 | // Iface *tun.Tun 72 | // PublicKey [32]byte 73 | // PrivateKey [32]byte 74 | // UDPConn *net.UDPConn 75 | // Config *ServerConfig 76 | // BufSz int 77 | // Log *logging.Logger // go-logging 78 | // Peers3 map[string]*Peer 79 | // Peers map[[32]byte]*Peer 80 | // keyPair *KeyPair 81 | // } 82 | 83 | type Passwd struct { 84 | user [32]byte // username string, max 32 bytes 85 | password [32]byte // hashed form of password loaded from kestrel.toml 86 | publicKey []byte // future use - allow only a given public key to use this password 87 | addr *net.IPAddr // future use - allow on a given remote ip addr to use this password 88 | } 89 | 90 | type KeyPair struct { 91 | publicKey [32]byte 92 | privateKey [32]byte 93 | } 94 | 95 | type Peer struct { 96 | name string 97 | addr *net.UDPAddr 98 | conn *net.UDPConn 99 | //server *UDPServer 100 | password []byte // static password for incoming / outgoing peers..? 101 | state uint32 // handshake state or nonce 102 | nextNonce uint32 103 | tempKeyPair *KeyPair // This is our tempKeyPair, not actually the peers 104 | sharedSecret [32]byte 105 | passwordHash [32]byte 106 | publicKey [32]byte // the remote peer's permanent public key 107 | tempPublicKey [32]byte // This is the remote peer's temporary public key 108 | //log *logging.Logger 109 | log *logrus.Logger 110 | //passwordHash [32]byte 111 | initiator bool 112 | established bool 113 | requireAuth bool 114 | timeOfLastPacket uint32 115 | replayProtector *ReplayProtector 116 | } 117 | 118 | type ReplayProtector struct { 119 | bitfield uint64 120 | baseOffset uint32 121 | duplicates uint32 122 | lostPackets uint32 123 | receivedOutOfRange uint32 124 | } 125 | 126 | // type Message struct { 127 | // length uint32 128 | // padding uint32 129 | // payload []byte 130 | // capacity uint32 131 | // } 132 | 133 | type EncryptedMessage2 struct { 134 | handshake [120]byte 135 | payload []byte 136 | } 137 | -------------------------------------------------------------------------------- /udp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 JPH 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "github.com/sirupsen/logrus" 19 | "net" 20 | "os" 21 | "syscall" 22 | ) 23 | 24 | const ( 25 | UDP_MAX_PACKET_SIZE = 8192 26 | UDP_PADDING = 512 27 | UDP_MAX_PACKET_PAYLOAD = UDP_MAX_PACKET_SIZE - UDP_PADDING 28 | ) 29 | 30 | func (c *ServerConfig) newUDPServer() *UDPServer { 31 | 32 | u := new(UDPServer) 33 | 34 | u.bufsz = UDP_MAX_PACKET_SIZE 35 | u.padsz = UDP_PADDING 36 | u.config = c 37 | u.log = logrus.New() 38 | //u.log. 39 | u.log.Out = os.Stderr 40 | u.log.Level = logrus.DebugLevel 41 | 42 | return u 43 | } 44 | 45 | func (u *UDPServer) start() { 46 | 47 | u.log.Debug("Starting UDP Interface on %s", u.config.Listen) 48 | u.listen() 49 | } 50 | 51 | func (u *UDPServer) listen() { 52 | 53 | localAddr, err := net.ResolveUDPAddr("udp4", u.config.Listen) 54 | checkFatal(err) 55 | 56 | u.conn, err = net.ListenUDP("udp4", localAddr) 57 | checkFatal(err) 58 | 59 | f, err := u.conn.File() 60 | defer f.Close() 61 | checkFatal(err) 62 | fd := int(f.Fd()) 63 | // This one makes sure all packets we send out do not have DF set on them. 64 | err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_MTU_DISCOVER, syscall.IP_PMTUDISC_DONT) 65 | checkFatal(err) 66 | 67 | u.log.Debug("UDPServer.listen(): going into read loop") 68 | go u.readLoop() 69 | } 70 | func (u *UDPServer) readLoop() { 71 | defer u.conn.Close() 72 | payload := make([]byte, u.bufsz) // TODO: optimize 73 | oob := make([]byte, 4096) // TODO: optimize 74 | 75 | for { 76 | 77 | n, oobn, _, _, err := u.conn.ReadMsgUDP(payload, oob) 78 | u.log.Debug("UDPServer.readLoop(): payload[%d], oob[%d]", n, oobn) 79 | checkFatal(err) 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 JPH 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "log" 19 | ) 20 | 21 | func check(e error) { 22 | if e != nil { 23 | panic(e) 24 | } 25 | } 26 | 27 | func checkFatal(e error) { 28 | if e != nil { 29 | log.Fatal(e) 30 | } 31 | } 32 | 33 | func isEmpty(x [32]byte) bool { 34 | if x == [32]byte{} { 35 | return true 36 | } 37 | return false 38 | } 39 | --------------------------------------------------------------------------------