ntor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Copyright (c) 2014, Yawning Angel <yawning at torproject dot org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. *
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  19. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  25. * POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // Package ntor implements the Tor Project's ntor handshake as defined in
  28. // proposal 216 "Improved circuit-creation key exchange". It also supports
  29. // using Elligator to transform the Curve25519 public keys sent over the wire
  30. // to a form that is indistinguishable from random strings.
  31. //
  32. // Before using this package, it is strongly recommended that the specification
  33. // is read and understood.
  34. package ntor // import "gitlab.com/yawning/obfs4.git/common/ntor"
  35. import (
  36. "bytes"
  37. "crypto/hmac"
  38. "crypto/sha256"
  39. "crypto/subtle"
  40. "encoding/hex"
  41. "fmt"
  42. "io"
  43. "github.com/agl/ed25519/extra25519"
  44. "gitlab.com/yawning/obfs4.git/common/csrand"
  45. "golang.org/x/crypto/curve25519"
  46. "golang.org/x/crypto/hkdf"
  47. )
  48. const (
  49. // PublicKeyLength is the length of a Curve25519 public key.
  50. PublicKeyLength = 32
  51. // RepresentativeLength is the length of an Elligator representative.
  52. RepresentativeLength = 32
  53. // PrivateKeyLength is the length of a Curve25519 private key.
  54. PrivateKeyLength = 32
  55. // SharedSecretLength is the length of a Curve25519 shared secret.
  56. SharedSecretLength = 32
  57. // NodeIDLength is the length of a ntor node identifier.
  58. NodeIDLength = 20
  59. // KeySeedLength is the length of the derived KEY_SEED.
  60. KeySeedLength = sha256.Size
  61. // AuthLength is the lenght of the derived AUTH.
  62. AuthLength = sha256.Size
  63. )
  64. var protoID = []byte("ntor-curve25519-sha256-1")
  65. var tMac = append(protoID, []byte(":mac")...)
  66. var tKey = append(protoID, []byte(":key_extract")...)
  67. var tVerify = append(protoID, []byte(":key_verify")...)
  68. var mExpand = append(protoID, []byte(":key_expand")...)
  69. // PublicKeyLengthError is the error returned when the public key being
  70. // imported is an invalid length.
  71. type PublicKeyLengthError int
  72. func (e PublicKeyLengthError) Error() string {
  73. return fmt.Sprintf("ntor: Invalid Curve25519 public key length: %d",
  74. int(e))
  75. }
  76. // PrivateKeyLengthError is the error returned when the private key being
  77. // imported is an invalid length.
  78. type PrivateKeyLengthError int
  79. func (e PrivateKeyLengthError) Error() string {
  80. return fmt.Sprintf("ntor: Invalid Curve25519 private key length: %d",
  81. int(e))
  82. }
  83. // NodeIDLengthError is the error returned when the node ID being imported is
  84. // an invalid length.
  85. type NodeIDLengthError int
  86. func (e NodeIDLengthError) Error() string {
  87. return fmt.Sprintf("ntor: Invalid NodeID length: %d", int(e))
  88. }
  89. // KeySeed is the key material that results from a handshake (KEY_SEED).
  90. type KeySeed [KeySeedLength]byte
  91. // Bytes returns a pointer to the raw key material.
  92. func (key_seed *KeySeed) Bytes() *[KeySeedLength]byte {
  93. return (*[KeySeedLength]byte)(key_seed)
  94. }
  95. // Auth is the verifier that results from a handshake (AUTH).
  96. type Auth [AuthLength]byte
  97. // Bytes returns a pointer to the raw auth.
  98. func (auth *Auth) Bytes() *[AuthLength]byte {
  99. return (*[AuthLength]byte)(auth)
  100. }
  101. // NodeID is a ntor node identifier.
  102. type NodeID [NodeIDLength]byte
  103. // NewNodeID creates a NodeID from the raw bytes.
  104. func NewNodeID(raw []byte) (*NodeID, error) {
  105. if len(raw) != NodeIDLength {
  106. return nil, NodeIDLengthError(len(raw))
  107. }
  108. nodeID := new(NodeID)
  109. copy(nodeID[:], raw)
  110. return nodeID, nil
  111. }
  112. // NodeIDFromHex creates a new NodeID from the hexdecimal representation.
  113. func NodeIDFromHex(encoded string) (*NodeID, error) {
  114. raw, err := hex.DecodeString(encoded)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return NewNodeID(raw)
  119. }
  120. // Bytes returns a pointer to the raw NodeID.
  121. func (id *NodeID) Bytes() *[NodeIDLength]byte {
  122. return (*[NodeIDLength]byte)(id)
  123. }
  124. // Hex returns the hexdecimal representation of the NodeID.
  125. func (id *NodeID) Hex() string {
  126. return hex.EncodeToString(id[:])
  127. }
  128. // PublicKey is a Curve25519 public key in little-endian byte order.
  129. type PublicKey [PublicKeyLength]byte
  130. // Bytes returns a pointer to the raw Curve25519 public key.
  131. func (public *PublicKey) Bytes() *[PublicKeyLength]byte {
  132. return (*[PublicKeyLength]byte)(public)
  133. }
  134. // Hex returns the hexdecimal representation of the Curve25519 public key.
  135. func (public *PublicKey) Hex() string {
  136. return hex.EncodeToString(public.Bytes()[:])
  137. }
  138. // NewPublicKey creates a PublicKey from the raw bytes.
  139. func NewPublicKey(raw []byte) (*PublicKey, error) {
  140. if len(raw) != PublicKeyLength {
  141. return nil, PublicKeyLengthError(len(raw))
  142. }
  143. pubKey := new(PublicKey)
  144. copy(pubKey[:], raw)
  145. return pubKey, nil
  146. }
  147. // PublicKeyFromHex returns a PublicKey from the hexdecimal representation.
  148. func PublicKeyFromHex(encoded string) (*PublicKey, error) {
  149. raw, err := hex.DecodeString(encoded)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return NewPublicKey(raw)
  154. }
  155. // Representative is an Elligator representative of a Curve25519 public key
  156. // in little-endian byte order.
  157. type Representative [RepresentativeLength]byte
  158. // Bytes returns a pointer to the raw Elligator representative.
  159. func (repr *Representative) Bytes() *[RepresentativeLength]byte {
  160. return (*[RepresentativeLength]byte)(repr)
  161. }
  162. // ToPublic converts a Elligator representative to a Curve25519 public key.
  163. func (repr *Representative) ToPublic() *PublicKey {
  164. pub := new(PublicKey)
  165. extra25519.RepresentativeToPublicKey(pub.Bytes(), repr.Bytes())
  166. return pub
  167. }
  168. // PrivateKey is a Curve25519 private key in little-endian byte order.
  169. type PrivateKey [PrivateKeyLength]byte
  170. // Bytes returns a pointer to the raw Curve25519 private key.
  171. func (private *PrivateKey) Bytes() *[PrivateKeyLength]byte {
  172. return (*[PrivateKeyLength]byte)(private)
  173. }
  174. // Hex returns the hexdecimal representation of the Curve25519 private key.
  175. func (private *PrivateKey) Hex() string {
  176. return hex.EncodeToString(private.Bytes()[:])
  177. }
  178. // Keypair is a Curve25519 keypair with an optional Elligator representative.
  179. // As only certain Curve25519 keys can be obfuscated with Elligator, the
  180. // representative must be generated along with the keypair.
  181. type Keypair struct {
  182. public *PublicKey
  183. private *PrivateKey
  184. representative *Representative
  185. }
  186. // Public returns the Curve25519 public key belonging to the Keypair.
  187. func (keypair *Keypair) Public() *PublicKey {
  188. return keypair.public
  189. }
  190. // Private returns the Curve25519 private key belonging to the Keypair.
  191. func (keypair *Keypair) Private() *PrivateKey {
  192. return keypair.private
  193. }
  194. // Representative returns the Elligator representative of the public key
  195. // belonging to the Keypair.
  196. func (keypair *Keypair) Representative() *Representative {
  197. return keypair.representative
  198. }
  199. // HasElligator returns true if the Keypair has an Elligator representative.
  200. func (keypair *Keypair) HasElligator() bool {
  201. return nil != keypair.representative
  202. }
  203. // NewKeypair generates a new Curve25519 keypair, and optionally also generates
  204. // an Elligator representative of the public key.
  205. func NewKeypair(elligator bool) (*Keypair, error) {
  206. keypair := new(Keypair)
  207. keypair.private = new(PrivateKey)
  208. keypair.public = new(PublicKey)
  209. if elligator {
  210. keypair.representative = new(Representative)
  211. }
  212. for {
  213. // Generate a Curve25519 private key. Like everyone who does this,
  214. // run the CSPRNG output through SHA256 for extra tinfoil hattery.
  215. priv := keypair.private.Bytes()[:]
  216. if err := csrand.Bytes(priv); err != nil {
  217. return nil, err
  218. }
  219. digest := sha256.Sum256(priv)
  220. digest[0] &= 248
  221. digest[31] &= 127
  222. digest[31] |= 64
  223. copy(priv, digest[:])
  224. if elligator {
  225. // Apply the Elligator transform. This fails ~50% of the time.
  226. if !extra25519.ScalarBaseMult(keypair.public.Bytes(),
  227. keypair.representative.Bytes(),
  228. keypair.private.Bytes()) {
  229. continue
  230. }
  231. } else {
  232. // Generate the corresponding Curve25519 public key.
  233. curve25519.ScalarBaseMult(keypair.public.Bytes(),
  234. keypair.private.Bytes())
  235. }
  236. return keypair, nil
  237. }
  238. }
  239. // KeypairFromHex returns a Keypair from the hexdecimal representation of the
  240. // private key.
  241. func KeypairFromHex(encoded string) (*Keypair, error) {
  242. raw, err := hex.DecodeString(encoded)
  243. if err != nil {
  244. return nil, err
  245. }
  246. if len(raw) != PrivateKeyLength {
  247. return nil, PrivateKeyLengthError(len(raw))
  248. }
  249. keypair := new(Keypair)
  250. keypair.private = new(PrivateKey)
  251. keypair.public = new(PublicKey)
  252. copy(keypair.private[:], raw)
  253. curve25519.ScalarBaseMult(keypair.public.Bytes(),
  254. keypair.private.Bytes())
  255. return keypair, nil
  256. }
  257. // ServerHandshake does the server side of a ntor handshake and returns status,
  258. // KEY_SEED, and AUTH. If status is not true, the handshake MUST be aborted.
  259. func ServerHandshake(clientPublic *PublicKey, serverKeypair *Keypair, idKeypair *Keypair, id *NodeID) (ok bool, keySeed *KeySeed, auth *Auth) {
  260. var notOk int
  261. var secretInput bytes.Buffer
  262. // Server side uses EXP(X,y) | EXP(X,b)
  263. var exp [SharedSecretLength]byte
  264. curve25519.ScalarMult(&exp, serverKeypair.private.Bytes(),
  265. clientPublic.Bytes())
  266. notOk |= constantTimeIsZero(exp[:])
  267. secretInput.Write(exp[:])
  268. curve25519.ScalarMult(&exp, idKeypair.private.Bytes(),
  269. clientPublic.Bytes())
  270. notOk |= constantTimeIsZero(exp[:])
  271. secretInput.Write(exp[:])
  272. keySeed, auth = ntorCommon(secretInput, id, idKeypair.public,
  273. clientPublic, serverKeypair.public)
  274. return notOk == 0, keySeed, auth
  275. }
  276. // ClientHandshake does the client side of a ntor handshake and returnes
  277. // status, KEY_SEED, and AUTH. If status is not true or AUTH does not match
  278. // the value recieved from the server, the handshake MUST be aborted.
  279. func ClientHandshake(clientKeypair *Keypair, serverPublic *PublicKey, idPublic *PublicKey, id *NodeID) (ok bool, keySeed *KeySeed, auth *Auth) {
  280. var notOk int
  281. var secretInput bytes.Buffer
  282. // Client side uses EXP(Y,x) | EXP(B,x)
  283. var exp [SharedSecretLength]byte
  284. curve25519.ScalarMult(&exp, clientKeypair.private.Bytes(),
  285. serverPublic.Bytes())
  286. notOk |= constantTimeIsZero(exp[:])
  287. secretInput.Write(exp[:])
  288. curve25519.ScalarMult(&exp, clientKeypair.private.Bytes(),
  289. idPublic.Bytes())
  290. notOk |= constantTimeIsZero(exp[:])
  291. secretInput.Write(exp[:])
  292. keySeed, auth = ntorCommon(secretInput, id, idPublic,
  293. clientKeypair.public, serverPublic)
  294. return notOk == 0, keySeed, auth
  295. }
  296. // CompareAuth does a constant time compare of a Auth and a byte slice
  297. // (presumably received over a network).
  298. func CompareAuth(auth1 *Auth, auth2 []byte) bool {
  299. auth1Bytes := auth1.Bytes()
  300. return hmac.Equal(auth1Bytes[:], auth2)
  301. }
  302. func ntorCommon(secretInput bytes.Buffer, id *NodeID, b *PublicKey, x *PublicKey, y *PublicKey) (*KeySeed, *Auth) {
  303. keySeed := new(KeySeed)
  304. auth := new(Auth)
  305. // secret_input/auth_input use this common bit, build it once.
  306. suffix := bytes.NewBuffer(b.Bytes()[:])
  307. suffix.Write(b.Bytes()[:])
  308. suffix.Write(x.Bytes()[:])
  309. suffix.Write(y.Bytes()[:])
  310. suffix.Write(protoID)
  311. suffix.Write(id[:])
  312. // At this point secret_input has the 2 exponents, concatenated, append the
  313. // client/server common suffix.
  314. secretInput.Write(suffix.Bytes())
  315. // KEY_SEED = H(secret_input, t_key)
  316. h := hmac.New(sha256.New, tKey)
  317. _, _ = h.Write(secretInput.Bytes())
  318. tmp := h.Sum(nil)
  319. copy(keySeed[:], tmp)
  320. // verify = H(secret_input, t_verify)
  321. h = hmac.New(sha256.New, tVerify)
  322. _, _ = h.Write(secretInput.Bytes())
  323. verify := h.Sum(nil)
  324. // auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  325. authInput := bytes.NewBuffer(verify)
  326. _, _ = authInput.Write(suffix.Bytes())
  327. _, _ = authInput.Write([]byte("Server"))
  328. h = hmac.New(sha256.New, tMac)
  329. _, _ = h.Write(authInput.Bytes())
  330. tmp = h.Sum(nil)
  331. copy(auth[:], tmp)
  332. return keySeed, auth
  333. }
  334. func constantTimeIsZero(x []byte) int {
  335. var ret byte
  336. for _, v := range x {
  337. ret |= v
  338. }
  339. return subtle.ConstantTimeByteEq(ret, 0)
  340. }
  341. // Kdf extracts and expands KEY_SEED via HKDF-SHA256 and returns `okm_len` bytes
  342. // of key material.
  343. func Kdf(keySeed []byte, okmLen int) []byte {
  344. kdf := hkdf.New(sha256.New, keySeed, tKey, mExpand)
  345. okm := make([]byte, okmLen)
  346. n, err := io.ReadFull(kdf, okm)
  347. if err != nil {
  348. panic(fmt.Sprintf("BUG: Failed HKDF: %s", err.Error()))
  349. } else if n != len(okm) {
  350. panic(fmt.Sprintf("BUG: Got truncated HKDF output: %d", n))
  351. }
  352. return okm
  353. }