ntor_ref.py 12 KB

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