association.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. #-*-test-case-name: openid.test.test_association-*-
  2. #-*- coding: utf-8 -*-
  3. """
  4. This module contains code for dealing with associations between
  5. consumers and servers. Associations contain a shared secret that is
  6. used to sign C{openid.mode=id_res} messages.
  7. Users of the library should not usually need to interact directly with
  8. associations. The L{store<openid.store>}, L{server<openid.server.server>}
  9. and L{consumer<openid.consumer.consumer>} objects will create and manage
  10. the associations. The consumer and server code will make use of a
  11. C{L{SessionNegotiator}} when managing associations, which enables
  12. users to express a preference for what kind of associations should be
  13. allowed, and what kind of exchange should be done to establish the
  14. association.
  15. @var default_negotiator: A C{L{SessionNegotiator}} that allows all
  16. association types that are specified by the OpenID
  17. specification. It prefers to use HMAC-SHA1/DH-SHA1, if it's
  18. available. If HMAC-SHA256 is not supported by your Python runtime,
  19. HMAC-SHA256 and DH-SHA256 will not be available.
  20. @var encrypted_negotiator: A C{L{SessionNegotiator}} that
  21. does not support C{'no-encryption'} associations. It prefers
  22. HMAC-SHA1/DH-SHA1 association types if available.
  23. """
  24. import time
  25. import functools
  26. from openid import cryptutil
  27. from openid import kvform
  28. from openid import oidutil
  29. from openid.message import OPENID_NS
  30. __all__ = [
  31. 'default_negotiator',
  32. 'encrypted_negotiator',
  33. 'SessionNegotiator',
  34. 'Association',
  35. ]
  36. all_association_types = [
  37. 'HMAC-SHA1',
  38. 'HMAC-SHA256',
  39. ]
  40. if hasattr(cryptutil, 'hmacSha256'):
  41. supported_association_types = list(all_association_types)
  42. default_association_order = [
  43. ('HMAC-SHA1', 'DH-SHA1'),
  44. ('HMAC-SHA1', 'no-encryption'),
  45. ('HMAC-SHA256', 'DH-SHA256'),
  46. ('HMAC-SHA256', 'no-encryption'),
  47. ]
  48. only_encrypted_association_order = [
  49. ('HMAC-SHA1', 'DH-SHA1'),
  50. ('HMAC-SHA256', 'DH-SHA256'),
  51. ]
  52. else:
  53. supported_association_types = ['HMAC-SHA1']
  54. default_association_order = [
  55. ('HMAC-SHA1', 'DH-SHA1'),
  56. ('HMAC-SHA1', 'no-encryption'),
  57. ]
  58. only_encrypted_association_order = [
  59. ('HMAC-SHA1', 'DH-SHA1'),
  60. ]
  61. def getSessionTypes(assoc_type):
  62. """Return the allowed session types for a given association type"""
  63. assoc_to_session = {
  64. 'HMAC-SHA1': ['DH-SHA1', 'no-encryption'],
  65. 'HMAC-SHA256': ['DH-SHA256', 'no-encryption'],
  66. }
  67. return assoc_to_session.get(assoc_type, [])
  68. def checkSessionType(assoc_type, session_type):
  69. """Check to make sure that this pair of assoc type and session
  70. type are allowed"""
  71. if session_type not in getSessionTypes(assoc_type):
  72. raise ValueError('Session type %r not valid for assocation type %r' %
  73. (session_type, assoc_type))
  74. class SessionNegotiator(object):
  75. """A session negotiator controls the allowed and preferred
  76. association types and association session types. Both the
  77. C{L{Consumer<openid.consumer.consumer.Consumer>}} and
  78. C{L{Server<openid.server.server.Server>}} use negotiators when
  79. creating associations.
  80. You can create and use negotiators if you:
  81. - Do not want to do Diffie-Hellman key exchange because you use
  82. transport-layer encryption (e.g. SSL)
  83. - Want to use only SHA-256 associations
  84. - Do not want to support plain-text associations over a non-secure
  85. channel
  86. It is up to you to set a policy for what kinds of associations to
  87. accept. By default, the library will make any kind of association
  88. that is allowed in the OpenID 2.0 specification.
  89. Use of negotiators in the library
  90. =================================
  91. When a consumer makes an association request, it calls
  92. C{L{getAllowedType}} to get the preferred association type and
  93. association session type.
  94. The server gets a request for a particular association/session
  95. type and calls C{L{isAllowed}} to determine if it should
  96. create an association. If it is supported, negotiation is
  97. complete. If it is not, the server calls C{L{getAllowedType}} to
  98. get an allowed association type to return to the consumer.
  99. If the consumer gets an error response indicating that the
  100. requested association/session type is not supported by the server
  101. that contains an assocation/session type to try, it calls
  102. C{L{isAllowed}} to determine if it should try again with the
  103. given combination of association/session type.
  104. @ivar allowed_types: A list of association/session types that are
  105. allowed by the server. The order of the pairs in this list
  106. determines preference. If an association/session type comes
  107. earlier in the list, the library is more likely to use that
  108. type.
  109. @type allowed_types: [(str, str)]
  110. """
  111. def __init__(self, allowed_types):
  112. self.setAllowedTypes(allowed_types)
  113. def copy(self):
  114. return self.__class__(list(self.allowed_types))
  115. def setAllowedTypes(self, allowed_types):
  116. """Set the allowed association types, checking to make sure
  117. each combination is valid."""
  118. for (assoc_type, session_type) in allowed_types:
  119. checkSessionType(assoc_type, session_type)
  120. self.allowed_types = allowed_types
  121. def addAllowedType(self, assoc_type, session_type=None):
  122. """Add an association type and session type to the allowed
  123. types list. The assocation/session pairs are tried in the
  124. order that they are added."""
  125. if self.allowed_types is None:
  126. self.allowed_types = []
  127. if session_type is None:
  128. available = getSessionTypes(assoc_type)
  129. if not available:
  130. raise ValueError('No session available for association type %r'
  131. % (assoc_type, ))
  132. for session_type in getSessionTypes(assoc_type):
  133. self.addAllowedType(assoc_type, session_type)
  134. else:
  135. checkSessionType(assoc_type, session_type)
  136. self.allowed_types.append((assoc_type, session_type))
  137. def isAllowed(self, assoc_type, session_type):
  138. """Is this combination of association type and session type allowed?"""
  139. assoc_good = (assoc_type, session_type) in self.allowed_types
  140. matches = session_type in getSessionTypes(assoc_type)
  141. return assoc_good and matches
  142. def getAllowedType(self):
  143. """Get a pair of assocation type and session type that are
  144. supported"""
  145. try:
  146. return self.allowed_types[0]
  147. except IndexError:
  148. return (None, None)
  149. default_negotiator = SessionNegotiator(default_association_order)
  150. encrypted_negotiator = SessionNegotiator(only_encrypted_association_order)
  151. def getSecretSize(assoc_type):
  152. if assoc_type == 'HMAC-SHA1':
  153. return 20
  154. elif assoc_type == 'HMAC-SHA256':
  155. return 32
  156. else:
  157. raise ValueError('Unsupported association type: %r' % (assoc_type, ))
  158. @functools.total_ordering
  159. class Association(object):
  160. """
  161. This class represents an association between a server and a
  162. consumer. In general, users of this library will never see
  163. instances of this object. The only exception is if you implement
  164. a custom C{L{OpenIDStore<openid.store.interface.OpenIDStore>}}.
  165. If you do implement such a store, it will need to store the values
  166. of the C{L{handle}}, C{L{secret}}, C{L{issued}}, C{L{lifetime}}, and
  167. C{L{assoc_type}} instance variables.
  168. @ivar handle: This is the handle the server gave this association.
  169. @type handle: C{str}
  170. @ivar secret: This is the shared secret the server generated for
  171. this association.
  172. @type secret: C{str}
  173. @ivar issued: This is the time this association was issued, in
  174. seconds since 00:00 GMT, January 1, 1970. (ie, a unix
  175. timestamp)
  176. @type issued: C{int}
  177. @ivar lifetime: This is the amount of time this association is
  178. good for, measured in seconds since the association was
  179. issued.
  180. @type lifetime: C{int}
  181. @ivar assoc_type: This is the type of association this instance
  182. represents. The only valid value of this field at this time
  183. is C{'HMAC-SHA1'}, but new types may be defined in the future.
  184. @type assoc_type: C{str}
  185. @sort: __init__, fromExpiresIn, expiresIn, __eq__, __ne__,
  186. handle, secret, issued, lifetime, assoc_type
  187. """
  188. # The ordering and name of keys as stored by serialize
  189. assoc_keys = [
  190. 'version',
  191. 'handle',
  192. 'secret',
  193. 'issued',
  194. 'lifetime',
  195. 'assoc_type',
  196. ]
  197. _macs = {
  198. 'HMAC-SHA1': cryptutil.hmacSha1,
  199. 'HMAC-SHA256': cryptutil.hmacSha256,
  200. }
  201. @classmethod
  202. def fromExpiresIn(cls, expires_in, handle, secret, assoc_type):
  203. """
  204. This is an alternate constructor used by the OpenID consumer
  205. library to create associations. C{L{OpenIDStore
  206. <openid.store.interface.OpenIDStore>}} implementations
  207. shouldn't use this constructor.
  208. @param expires_in: This is the amount of time this association
  209. is good for, measured in seconds since the association was
  210. issued.
  211. @type expires_in: C{int}
  212. @param handle: This is the handle the server gave this
  213. association.
  214. @type handle: C{str}
  215. @param secret: This is the shared secret the server generated
  216. for this association.
  217. @type secret: C{str}
  218. @param assoc_type: This is the type of association this
  219. instance represents. The only valid value of this field
  220. at this time is C{'HMAC-SHA1'}, but new types may be
  221. defined in the future.
  222. @type assoc_type: C{str}
  223. """
  224. issued = int(time.time())
  225. lifetime = expires_in
  226. return cls(handle, secret, issued, lifetime, assoc_type)
  227. def __init__(self, handle, secret, issued, lifetime, assoc_type):
  228. """
  229. This is the standard constructor for creating an association.
  230. @param handle: This is the handle the server gave this
  231. association.
  232. @type handle: C{str}
  233. @param secret: This is the shared secret the server generated
  234. for this association.
  235. @type secret: C{str}
  236. @param issued: This is the time this association was issued,
  237. in seconds since 00:00 GMT, January 1, 1970. (ie, a unix
  238. timestamp)
  239. @type issued: C{int}
  240. @param lifetime: This is the amount of time this association
  241. is good for, measured in seconds since the association was
  242. issued.
  243. @type lifetime: C{int}
  244. @param assoc_type: This is the type of association this
  245. instance represents. The only valid value of this field
  246. at this time is C{'HMAC-SHA1'}, but new types may be
  247. defined in the future.
  248. @type assoc_type: C{str}
  249. """
  250. if assoc_type not in all_association_types:
  251. fmt = '%r is not a supported association type'
  252. raise ValueError(fmt % (assoc_type, ))
  253. # secret_size = getSecretSize(assoc_type)
  254. # if len(secret) != secret_size:
  255. # fmt = 'Wrong size secret (%s bytes) for association type %s'
  256. # raise ValueError(fmt % (len(secret), assoc_type))
  257. self.handle = handle
  258. if isinstance(secret, str):
  259. secret = secret.encode("utf-8") # should be bytes
  260. self.secret = secret
  261. self.issued = issued
  262. self.lifetime = lifetime
  263. self.assoc_type = assoc_type
  264. @property
  265. def expiresIn(self, now=None):
  266. """
  267. This returns the number of seconds this association is still
  268. valid for, or C{0} if the association is no longer valid.
  269. @return: The number of seconds this association is still valid
  270. for, or C{0} if the association is no longer valid.
  271. @rtype: C{int}
  272. """
  273. if now is None:
  274. now = int(time.time())
  275. return max(0, self.issued + self.lifetime - now)
  276. def __lt__(self, other):
  277. """
  278. Compare two C{L{Association}} instances to determine relative
  279. ordering.
  280. Currently compares object lifetimes -- C{L{Association}} A < B
  281. if A.lifetime < B.lifetime.
  282. """
  283. return self.lifetime < other.lifetime
  284. def __eq__(self, other):
  285. """
  286. This checks to see if two C{L{Association}} instances
  287. represent the same association.
  288. @return: C{True} if the two instances represent the same
  289. association, C{False} otherwise.
  290. @rtype: C{bool}
  291. """
  292. return type(self) is type(other) and self.__dict__ == other.__dict__
  293. def __ne__(self, other):
  294. """
  295. This checks to see if two C{L{Association}} instances
  296. represent different associations.
  297. @return: C{True} if the two instances represent different
  298. associations, C{False} otherwise.
  299. @rtype: C{bool}
  300. """
  301. return not (self == other)
  302. def serialize(self):
  303. """
  304. Convert an association to KV form.
  305. @return: String in KV form suitable for deserialization by
  306. deserialize.
  307. @rtype: str
  308. """
  309. data = {
  310. 'version': '2',
  311. 'handle': self.handle,
  312. 'secret': oidutil.toBase64(self.secret),
  313. 'issued': str(int(self.issued)),
  314. 'lifetime': str(int(self.lifetime)),
  315. 'assoc_type': self.assoc_type
  316. }
  317. assert len(data) == len(self.assoc_keys)
  318. pairs = []
  319. for field_name in self.assoc_keys:
  320. pairs.append((field_name, data[field_name]))
  321. return kvform.seqToKV(pairs, strict=True)
  322. @classmethod
  323. def deserialize(cls, assoc_s):
  324. """
  325. Parse an association as stored by serialize().
  326. inverse of serialize
  327. @param assoc_s: Association as serialized by serialize()
  328. @type assoc_s: bytes
  329. @return: instance of this class
  330. """
  331. pairs = kvform.kvToSeq(assoc_s, strict=True)
  332. keys = []
  333. values = []
  334. for k, v in pairs:
  335. keys.append(k)
  336. values.append(v)
  337. if keys != cls.assoc_keys:
  338. raise ValueError('Unexpected key values: %r', keys)
  339. version, handle, secret, issued, lifetime, assoc_type = values
  340. if version != '2':
  341. raise ValueError('Unknown version: %r' % version)
  342. issued = int(issued)
  343. lifetime = int(lifetime)
  344. secret = oidutil.fromBase64(secret)
  345. return cls(handle, secret, issued, lifetime, assoc_type)
  346. def sign(self, pairs):
  347. """
  348. Generate a signature for a sequence of (key, value) pairs
  349. @param pairs: The pairs to sign, in order
  350. @type pairs: sequence of (str, str)
  351. @return: The binary signature of this sequence of pairs
  352. @rtype: bytes
  353. """
  354. kv = kvform.seqToKV(pairs)
  355. try:
  356. mac = self._macs[self.assoc_type]
  357. except KeyError:
  358. raise ValueError('Unknown association type: %r' %
  359. (self.assoc_type, ))
  360. return mac(self.secret, kv)
  361. def getMessageSignature(self, message):
  362. """Return the signature of a message.
  363. If I am not a sign-all association, the message must have a
  364. signed list.
  365. @return: the signature, base64 encoded
  366. @rtype: bytes
  367. @raises ValueError: If there is no signed list and I am not a sign-all
  368. type of association.
  369. """
  370. pairs = self._makePairs(message)
  371. return oidutil.toBase64(self.sign(pairs))
  372. def signMessage(self, message):
  373. """Add a signature (and a signed list) to a message.
  374. @return: a new Message object with a signature
  375. @rtype: L{openid.message.Message}
  376. """
  377. if (message.hasKey(OPENID_NS, 'sig') or
  378. message.hasKey(OPENID_NS, 'signed')):
  379. raise ValueError('Message already has signed list or signature')
  380. extant_handle = message.getArg(OPENID_NS, 'assoc_handle')
  381. if extant_handle and extant_handle != self.handle:
  382. raise ValueError("Message has a different association handle")
  383. signed_message = message.copy()
  384. signed_message.setArg(OPENID_NS, 'assoc_handle', self.handle)
  385. message_keys = list(signed_message.toPostArgs().keys())
  386. signed_list = [k[7:] for k in message_keys if k.startswith('openid.')]
  387. signed_list.append('signed')
  388. signed_list.sort()
  389. signed_message.setArg(OPENID_NS, 'signed', ','.join(signed_list))
  390. sig = self.getMessageSignature(signed_message)
  391. signed_message.setArg(OPENID_NS, 'sig', sig)
  392. return signed_message
  393. def checkMessageSignature(self, message):
  394. """Given a message with a signature, calculate a new signature
  395. and return whether it matches the signature in the message.
  396. @raises ValueError: if the message has no signature or no signature
  397. can be calculated for it.
  398. """
  399. message_sig = message.getArg(OPENID_NS, 'sig')
  400. if not message_sig:
  401. raise ValueError("%s has no sig." % (message, ))
  402. calculated_sig = self.getMessageSignature(message)
  403. # remember, getMessageSignature returns bytes
  404. calculated_sig = calculated_sig.decode('utf-8')
  405. return cryptutil.const_eq(calculated_sig, message_sig)
  406. def _makePairs(self, message):
  407. signed = message.getArg(OPENID_NS, 'signed')
  408. if not signed:
  409. raise ValueError('Message has no signed list: %s' % (message, ))
  410. signed_list = signed.split(',')
  411. pairs = []
  412. data = message.toPostArgs()
  413. for field in signed_list:
  414. pairs.append((field, data.get('openid.' + field, '')))
  415. return pairs
  416. def __repr__(self):
  417. return "<%s.%s %s %s>" % (self.__class__.__module__,
  418. self.__class__.__name__, self.assoc_type,
  419. self.handle)