ntor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (c) 2014, Yawning Angel <yawning at schwanenlied dot me>
  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.torproject.org/tpo/anti-censorship/pluggable-transports/lyrebird/common/ntor"
  35. import (
  36. "bytes"
  37. "crypto/hmac"
  38. "crypto/sha256"
  39. "crypto/sha512"
  40. "crypto/subtle"
  41. "encoding/hex"
  42. "fmt"
  43. "io"
  44. "golang.org/x/crypto/curve25519"
  45. "golang.org/x/crypto/hkdf"
  46. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/lyrebird/common/csrand"
  47. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/lyrebird/internal/x25519ell2"
  48. )
  49. const (
  50. // PublicKeyLength is the length of a Curve25519 public key.
  51. PublicKeyLength = 32
  52. // RepresentativeLength is the length of an Elligator representative.
  53. RepresentativeLength = 32
  54. // PrivateKeyLength is the length of a Curve25519 private key.
  55. PrivateKeyLength = 32
  56. // SharedSecretLength is the length of a Curve25519 shared secret.
  57. SharedSecretLength = 32
  58. // NodeIDLength is the length of a ntor node identifier.
  59. NodeIDLength = 20
  60. // KeySeedLength is the length of the derived KEY_SEED.
  61. KeySeedLength = sha256.Size
  62. // AuthLength is the lenght of the derived AUTH.
  63. AuthLength = sha256.Size
  64. )
  65. var protoID = []byte("ntor-curve25519-sha256-1")
  66. var tMac = append(protoID, []byte(":mac")...)
  67. var tKey = append(protoID, []byte(":key_extract")...)
  68. var tVerify = append(protoID, []byte(":key_verify")...)
  69. var mExpand = append(protoID, []byte(":key_expand")...)
  70. // PublicKeyLengthError is the error returned when the public key being
  71. // imported is an invalid length.
  72. type PublicKeyLengthError int
  73. func (e PublicKeyLengthError) Error() string {
  74. return fmt.Sprintf("ntor: Invalid Curve25519 public key length: %d",
  75. int(e))
  76. }
  77. // PrivateKeyLengthError is the error returned when the private key being
  78. // imported is an invalid length.
  79. type PrivateKeyLengthError int
  80. func (e PrivateKeyLengthError) Error() string {
  81. return fmt.Sprintf("ntor: Invalid Curve25519 private key length: %d",
  82. int(e))
  83. }
  84. // NodeIDLengthError is the error returned when the node ID being imported is
  85. // an invalid length.
  86. type NodeIDLengthError int
  87. func (e NodeIDLengthError) Error() string {
  88. return fmt.Sprintf("ntor: Invalid NodeID length: %d", int(e))
  89. }
  90. // KeySeed is the key material that results from a handshake (KEY_SEED).
  91. type KeySeed [KeySeedLength]byte
  92. // Bytes returns a pointer to the raw key material.
  93. func (key_seed *KeySeed) Bytes() *[KeySeedLength]byte {
  94. return (*[KeySeedLength]byte)(key_seed)
  95. }
  96. // Auth is the verifier that results from a handshake (AUTH).
  97. type Auth [AuthLength]byte
  98. // Bytes returns a pointer to the raw auth.
  99. func (auth *Auth) Bytes() *[AuthLength]byte {
  100. return (*[AuthLength]byte)(auth)
  101. }
  102. // NodeID is a ntor node identifier.
  103. type NodeID [NodeIDLength]byte
  104. // NewNodeID creates a NodeID from the raw bytes.
  105. func NewNodeID(raw []byte) (*NodeID, error) {
  106. if len(raw) != NodeIDLength {
  107. return nil, NodeIDLengthError(len(raw))
  108. }
  109. nodeID := new(NodeID)
  110. copy(nodeID[:], raw)
  111. return nodeID, nil
  112. }
  113. // NodeIDFromHex creates a new NodeID from the hexdecimal representation.
  114. func NodeIDFromHex(encoded string) (*NodeID, error) {
  115. raw, err := hex.DecodeString(encoded)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return NewNodeID(raw)
  120. }
  121. // Bytes returns a pointer to the raw NodeID.
  122. func (id *NodeID) Bytes() *[NodeIDLength]byte {
  123. return (*[NodeIDLength]byte)(id)
  124. }
  125. // Hex returns the hexdecimal representation of the NodeID.
  126. func (id *NodeID) Hex() string {
  127. return hex.EncodeToString(id[:])
  128. }
  129. // PublicKey is a Curve25519 public key in little-endian byte order.
  130. type PublicKey [PublicKeyLength]byte
  131. // Bytes returns a pointer to the raw Curve25519 public key.
  132. func (public *PublicKey) Bytes() *[PublicKeyLength]byte {
  133. return (*[PublicKeyLength]byte)(public)
  134. }
  135. // Hex returns the hexdecimal representation of the Curve25519 public key.
  136. func (public *PublicKey) Hex() string {
  137. return hex.EncodeToString(public.Bytes()[:])
  138. }
  139. // NewPublicKey creates a PublicKey from the raw bytes.
  140. func NewPublicKey(raw []byte) (*PublicKey, error) {
  141. if len(raw) != PublicKeyLength {
  142. return nil, PublicKeyLengthError(len(raw))
  143. }
  144. pubKey := new(PublicKey)
  145. copy(pubKey[:], raw)
  146. return pubKey, nil
  147. }
  148. // PublicKeyFromHex returns a PublicKey from the hexdecimal representation.
  149. func PublicKeyFromHex(encoded string) (*PublicKey, error) {
  150. raw, err := hex.DecodeString(encoded)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return NewPublicKey(raw)
  155. }
  156. // Representative is an Elligator representative of a Curve25519 public key
  157. // in little-endian byte order.
  158. type Representative [RepresentativeLength]byte
  159. // Bytes returns a pointer to the raw Elligator representative.
  160. func (repr *Representative) Bytes() *[RepresentativeLength]byte {
  161. return (*[RepresentativeLength]byte)(repr)
  162. }
  163. // ToPublic converts a Elligator representative to a Curve25519 public key.
  164. func (repr *Representative) ToPublic() *PublicKey {
  165. pub := new(PublicKey)
  166. x25519ell2.RepresentativeToPublicKey(pub.Bytes(), repr.Bytes())
  167. return pub
  168. }
  169. // PrivateKey is a Curve25519 private key in little-endian byte order.
  170. type PrivateKey [PrivateKeyLength]byte
  171. // Bytes returns a pointer to the raw Curve25519 private key.
  172. func (private *PrivateKey) Bytes() *[PrivateKeyLength]byte {
  173. return (*[PrivateKeyLength]byte)(private)
  174. }
  175. // Hex returns the hexdecimal representation of the Curve25519 private key.
  176. func (private *PrivateKey) Hex() string {
  177. return hex.EncodeToString(private.Bytes()[:])
  178. }
  179. // Keypair is a Curve25519 keypair with an optional Elligator representative.
  180. // As only certain Curve25519 keys can be obfuscated with Elligator, the
  181. // representative must be generated along with the keypair.
  182. type Keypair struct {
  183. public *PublicKey
  184. private *PrivateKey
  185. representative *Representative
  186. }
  187. // Public returns the Curve25519 public key belonging to the Keypair.
  188. func (keypair *Keypair) Public() *PublicKey {
  189. return keypair.public
  190. }
  191. // Private returns the Curve25519 private key belonging to the Keypair.
  192. func (keypair *Keypair) Private() *PrivateKey {
  193. return keypair.private
  194. }
  195. // Representative returns the Elligator representative of the public key
  196. // belonging to the Keypair.
  197. func (keypair *Keypair) Representative() *Representative {
  198. return keypair.representative
  199. }
  200. // HasElligator returns true if the Keypair has an Elligator representative.
  201. func (keypair *Keypair) HasElligator() bool {
  202. return nil != keypair.representative
  203. }
  204. // NewKeypair generates a new Curve25519 keypair, and optionally also generates
  205. // an Elligator representative of the public key.
  206. func NewKeypair(elligator bool) (*Keypair, error) {
  207. keypair := new(Keypair)
  208. keypair.private = new(PrivateKey)
  209. keypair.public = new(PublicKey)
  210. if elligator {
  211. keypair.representative = new(Representative)
  212. }
  213. for {
  214. // Generate a Curve25519 private key. Like everyone who does this,
  215. // run the CSPRNG output through SHA512 for extra tinfoil hattery.
  216. //
  217. // Also use part of the digest that gets truncated off for the
  218. // obfuscation tweak.
  219. priv := keypair.private.Bytes()[:]
  220. if err := csrand.Bytes(priv); err != nil {
  221. return nil, err
  222. }
  223. digest := sha512.Sum512(priv)
  224. copy(priv, digest[:])
  225. if elligator {
  226. tweak := digest[63]
  227. // Apply the Elligator transform. This fails ~50% of the time.
  228. if !x25519ell2.ScalarBaseMult(keypair.public.Bytes(),
  229. keypair.representative.Bytes(),
  230. keypair.private.Bytes(),
  231. tweak) {
  232. continue
  233. }
  234. } else {
  235. // Generate the corresponding Curve25519 public key.
  236. curve25519.ScalarBaseMult(keypair.public.Bytes(),
  237. keypair.private.Bytes())
  238. }
  239. return keypair, nil
  240. }
  241. }
  242. // KeypairFromHex returns a Keypair from the hexdecimal representation of the
  243. // private key.
  244. func KeypairFromHex(encoded string) (*Keypair, error) {
  245. raw, err := hex.DecodeString(encoded)
  246. if err != nil {
  247. return nil, err
  248. }
  249. if len(raw) != PrivateKeyLength {
  250. return nil, PrivateKeyLengthError(len(raw))
  251. }
  252. keypair := new(Keypair)
  253. keypair.private = new(PrivateKey)
  254. keypair.public = new(PublicKey)
  255. copy(keypair.private[:], raw)
  256. curve25519.ScalarBaseMult(keypair.public.Bytes(),
  257. keypair.private.Bytes())
  258. return keypair, nil
  259. }
  260. // ServerHandshake does the server side of a ntor handshake and returns status,
  261. // KEY_SEED, and AUTH. If status is not true, the handshake MUST be aborted.
  262. func ServerHandshake(clientPublic *PublicKey, serverKeypair *Keypair, idKeypair *Keypair, id *NodeID) (ok bool, keySeed *KeySeed, auth *Auth) {
  263. var notOk int
  264. var secretInput bytes.Buffer
  265. // Server side uses EXP(X,y) | EXP(X,b)
  266. var exp [SharedSecretLength]byte
  267. curve25519.ScalarMult(&exp, serverKeypair.private.Bytes(),
  268. clientPublic.Bytes())
  269. notOk |= constantTimeIsZero(exp[:])
  270. secretInput.Write(exp[:])
  271. curve25519.ScalarMult(&exp, idKeypair.private.Bytes(),
  272. clientPublic.Bytes())
  273. notOk |= constantTimeIsZero(exp[:])
  274. secretInput.Write(exp[:])
  275. keySeed, auth = ntorCommon(secretInput, id, idKeypair.public,
  276. clientPublic, serverKeypair.public)
  277. return notOk == 0, keySeed, auth
  278. }
  279. // ClientHandshake does the client side of a ntor handshake and returnes
  280. // status, KEY_SEED, and AUTH. If status is not true or AUTH does not match
  281. // the value recieved from the server, the handshake MUST be aborted.
  282. func ClientHandshake(clientKeypair *Keypair, serverPublic *PublicKey, idPublic *PublicKey, id *NodeID) (ok bool, keySeed *KeySeed, auth *Auth) {
  283. var notOk int
  284. var secretInput bytes.Buffer
  285. // Client side uses EXP(Y,x) | EXP(B,x)
  286. var exp [SharedSecretLength]byte
  287. curve25519.ScalarMult(&exp, clientKeypair.private.Bytes(),
  288. serverPublic.Bytes())
  289. notOk |= constantTimeIsZero(exp[:])
  290. secretInput.Write(exp[:])
  291. curve25519.ScalarMult(&exp, clientKeypair.private.Bytes(),
  292. idPublic.Bytes())
  293. notOk |= constantTimeIsZero(exp[:])
  294. secretInput.Write(exp[:])
  295. keySeed, auth = ntorCommon(secretInput, id, idPublic,
  296. clientKeypair.public, serverPublic)
  297. return notOk == 0, keySeed, auth
  298. }
  299. // CompareAuth does a constant time compare of a Auth and a byte slice
  300. // (presumably received over a network).
  301. func CompareAuth(auth1 *Auth, auth2 []byte) bool {
  302. auth1Bytes := auth1.Bytes()
  303. return hmac.Equal(auth1Bytes[:], auth2)
  304. }
  305. func ntorCommon(secretInput bytes.Buffer, id *NodeID, b *PublicKey, x *PublicKey, y *PublicKey) (*KeySeed, *Auth) {
  306. keySeed := new(KeySeed)
  307. auth := new(Auth)
  308. // secret_input/auth_input use this common bit, build it once.
  309. suffix := bytes.NewBuffer(b.Bytes()[:])
  310. suffix.Write(b.Bytes()[:])
  311. suffix.Write(x.Bytes()[:])
  312. suffix.Write(y.Bytes()[:])
  313. suffix.Write(protoID)
  314. suffix.Write(id[:])
  315. // At this point secret_input has the 2 exponents, concatenated, append the
  316. // client/server common suffix.
  317. secretInput.Write(suffix.Bytes())
  318. // KEY_SEED = H(secret_input, t_key)
  319. h := hmac.New(sha256.New, tKey)
  320. _, _ = h.Write(secretInput.Bytes())
  321. tmp := h.Sum(nil)
  322. copy(keySeed[:], tmp)
  323. // verify = H(secret_input, t_verify)
  324. h = hmac.New(sha256.New, tVerify)
  325. _, _ = h.Write(secretInput.Bytes())
  326. verify := h.Sum(nil)
  327. // auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  328. authInput := bytes.NewBuffer(verify)
  329. _, _ = authInput.Write(suffix.Bytes())
  330. _, _ = authInput.Write([]byte("Server"))
  331. h = hmac.New(sha256.New, tMac)
  332. _, _ = h.Write(authInput.Bytes())
  333. tmp = h.Sum(nil)
  334. copy(auth[:], tmp)
  335. return keySeed, auth
  336. }
  337. func constantTimeIsZero(x []byte) int {
  338. var ret byte
  339. for _, v := range x {
  340. ret |= v
  341. }
  342. return subtle.ConstantTimeByteEq(ret, 0)
  343. }
  344. // Kdf extracts and expands KEY_SEED via HKDF-SHA256 and returns `okm_len` bytes
  345. // of key material.
  346. func Kdf(keySeed []byte, okmLen int) []byte {
  347. kdf := hkdf.New(sha256.New, keySeed, tKey, mExpand)
  348. okm := make([]byte, okmLen)
  349. n, err := io.ReadFull(kdf, okm)
  350. if err != nil {
  351. panic(fmt.Sprintf("BUG: Failed HKDF: %s", err.Error()))
  352. } else if n != len(okm) {
  353. panic(fmt.Sprintf("BUG: Got truncated HKDF output: %d", n))
  354. }
  355. return okm
  356. }