association.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. # -*- test-case-name: openid.test.test_association -*-
  2. """
  3. This module contains code for dealing with associations between
  4. consumers and servers. Associations contain a shared secret that is
  5. used to sign C{openid.mode=id_res} messages.
  6. Users of the library should not usually need to interact directly with
  7. associations. The L{store<openid.store>},
  8. L{server<openid.server.server>} and
  9. 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. __all__ = [
  25. 'default_negotiator',
  26. 'encrypted_negotiator',
  27. 'SessionNegotiator',
  28. 'Association',
  29. ]
  30. import time
  31. from openid import cryptutil
  32. from openid import kvform
  33. from openid import oidutil
  34. from openid.message import OPENID_NS
  35. all_association_types = [
  36. 'HMAC-SHA1',
  37. 'HMAC-SHA256',
  38. ]
  39. if hasattr(cryptutil, 'hmacSha256'):
  40. supported_association_types = list(all_association_types)
  41. default_association_order = [
  42. ('HMAC-SHA1', 'DH-SHA1'),
  43. ('HMAC-SHA1', 'no-encryption'),
  44. ('HMAC-SHA256', 'DH-SHA256'),
  45. ('HMAC-SHA256', 'no-encryption'),
  46. ]
  47. only_encrypted_association_order = [
  48. ('HMAC-SHA1', 'DH-SHA1'),
  49. ('HMAC-SHA256', 'DH-SHA256'),
  50. ]
  51. else:
  52. supported_association_types = ['HMAC-SHA1']
  53. default_association_order = [
  54. ('HMAC-SHA1', 'DH-SHA1'),
  55. ('HMAC-SHA1', 'no-encryption'),
  56. ]
  57. only_encrypted_association_order = [
  58. ('HMAC-SHA1', 'DH-SHA1'),
  59. ]
  60. def getSessionTypes(assoc_type):
  61. """Return the allowed session types for a given association type"""
  62. assoc_to_session = {
  63. 'HMAC-SHA1': ['DH-SHA1', 'no-encryption'],
  64. 'HMAC-SHA256': ['DH-SHA256', 'no-encryption'],
  65. }
  66. return assoc_to_session.get(assoc_type, [])
  67. def checkSessionType(assoc_type, session_type):
  68. """Check to make sure that this pair of assoc type and session
  69. type are allowed"""
  70. if session_type not in getSessionTypes(assoc_type):
  71. raise ValueError(
  72. '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. class Association(object):
  159. """
  160. This class represents an association between a server and a
  161. consumer. In general, users of this library will never see
  162. instances of this object. The only exception is if you implement
  163. a custom C{L{OpenIDStore<openid.store.interface.OpenIDStore>}}.
  164. If you do implement such a store, it will need to store the values
  165. of the C{L{handle}}, C{L{secret}}, C{L{issued}}, C{L{lifetime}}, and
  166. C{L{assoc_type}} instance variables.
  167. @ivar handle: This is the handle the server gave this association.
  168. @type handle: C{str}
  169. @ivar secret: This is the shared secret the server generated for
  170. this association.
  171. @type secret: C{str}
  172. @ivar issued: This is the time this association was issued, in
  173. seconds since 00:00 GMT, January 1, 1970. (ie, a unix
  174. timestamp)
  175. @type issued: C{int}
  176. @ivar lifetime: This is the amount of time this association is
  177. good for, measured in seconds since the association was
  178. issued.
  179. @type lifetime: C{int}
  180. @ivar assoc_type: This is the type of association this instance
  181. represents. The only valid value of this field at this time
  182. is C{'HMAC-SHA1'}, but new types may be defined in the future.
  183. @type assoc_type: C{str}
  184. @sort: __init__, fromExpiresIn, getExpiresIn, __eq__, __ne__,
  185. handle, secret, issued, lifetime, assoc_type
  186. """
  187. # The ordering and name of keys as stored by serialize
  188. assoc_keys = [
  189. 'version',
  190. 'handle',
  191. 'secret',
  192. 'issued',
  193. 'lifetime',
  194. 'assoc_type',
  195. ]
  196. _macs = {
  197. 'HMAC-SHA1': cryptutil.hmacSha1,
  198. 'HMAC-SHA256': cryptutil.hmacSha256,
  199. }
  200. def fromExpiresIn(cls, expires_in, handle, secret, assoc_type):
  201. """
  202. This is an alternate constructor used by the OpenID consumer
  203. library to create associations. C{L{OpenIDStore
  204. <openid.store.interface.OpenIDStore>}} implementations
  205. shouldn't use this constructor.
  206. @param expires_in: This is the amount of time this association
  207. is good for, measured in seconds since the association was
  208. issued.
  209. @type expires_in: C{int}
  210. @param handle: This is the handle the server gave this
  211. association.
  212. @type handle: C{str}
  213. @param secret: This is the shared secret the server generated
  214. for this association.
  215. @type secret: C{str}
  216. @param assoc_type: This is the type of association this
  217. instance represents. The only valid value of this field
  218. at this time is C{'HMAC-SHA1'}, but new types may be
  219. defined in the future.
  220. @type assoc_type: C{str}
  221. """
  222. issued = int(time.time())
  223. lifetime = expires_in
  224. return cls(handle, secret, issued, lifetime, assoc_type)
  225. fromExpiresIn = classmethod(fromExpiresIn)
  226. def __init__(self, handle, secret, issued, lifetime, assoc_type):
  227. """
  228. This is the standard constructor for creating an association.
  229. @param handle: This is the handle the server gave this
  230. association.
  231. @type handle: C{str}
  232. @param secret: This is the shared secret the server generated
  233. for this association.
  234. @type secret: C{str}
  235. @param issued: This is the time this association was issued,
  236. in seconds since 00:00 GMT, January 1, 1970. (ie, a unix
  237. timestamp)
  238. @type issued: C{int}
  239. @param lifetime: This is the amount of time this association
  240. is good for, measured in seconds since the association was
  241. issued.
  242. @type lifetime: C{int}
  243. @param assoc_type: This is the type of association this
  244. instance represents. The only valid value of this field
  245. at this time is C{'HMAC-SHA1'}, but new types may be
  246. defined in the future.
  247. @type assoc_type: C{str}
  248. """
  249. if assoc_type not in all_association_types:
  250. fmt = '%r is not a supported association type'
  251. raise ValueError(fmt % (assoc_type,))
  252. # secret_size = getSecretSize(assoc_type)
  253. # if len(secret) != secret_size:
  254. # fmt = 'Wrong size secret (%s bytes) for association type %s'
  255. # raise ValueError(fmt % (len(secret), assoc_type))
  256. self.handle = handle
  257. self.secret = secret
  258. self.issued = issued
  259. self.lifetime = lifetime
  260. self.assoc_type = assoc_type
  261. def getExpiresIn(self, now=None):
  262. """
  263. This returns the number of seconds this association is still
  264. valid for, or C{0} if the association is no longer valid.
  265. @return: The number of seconds this association is still valid
  266. for, or C{0} if the association is no longer valid.
  267. @rtype: C{int}
  268. """
  269. if now is None:
  270. now = int(time.time())
  271. return max(0, self.issued + self.lifetime - now)
  272. expiresIn = property(getExpiresIn)
  273. def __eq__(self, other):
  274. """
  275. This checks to see if two C{L{Association}} instances
  276. represent the same association.
  277. @return: C{True} if the two instances represent the same
  278. association, C{False} otherwise.
  279. @rtype: C{bool}
  280. """
  281. return type(self) is type(other) and self.__dict__ == other.__dict__
  282. def __ne__(self, other):
  283. """
  284. This checks to see if two C{L{Association}} instances
  285. represent different associations.
  286. @return: C{True} if the two instances represent different
  287. associations, C{False} otherwise.
  288. @rtype: C{bool}
  289. """
  290. return not (self == other)
  291. def serialize(self):
  292. """
  293. Convert an association to KV form.
  294. @return: String in KV form suitable for deserialization by
  295. deserialize.
  296. @rtype: str
  297. """
  298. data = {
  299. 'version':'2',
  300. 'handle':self.handle,
  301. 'secret':oidutil.toBase64(self.secret),
  302. 'issued':str(int(self.issued)),
  303. 'lifetime':str(int(self.lifetime)),
  304. 'assoc_type':self.assoc_type
  305. }
  306. assert len(data) == len(self.assoc_keys)
  307. pairs = []
  308. for field_name in self.assoc_keys:
  309. pairs.append((field_name, data[field_name]))
  310. return kvform.seqToKV(pairs, strict=True)
  311. def deserialize(cls, assoc_s):
  312. """
  313. Parse an association as stored by serialize().
  314. inverse of serialize
  315. @param assoc_s: Association as serialized by serialize()
  316. @type assoc_s: str
  317. @return: instance of this class
  318. """
  319. pairs = kvform.kvToSeq(assoc_s, strict=True)
  320. keys = []
  321. values = []
  322. for k, v in pairs:
  323. keys.append(k)
  324. values.append(v)
  325. if keys != cls.assoc_keys:
  326. raise ValueError('Unexpected key values: %r', keys)
  327. version, handle, secret, issued, lifetime, assoc_type = values
  328. if version != '2':
  329. raise ValueError('Unknown version: %r' % version)
  330. issued = int(issued)
  331. lifetime = int(lifetime)
  332. secret = oidutil.fromBase64(secret)
  333. return cls(handle, secret, issued, lifetime, assoc_type)
  334. deserialize = classmethod(deserialize)
  335. def sign(self, pairs):
  336. """
  337. Generate a signature for a sequence of (key, value) pairs
  338. @param pairs: The pairs to sign, in order
  339. @type pairs: sequence of (str, str)
  340. @return: The binary signature of this sequence of pairs
  341. @rtype: str
  342. """
  343. kv = kvform.seqToKV(pairs)
  344. try:
  345. mac = self._macs[self.assoc_type]
  346. except KeyError:
  347. raise ValueError(
  348. 'Unknown association type: %r' % (self.assoc_type,))
  349. return mac(self.secret, kv)
  350. def getMessageSignature(self, message):
  351. """Return the signature of a message.
  352. If I am not a sign-all association, the message must have a
  353. signed list.
  354. @return: the signature, base64 encoded
  355. @rtype: str
  356. @raises ValueError: If there is no signed list and I am not a sign-all
  357. type of association.
  358. """
  359. pairs = self._makePairs(message)
  360. return oidutil.toBase64(self.sign(pairs))
  361. def signMessage(self, message):
  362. """Add a signature (and a signed list) to a message.
  363. @return: a new Message object with a signature
  364. @rtype: L{openid.message.Message}
  365. """
  366. if (message.hasKey(OPENID_NS, 'sig') or
  367. message.hasKey(OPENID_NS, 'signed')):
  368. raise ValueError('Message already has signed list or signature')
  369. extant_handle = message.getArg(OPENID_NS, 'assoc_handle')
  370. if extant_handle and extant_handle != self.handle:
  371. raise ValueError("Message has a different association handle")
  372. signed_message = message.copy()
  373. signed_message.setArg(OPENID_NS, 'assoc_handle', self.handle)
  374. message_keys = signed_message.toPostArgs().keys()
  375. signed_list = [k[7:] for k in message_keys
  376. if k.startswith('openid.')]
  377. signed_list.append('signed')
  378. signed_list.sort()
  379. signed_message.setArg(OPENID_NS, 'signed', ','.join(signed_list))
  380. sig = self.getMessageSignature(signed_message)
  381. signed_message.setArg(OPENID_NS, 'sig', sig)
  382. return signed_message
  383. def checkMessageSignature(self, message):
  384. """Given a message with a signature, calculate a new signature
  385. and return whether it matches the signature in the message.
  386. @raises ValueError: if the message has no signature or no signature
  387. can be calculated for it.
  388. """
  389. message_sig = message.getArg(OPENID_NS, 'sig')
  390. if not message_sig:
  391. raise ValueError("%s has no sig." % (message,))
  392. calculated_sig = self.getMessageSignature(message)
  393. return calculated_sig == message_sig
  394. def _makePairs(self, message):
  395. signed = message.getArg(OPENID_NS, 'signed')
  396. if not signed:
  397. raise ValueError('Message has no signed list: %s' % (message,))
  398. signed_list = signed.split(',')
  399. pairs = []
  400. data = message.toPostArgs()
  401. for field in signed_list:
  402. pairs.append((field, data.get('openid.' + field, '')))
  403. return pairs
  404. def __repr__(self):
  405. return "<%s.%s %s %s>" % (
  406. self.__class__.__module__,
  407. self.__class__.__name__,
  408. self.assoc_type,
  409. self.handle)