ntor_ref.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. # Copyright 2012 The Tor Project, Inc
  2. # See LICENSE for licensing information
  3. """
  4. ntor_ref.py
  5. This module is a reference implementation for the "ntor" protocol
  6. s proposed by Goldberg, Stebila, and Ustaoglu and as instantiated in
  7. Tor Proposal 216.
  8. It's meant to be used to validate Tor's ntor implementation. It
  9. requirs the curve25519 python module from the curve25519-donna
  10. package.
  11. *** DO NOT USE THIS IN PRODUCTION. ***
  12. commands:
  13. gen_kdf_vectors: Print out some test vectors for the RFC5869 KDF.
  14. timing: Print a little timing information about this implementation's
  15. handshake.
  16. self-test: Try handshaking with ourself; make sure we can.
  17. test-tor: Handshake with tor's ntor implementation via the program
  18. src/test/test-ntor-cl; make sure we can.
  19. """
  20. import binascii
  21. import curve25519
  22. import hashlib
  23. import hmac
  24. import subprocess
  25. # **********************************************************************
  26. # Helpers and constants
  27. def HMAC(key,msg):
  28. "Return the HMAC-SHA256 of 'msg' using the key 'key'."
  29. H = hmac.new(key, "", hashlib.sha256)
  30. H.update(msg)
  31. return H.digest()
  32. def H(msg,tweak):
  33. """Return the hash of 'msg' using tweak 'tweak'. (In this version of ntor,
  34. the tweaked hash is just HMAC with the tweak as the key.)"""
  35. return HMAC(key=tweak,
  36. msg=msg)
  37. def keyid(k):
  38. """Return the 32-byte key ID of a public key 'k'. (Since we're
  39. using curve25519, we let k be its own keyid.)
  40. """
  41. return k.serialize()
  42. NODE_ID_LENGTH = 20
  43. KEYID_LENGTH = 32
  44. G_LENGTH = 32
  45. H_LENGTH = 32
  46. PROTOID = b"ntor-curve25519-sha256-1"
  47. M_EXPAND = PROTOID + ":key_expand"
  48. T_MAC = PROTOID + ":mac"
  49. T_KEY = PROTOID + ":key_extract"
  50. T_VERIFY = PROTOID + ":verify"
  51. def H_mac(msg): return H(msg, tweak=T_MAC)
  52. def H_verify(msg): return H(msg, tweak=T_VERIFY)
  53. class PrivateKey(curve25519.keys.Private):
  54. """As curve25519.keys.Private, but doesn't regenerate its public key
  55. every time you ask for it.
  56. """
  57. def __init__(self):
  58. curve25519.keys.Private.__init__(self)
  59. self._memo_public = None
  60. def get_public(self):
  61. if self._memo_public is None:
  62. self._memo_public = curve25519.keys.Private.get_public(self)
  63. return self._memo_public
  64. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  65. def kdf_rfc5869(key, salt, info, n):
  66. prk = HMAC(key=salt, msg=key)
  67. out = b""
  68. last = b""
  69. i = 1
  70. while len(out) < n:
  71. m = last + info + chr(i)
  72. last = h = HMAC(key=prk, msg=m)
  73. out += h
  74. i = i + 1
  75. return out[:n]
  76. def kdf_ntor(key, n):
  77. return kdf_rfc5869(key, T_KEY, M_EXPAND, n)
  78. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  79. def client_part1(node_id, pubkey_B):
  80. """Initial handshake, client side.
  81. From the specification:
  82. <<To send a create cell, the client generates a keypair x,X =
  83. KEYGEN(), and sends a CREATE cell with contents:
  84. NODEID: ID -- ID_LENGTH bytes
  85. KEYID: KEYID(B) -- H_LENGTH bytes
  86. CLIENT_PK: X -- G_LENGTH bytes
  87. >>
  88. Takes node_id -- a digest of the server's identity key,
  89. pubkey_B -- a public key for the server.
  90. Returns a tuple of (client secret key x, client->server message)"""
  91. assert len(node_id) == NODE_ID_LENGTH
  92. key_id = keyid(pubkey_B)
  93. seckey_x = PrivateKey()
  94. pubkey_X = seckey_x.get_public().serialize()
  95. message = node_id + key_id + pubkey_X
  96. assert len(message) == NODE_ID_LENGTH + H_LENGTH + H_LENGTH
  97. return seckey_x , message
  98. def hash_nil(x):
  99. """Identity function: if we don't pass a hash function that does nothing,
  100. the curve25519 python lib will try to sha256 it for us."""
  101. return x
  102. def bad_result(r):
  103. """Helper: given a result of multiplying a public key by a private key,
  104. return True iff one of the inputs was broken"""
  105. assert len(r) == 32
  106. return r == '\x00'*32
  107. def server(seckey_b, my_node_id, message, keyBytes=72):
  108. """Handshake step 2, server side.
  109. From the spec:
  110. <<
  111. The server generates a keypair of y,Y = KEYGEN(), and computes
  112. secret_input = EXP(X,y) | EXP(X,b) | ID | B | X | Y | PROTOID
  113. KEY_SEED = H(secret_input, t_key)
  114. verify = H(secret_input, t_verify)
  115. auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  116. The server sends a CREATED cell containing:
  117. SERVER_PK: Y -- G_LENGTH bytes
  118. AUTH: H(auth_input, t_mac) -- H_LENGTH byets
  119. >>
  120. Takes seckey_b -- the server's secret key
  121. my_node_id -- the servers's public key digest,
  122. message -- a message from a client
  123. keybytes -- amount of key material to generate
  124. Returns a tuple of (key material, sever->client reply), or None on
  125. error.
  126. """
  127. assert len(message) == NODE_ID_LENGTH + H_LENGTH + H_LENGTH
  128. if my_node_id != message[:NODE_ID_LENGTH]:
  129. return None
  130. badness = (keyid(seckey_b.get_public()) !=
  131. message[NODE_ID_LENGTH:NODE_ID_LENGTH+H_LENGTH])
  132. pubkey_X = curve25519.keys.Public(message[NODE_ID_LENGTH+H_LENGTH:])
  133. seckey_y = PrivateKey()
  134. pubkey_Y = seckey_y.get_public()
  135. pubkey_B = seckey_b.get_public()
  136. xy = seckey_y.get_shared_key(pubkey_X, hash_nil)
  137. xb = seckey_b.get_shared_key(pubkey_X, hash_nil)
  138. # secret_input = EXP(X,y) | EXP(X,b) | ID | B | X | Y | PROTOID
  139. secret_input = (xy + xb + my_node_id +
  140. pubkey_B.serialize() +
  141. pubkey_X.serialize() +
  142. pubkey_Y.serialize() +
  143. PROTOID)
  144. verify = H_verify(secret_input)
  145. # auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  146. auth_input = (verify +
  147. my_node_id +
  148. pubkey_B.serialize() +
  149. pubkey_Y.serialize() +
  150. pubkey_X.serialize() +
  151. PROTOID +
  152. "Server")
  153. msg = pubkey_Y.serialize() + H_mac(auth_input)
  154. badness += bad_result(xb)
  155. badness += bad_result(xy)
  156. if badness:
  157. return None
  158. keys = kdf_ntor(secret_input, keyBytes)
  159. return keys, msg
  160. def client_part2(seckey_x, msg, node_id, pubkey_B, keyBytes=72):
  161. """Handshake step 3: client side again.
  162. From the spec:
  163. <<
  164. The client then checks Y is in G^* [see NOTE below], and computes
  165. secret_input = EXP(Y,x) | EXP(B,x) | ID | B | X | Y | PROTOID
  166. KEY_SEED = H(secret_input, t_key)
  167. verify = H(secret_input, t_verify)
  168. auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  169. The client verifies that AUTH == H(auth_input, t_mac).
  170. >>
  171. Takes seckey_x -- the secret key we generated in step 1.
  172. msg -- the message from the server.
  173. node_id -- the node_id we used in step 1.
  174. server_key -- the same public key we used in step 1.
  175. keyBytes -- the number of bytes we want to generate
  176. Returns key material, or None on error
  177. """
  178. assert len(msg) == G_LENGTH + H_LENGTH
  179. pubkey_Y = curve25519.keys.Public(msg[:G_LENGTH])
  180. their_auth = msg[G_LENGTH:]
  181. pubkey_X = seckey_x.get_public()
  182. yx = seckey_x.get_shared_key(pubkey_Y, hash_nil)
  183. bx = seckey_x.get_shared_key(pubkey_B, hash_nil)
  184. # secret_input = EXP(Y,x) | EXP(B,x) | ID | B | X | Y | PROTOID
  185. secret_input = (yx + bx + node_id +
  186. pubkey_B.serialize() +
  187. pubkey_X.serialize() +
  188. pubkey_Y.serialize() + PROTOID)
  189. verify = H_verify(secret_input)
  190. # auth_input = verify | ID | B | Y | X | PROTOID | "Server"
  191. auth_input = (verify + node_id +
  192. pubkey_B.serialize() +
  193. pubkey_Y.serialize() +
  194. pubkey_X.serialize() + PROTOID +
  195. "Server")
  196. my_auth = H_mac(auth_input)
  197. badness = my_auth != their_auth
  198. badness = bad_result(yx) + bad_result(bx)
  199. if badness:
  200. return None
  201. return kdf_ntor(secret_input, keyBytes)
  202. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  203. def demo(node_id="iToldYouAboutStairs.", server_key=PrivateKey()):
  204. """
  205. Try to handshake with ourself.
  206. """
  207. x, create = client_part1(node_id, server_key.get_public())
  208. skeys, created = server(server_key, node_id, create)
  209. ckeys = client_part2(x, created, node_id, server_key.get_public())
  210. assert len(skeys) == 72
  211. assert len(ckeys) == 72
  212. assert skeys == ckeys
  213. # ======================================================================
  214. def timing():
  215. """
  216. Use Python's timeit module to see how fast this nonsense is
  217. """
  218. import timeit
  219. t = timeit.Timer(stmt="ntor_ref.demo(N,SK)",
  220. setup="import ntor_ref,curve25519;N='ABCD'*5;SK=ntor_ref.PrivateKey()")
  221. print t.timeit(number=1000)
  222. # ======================================================================
  223. def kdf_vectors():
  224. """
  225. Generate some vectors to check our KDF.
  226. """
  227. import binascii
  228. def kdf_vec(inp):
  229. k = kdf(inp, T_KEY, M_EXPAND, 100)
  230. print repr(inp), "\n\""+ binascii.b2a_hex(k)+ "\""
  231. kdf_vec("")
  232. kdf_vec("Tor")
  233. kdf_vec("AN ALARMING ITEM TO FIND ON YOUR CREDIT-RATING STATEMENT")
  234. # ======================================================================
  235. def test_tor():
  236. """
  237. Call the test-ntor-cl command-line program to make sure we can
  238. interoperate with Tor's ntor program
  239. """
  240. enhex=binascii.b2a_hex
  241. dehex=lambda s: binascii.a2b_hex(s.strip())
  242. PROG = "./src/test/test-ntor-cl"
  243. def tor_client1(node_id, pubkey_B):
  244. " returns (msg, state) "
  245. p = subprocess.Popen([PROG, "client1", enhex(node_id),
  246. enhex(pubkey_B.serialize())],
  247. stdout=subprocess.PIPE)
  248. return map(dehex, p.stdout.readlines())
  249. def tor_server1(seckey_b, node_id, msg, n):
  250. " returns (msg, keys) "
  251. p = subprocess.Popen([PROG, "server1", enhex(seckey_b.serialize()),
  252. enhex(node_id), enhex(msg), str(n)],
  253. stdout=subprocess.PIPE)
  254. return map(dehex, p.stdout.readlines())
  255. def tor_client2(state, msg, n):
  256. " returns (keys,) "
  257. p = subprocess.Popen([PROG, "client2", enhex(state),
  258. enhex(msg), str(n)],
  259. stdout=subprocess.PIPE)
  260. return map(dehex, p.stdout.readlines())
  261. node_id = "thisisatornodeid$#%^"
  262. seckey_b = PrivateKey()
  263. pubkey_B = seckey_b.get_public()
  264. # Do a pure-Tor handshake
  265. c2s_msg, c_state = tor_client1(node_id, pubkey_B)
  266. s2c_msg, s_keys = tor_server1(seckey_b, node_id, c2s_msg, 90)
  267. c_keys, = tor_client2(c_state, s2c_msg, 90)
  268. assert c_keys == s_keys
  269. assert len(c_keys) == 90
  270. # Try a mixed handshake with Tor as the client
  271. c2s_msg, c_state = tor_client1(node_id, pubkey_B)
  272. s_keys, s2c_msg = server(seckey_b, node_id, c2s_msg, 90)
  273. c_keys, = tor_client2(c_state, s2c_msg, 90)
  274. assert c_keys == s_keys
  275. assert len(c_keys) == 90
  276. # Now do a mixed handshake with Tor as the server
  277. c_x, c2s_msg = client_part1(node_id, pubkey_B)
  278. s2c_msg, s_keys = tor_server1(seckey_b, node_id, c2s_msg, 90)
  279. c_keys = client_part2(c_x, s2c_msg, node_id, pubkey_B, 90)
  280. assert c_keys == s_keys
  281. assert len(c_keys) == 90
  282. print "We just interoperated."
  283. # ======================================================================
  284. if __name__ == '__main__':
  285. import sys
  286. if sys.argv[1] == 'gen_kdf_vectors':
  287. kdf_vectors()
  288. elif sys.argv[1] == 'timing':
  289. timing()
  290. elif sys.argv[1] == 'self-test':
  291. demo()
  292. elif sys.argv[1] == 'test-tor':
  293. test_tor()
  294. else:
  295. print __doc__