ntor_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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
  28. import (
  29. "bytes"
  30. "testing"
  31. "filippo.io/edwards25519"
  32. "filippo.io/edwards25519/field"
  33. "gitlab.com/yawning/edwards25519-extra/elligator2"
  34. )
  35. // TestNewKeypair tests Curve25519/Elligator keypair generation.
  36. func TestNewKeypair(t *testing.T) {
  37. // Test standard Curve25519 first.
  38. keypair, err := NewKeypair(false)
  39. if err != nil {
  40. t.Fatal("NewKeypair(false) failed:", err)
  41. }
  42. if keypair == nil {
  43. t.Fatal("NewKeypair(false) returned nil")
  44. }
  45. if keypair.HasElligator() {
  46. t.Fatal("NewKeypair(false) has a Elligator representative")
  47. }
  48. // Test Elligator generation.
  49. keypair, err = NewKeypair(true)
  50. if err != nil {
  51. t.Fatal("NewKeypair(true) failed:", err)
  52. }
  53. if keypair == nil {
  54. t.Fatal("NewKeypair(true) returned nil")
  55. }
  56. if !keypair.HasElligator() {
  57. t.Fatal("NewKeypair(true) mising an Elligator representative")
  58. }
  59. }
  60. // Test Client/Server handshake.
  61. func TestHandshake(t *testing.T) {
  62. clientKeypair, err := NewKeypair(true)
  63. if err != nil {
  64. t.Fatal("Failed to generate client keypair:", err)
  65. }
  66. if clientKeypair == nil {
  67. t.Fatal("Client keypair is nil")
  68. }
  69. serverKeypair, err := NewKeypair(true)
  70. if err != nil {
  71. t.Fatal("Failed to generate server keypair:", err)
  72. }
  73. if serverKeypair == nil {
  74. t.Fatal("Server keypair is nil")
  75. }
  76. idKeypair, err := NewKeypair(false)
  77. if err != nil {
  78. t.Fatal("Failed to generate identity keypair:", err)
  79. }
  80. if idKeypair == nil {
  81. t.Fatal("Identity keypair is nil")
  82. }
  83. nodeID, err := NewNodeID([]byte("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13"))
  84. if err != nil {
  85. t.Fatal("Failed to load NodeId:", err)
  86. }
  87. // ServerHandshake
  88. clientPublic := clientKeypair.Representative().ToPublic()
  89. ok, serverSeed, serverAuth := ServerHandshake(clientPublic,
  90. serverKeypair, idKeypair, nodeID)
  91. if !ok {
  92. t.Fatal("ServerHandshake failed")
  93. }
  94. if serverSeed == nil {
  95. t.Fatal("ServerHandshake returned nil KEY_SEED")
  96. }
  97. if serverAuth == nil {
  98. t.Fatal("ServerHandshake returned nil AUTH")
  99. }
  100. // ClientHandshake
  101. ok, clientSeed, clientAuth := ClientHandshake(clientKeypair,
  102. serverKeypair.Public(), idKeypair.Public(), nodeID)
  103. if !ok {
  104. t.Fatal("ClientHandshake failed")
  105. }
  106. if clientSeed == nil {
  107. t.Fatal("ClientHandshake returned nil KEY_SEED")
  108. }
  109. if clientAuth == nil {
  110. t.Fatal("ClientHandshake returned nil AUTH")
  111. }
  112. // WARNING: Use a constant time comparison in actual code.
  113. if 0 != bytes.Compare(clientSeed.Bytes()[:], serverSeed.Bytes()[:]) {
  114. t.Fatal("KEY_SEED mismatched between client/server")
  115. }
  116. if 0 != bytes.Compare(clientAuth.Bytes()[:], serverAuth.Bytes()[:]) {
  117. t.Fatal("AUTH mismatched between client/server")
  118. }
  119. }
  120. // TestPublicKeySubgroup tests that Elligator representatives produced by
  121. // NewKeypair map to public keys that are not always on the prime-order subgroup
  122. // of Curve25519. (And incidentally that Elligator representatives agree with
  123. // the public key stored in the Keypair.)
  124. //
  125. // See discussion under "Step 2" at https://elligator.org/key-exchange.
  126. func TestPublicKeySubgroup(t *testing.T) {
  127. // We will test the public keys that comes out of NewKeypair by
  128. // multiplying each one by L, the order of the prime-order subgroup of
  129. // Curve25519, then checking the order of the resulting point. The error
  130. // condition we are checking for specifically is output points always
  131. // having order 1, which means that public keys are always on the
  132. // prime-order subgroup of Curve25519, which would make Elligator
  133. // representatives distinguishable from random. More generally, we want
  134. // to ensure that all possible output points of low order are covered.
  135. //
  136. // We have to do some contortions to conform to the interfaces we use.
  137. // We do scalar multiplication by L using Edwards coordinates, rather
  138. // than the Montgomery coordinates output by Keypair.Public and
  139. // Representative.ToPublic, because the Montgomery-based
  140. // crypto/curve25519.X25519 clamps the scalar to be a multiple of 8,
  141. // which would not allow us to use the scalar we need. The Edwards-based
  142. // ScalarMult only accepts scalars that are strictly less than L; we
  143. // work around this by multiplying the point by L - 1, then adding the
  144. // point once to the product.
  145. scalarOrderMinus1, err := edwards25519.NewScalar().SetCanonicalBytes(
  146. // This is the same as scMinusOne in filippo.io/edwards25519.
  147. // https://github.com/FiloSottile/edwards25519/blob/v1.0.0/scalar.go#L34
  148. []byte{236, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16},
  149. )
  150. if err != nil {
  151. panic(err)
  152. }
  153. // Returns a new edwards25519.Point that is v multiplied by the subgroup
  154. // order.
  155. scalarMultOrder := func(v *edwards25519.Point) *edwards25519.Point {
  156. p := new(edwards25519.Point)
  157. // v * (L - 1) + v => v * L
  158. p.ScalarMult(scalarOrderMinus1, v)
  159. p.Add(p, v)
  160. return p
  161. }
  162. // Generates a new Keypair using NewKeypair, and returns the Keypair
  163. // along, with its public key as a newly allocated edwards25519.Point.
  164. generate := func() (*Keypair, *edwards25519.Point) {
  165. kp, err := NewKeypair(true)
  166. if err != nil {
  167. panic(err)
  168. }
  169. // We will be using the Edwards representation of the public key
  170. // (mapped from the Elligator representative) for further
  171. // processing. But while we're here, check that the Montgomery
  172. // representation output by Representative agrees with the
  173. // stored public key.
  174. if *kp.Representative().ToPublic() != *kp.Public() {
  175. t.Fatal(kp.Representative().ToPublic(), kp.Public())
  176. }
  177. // Do the Elligator map in Edwards coordinates.
  178. var clamped [32]byte
  179. copy(clamped[:], kp.Representative().Bytes()[:])
  180. clamped[31] &= 63
  181. repr, err := new(field.Element).SetBytes(clamped[:])
  182. if err != nil {
  183. panic(err)
  184. }
  185. ed := elligator2.EdwardsFlavor(repr)
  186. if !bytes.Equal(ed.BytesMontgomery(), kp.Public().Bytes()[:]) {
  187. panic("Failed to derive an equivalent public key in Edwards coordinates")
  188. }
  189. return kp, ed
  190. }
  191. // These are all the points of low order that may result from
  192. // multiplying an Elligator-mapped point by L. We will test that all of
  193. // them are covered.
  194. lowOrderPoints := [][32]byte{
  195. /* order 1 */ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  196. /* order 2 */ {236, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127},
  197. /* order 4 */ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  198. /* order 4 */ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128},
  199. /* order 8 */ {38, 232, 149, 143, 194, 178, 39, 176, 69, 195, 244, 137, 242, 239, 152, 240, 213, 223, 172, 5, 211, 198, 51, 57, 177, 56, 2, 136, 109, 83, 252, 5},
  200. /* order 8 */ {38, 232, 149, 143, 194, 178, 39, 176, 69, 195, 244, 137, 242, 239, 152, 240, 213, 223, 172, 5, 211, 198, 51, 57, 177, 56, 2, 136, 109, 83, 252, 133},
  201. /* order 8 */ {199, 23, 106, 112, 61, 77, 216, 79, 186, 60, 11, 118, 13, 16, 103, 15, 42, 32, 83, 250, 44, 57, 204, 198, 78, 199, 253, 119, 146, 172, 3, 122},
  202. /* order 8 */ {199, 23, 106, 112, 61, 77, 216, 79, 186, 60, 11, 118, 13, 16, 103, 15, 42, 32, 83, 250, 44, 57, 204, 198, 78, 199, 253, 119, 146, 172, 3, 250},
  203. }
  204. counts := make(map[[32]byte]int)
  205. for _, b := range lowOrderPoints {
  206. counts[b] = 0
  207. }
  208. // Assuming a uniform distribution of representatives, the probability
  209. // that a specific low-order point will not be covered after n trials is
  210. // (7/8)^n. The probability that *any* of the 8 low-order points will
  211. // remain uncovered after n trials is at most 8 times that, 8*(7/8)^n.
  212. // We must do at least log((1e-12)/8)/log(7/8) = 222.50 trials, in the
  213. // worst case, to ensure a false error rate of less than 1 in a
  214. // trillion. In practice, we keep track of the number of covered points
  215. // and break the loop when it reaches 8, so when representatives are
  216. // actually uniform we will usually run much fewer iterations.
  217. numCovered := 0
  218. for i := 0; i < 225; i++ {
  219. kp, pk := generate()
  220. v := scalarMultOrder(pk)
  221. var b [32]byte
  222. copy(b[:], v.Bytes())
  223. if _, ok := counts[b]; !ok {
  224. t.Fatalf("map(%x)*order yielded unexpected point %v",
  225. *kp.Representative().Bytes(), b)
  226. }
  227. counts[b]++
  228. if counts[b] == 1 {
  229. // We just covered a new point for the first time.
  230. numCovered++
  231. if numCovered == len(lowOrderPoints) {
  232. break
  233. }
  234. }
  235. }
  236. for _, b := range lowOrderPoints {
  237. count, ok := counts[b]
  238. if !ok {
  239. panic(b)
  240. }
  241. if count == 0 {
  242. t.Errorf("low-order point %x not covered", b)
  243. }
  244. }
  245. }
  246. // Benchmark Client/Server handshake. The actual time taken that will be
  247. // observed on either the Client or Server is half the reported time per
  248. // operation since the benchmark does both sides.
  249. func BenchmarkHandshake(b *testing.B) {
  250. // Generate the "long lasting" identity key and NodeId.
  251. idKeypair, err := NewKeypair(false)
  252. if err != nil || idKeypair == nil {
  253. b.Fatal("Failed to generate identity keypair")
  254. }
  255. nodeID, err := NewNodeID([]byte("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13"))
  256. if err != nil {
  257. b.Fatal("Failed to load NodeId:", err)
  258. }
  259. b.ResetTimer()
  260. // Start the actual benchmark.
  261. for i := 0; i < b.N; i++ {
  262. // Generate the keypairs.
  263. serverKeypair, err := NewKeypair(true)
  264. if err != nil || serverKeypair == nil {
  265. b.Fatal("Failed to generate server keypair")
  266. }
  267. clientKeypair, err := NewKeypair(true)
  268. if err != nil || clientKeypair == nil {
  269. b.Fatal("Failed to generate client keypair")
  270. }
  271. // Server handshake.
  272. clientPublic := clientKeypair.Representative().ToPublic()
  273. ok, serverSeed, serverAuth := ServerHandshake(clientPublic,
  274. serverKeypair, idKeypair, nodeID)
  275. if !ok || serverSeed == nil || serverAuth == nil {
  276. b.Fatal("ServerHandshake failed")
  277. }
  278. // Client handshake.
  279. serverPublic := serverKeypair.Representative().ToPublic()
  280. ok, clientSeed, clientAuth := ClientHandshake(clientKeypair,
  281. serverPublic, idKeypair.Public(), nodeID)
  282. if !ok || clientSeed == nil || clientAuth == nil {
  283. b.Fatal("ClientHandshake failed")
  284. }
  285. // Validate the authenticator. Real code would pass the AUTH read off
  286. // the network as a slice to CompareAuth here.
  287. if !CompareAuth(clientAuth, serverAuth.Bytes()[:]) ||
  288. !CompareAuth(serverAuth, clientAuth.Bytes()[:]) {
  289. b.Fatal("AUTH mismatched between client/server")
  290. }
  291. }
  292. }