Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exceptions.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. """
  2. """
  3. # Created on 2014.05.14
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2018 Giovanni Cannata
  8. #
  9. # This file is part of ldap3.
  10. #
  11. # ldap3 is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # ldap3 is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Lesser General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Lesser General Public License
  22. # along with ldap3 in the COPYING and COPYING.LESSER files.
  23. # If not, see <http://www.gnu.org/licenses/>.
  24. from os import sep
  25. from .results import RESULT_OPERATIONS_ERROR, RESULT_PROTOCOL_ERROR, RESULT_TIME_LIMIT_EXCEEDED, RESULT_SIZE_LIMIT_EXCEEDED, \
  26. RESULT_STRONGER_AUTH_REQUIRED, RESULT_REFERRAL, RESULT_ADMIN_LIMIT_EXCEEDED, RESULT_UNAVAILABLE_CRITICAL_EXTENSION, \
  27. RESULT_AUTH_METHOD_NOT_SUPPORTED, RESULT_UNDEFINED_ATTRIBUTE_TYPE, RESULT_NO_SUCH_ATTRIBUTE, \
  28. RESULT_SASL_BIND_IN_PROGRESS, RESULT_CONFIDENTIALITY_REQUIRED, RESULT_INAPPROPRIATE_MATCHING, \
  29. RESULT_CONSTRAINT_VIOLATION, \
  30. RESULT_ATTRIBUTE_OR_VALUE_EXISTS, RESULT_INVALID_ATTRIBUTE_SYNTAX, RESULT_NO_SUCH_OBJECT, RESULT_ALIAS_PROBLEM, \
  31. RESULT_INVALID_DN_SYNTAX, RESULT_ALIAS_DEREFERENCING_PROBLEM, RESULT_INVALID_CREDENTIALS, RESULT_LOOP_DETECTED, \
  32. RESULT_ENTRY_ALREADY_EXISTS, RESULT_LCUP_SECURITY_VIOLATION, RESULT_CANCELED, RESULT_E_SYNC_REFRESH_REQUIRED, \
  33. RESULT_NO_SUCH_OPERATION, RESULT_LCUP_INVALID_DATA, RESULT_OBJECT_CLASS_MODS_PROHIBITED, RESULT_NAMING_VIOLATION, \
  34. RESULT_INSUFFICIENT_ACCESS_RIGHTS, RESULT_OBJECT_CLASS_VIOLATION, RESULT_TOO_LATE, RESULT_CANNOT_CANCEL, \
  35. RESULT_LCUP_UNSUPPORTED_SCHEME, RESULT_BUSY, RESULT_AFFECT_MULTIPLE_DSAS, RESULT_UNAVAILABLE, \
  36. RESULT_NOT_ALLOWED_ON_NON_LEAF, \
  37. RESULT_UNWILLING_TO_PERFORM, RESULT_OTHER, RESULT_LCUP_RELOAD_REQUIRED, RESULT_ASSERTION_FAILED, \
  38. RESULT_AUTHORIZATION_DENIED, RESULT_LCUP_RESOURCES_EXHAUSTED, RESULT_NOT_ALLOWED_ON_RDN, \
  39. RESULT_INAPPROPRIATE_AUTHENTICATION
  40. import socket
  41. # LDAPException hierarchy
  42. class LDAPException(Exception):
  43. pass
  44. class LDAPOperationResult(LDAPException):
  45. def __new__(cls, result=None, description=None, dn=None, message=None, response_type=None, response=None):
  46. if cls is LDAPOperationResult and result and result in exception_table:
  47. exc = super(LDAPOperationResult, exception_table[result]).__new__(
  48. exception_table[result]) # create an exception of the required result error
  49. exc.result = result
  50. exc.description = description
  51. exc.dn = dn
  52. exc.message = message
  53. exc.type = response_type
  54. exc.response = response
  55. else:
  56. exc = super(LDAPOperationResult, cls).__new__(cls)
  57. return exc
  58. def __init__(self, result=None, description=None, dn=None, message=None, response_type=None, response=None):
  59. self.result = result
  60. self.description = description
  61. self.dn = dn
  62. self.message = message
  63. self.type = response_type
  64. self.response = response
  65. def __str__(self):
  66. s = [self.__class__.__name__,
  67. str(self.result) if self.result else None,
  68. self.description if self.description else None,
  69. self.dn if self.dn else None,
  70. self.message if self.message else None,
  71. self.type if self.type else None,
  72. self.response if self.response else None]
  73. return ' - '.join([str(item) for item in s if s is not None])
  74. def __repr__(self):
  75. return self.__str__()
  76. class LDAPOperationsErrorResult(LDAPOperationResult):
  77. pass
  78. class LDAPProtocolErrorResult(LDAPOperationResult):
  79. pass
  80. class LDAPTimeLimitExceededResult(LDAPOperationResult):
  81. pass
  82. class LDAPSizeLimitExceededResult(LDAPOperationResult):
  83. pass
  84. class LDAPAuthMethodNotSupportedResult(LDAPOperationResult):
  85. pass
  86. class LDAPStrongerAuthRequiredResult(LDAPOperationResult):
  87. pass
  88. class LDAPReferralResult(LDAPOperationResult):
  89. pass
  90. class LDAPAdminLimitExceededResult(LDAPOperationResult):
  91. pass
  92. class LDAPUnavailableCriticalExtensionResult(LDAPOperationResult):
  93. pass
  94. class LDAPConfidentialityRequiredResult(LDAPOperationResult):
  95. pass
  96. class LDAPSASLBindInProgressResult(LDAPOperationResult):
  97. pass
  98. class LDAPNoSuchAttributeResult(LDAPOperationResult):
  99. pass
  100. class LDAPUndefinedAttributeTypeResult(LDAPOperationResult):
  101. pass
  102. class LDAPInappropriateMatchingResult(LDAPOperationResult):
  103. pass
  104. class LDAPConstraintViolationResult(LDAPOperationResult):
  105. pass
  106. class LDAPAttributeOrValueExistsResult(LDAPOperationResult):
  107. pass
  108. class LDAPInvalidAttributeSyntaxResult(LDAPOperationResult):
  109. pass
  110. class LDAPNoSuchObjectResult(LDAPOperationResult):
  111. pass
  112. class LDAPAliasProblemResult(LDAPOperationResult):
  113. pass
  114. class LDAPInvalidDNSyntaxResult(LDAPOperationResult):
  115. pass
  116. class LDAPAliasDereferencingProblemResult(LDAPOperationResult):
  117. pass
  118. class LDAPInappropriateAuthenticationResult(LDAPOperationResult):
  119. pass
  120. class LDAPInvalidCredentialsResult(LDAPOperationResult):
  121. pass
  122. class LDAPInsufficientAccessRightsResult(LDAPOperationResult):
  123. pass
  124. class LDAPBusyResult(LDAPOperationResult):
  125. pass
  126. class LDAPUnavailableResult(LDAPOperationResult):
  127. pass
  128. class LDAPUnwillingToPerformResult(LDAPOperationResult):
  129. pass
  130. class LDAPLoopDetectedResult(LDAPOperationResult):
  131. pass
  132. class LDAPNamingViolationResult(LDAPOperationResult):
  133. pass
  134. class LDAPObjectClassViolationResult(LDAPOperationResult):
  135. pass
  136. class LDAPNotAllowedOnNotLeafResult(LDAPOperationResult):
  137. pass
  138. class LDAPNotAllowedOnRDNResult(LDAPOperationResult):
  139. pass
  140. class LDAPEntryAlreadyExistsResult(LDAPOperationResult):
  141. pass
  142. class LDAPObjectClassModsProhibitedResult(LDAPOperationResult):
  143. pass
  144. class LDAPAffectMultipleDSASResult(LDAPOperationResult):
  145. pass
  146. class LDAPOtherResult(LDAPOperationResult):
  147. pass
  148. class LDAPLCUPResourcesExhaustedResult(LDAPOperationResult):
  149. pass
  150. class LDAPLCUPSecurityViolationResult(LDAPOperationResult):
  151. pass
  152. class LDAPLCUPInvalidDataResult(LDAPOperationResult):
  153. pass
  154. class LDAPLCUPUnsupportedSchemeResult(LDAPOperationResult):
  155. pass
  156. class LDAPLCUPReloadRequiredResult(LDAPOperationResult):
  157. pass
  158. class LDAPCanceledResult(LDAPOperationResult):
  159. pass
  160. class LDAPNoSuchOperationResult(LDAPOperationResult):
  161. pass
  162. class LDAPTooLateResult(LDAPOperationResult):
  163. pass
  164. class LDAPCannotCancelResult(LDAPOperationResult):
  165. pass
  166. class LDAPAssertionFailedResult(LDAPOperationResult):
  167. pass
  168. class LDAPAuthorizationDeniedResult(LDAPOperationResult):
  169. pass
  170. class LDAPESyncRefreshRequiredResult(LDAPOperationResult):
  171. pass
  172. exception_table = {RESULT_OPERATIONS_ERROR: LDAPOperationsErrorResult,
  173. RESULT_PROTOCOL_ERROR: LDAPProtocolErrorResult,
  174. RESULT_TIME_LIMIT_EXCEEDED: LDAPTimeLimitExceededResult,
  175. RESULT_SIZE_LIMIT_EXCEEDED: LDAPSizeLimitExceededResult,
  176. RESULT_AUTH_METHOD_NOT_SUPPORTED: LDAPAuthMethodNotSupportedResult,
  177. RESULT_STRONGER_AUTH_REQUIRED: LDAPStrongerAuthRequiredResult,
  178. RESULT_REFERRAL: LDAPReferralResult,
  179. RESULT_ADMIN_LIMIT_EXCEEDED: LDAPAdminLimitExceededResult,
  180. RESULT_UNAVAILABLE_CRITICAL_EXTENSION: LDAPUnavailableCriticalExtensionResult,
  181. RESULT_CONFIDENTIALITY_REQUIRED: LDAPConfidentialityRequiredResult,
  182. RESULT_SASL_BIND_IN_PROGRESS: LDAPSASLBindInProgressResult,
  183. RESULT_NO_SUCH_ATTRIBUTE: LDAPNoSuchAttributeResult,
  184. RESULT_UNDEFINED_ATTRIBUTE_TYPE: LDAPUndefinedAttributeTypeResult,
  185. RESULT_INAPPROPRIATE_MATCHING: LDAPInappropriateMatchingResult,
  186. RESULT_CONSTRAINT_VIOLATION: LDAPConstraintViolationResult,
  187. RESULT_ATTRIBUTE_OR_VALUE_EXISTS: LDAPAttributeOrValueExistsResult,
  188. RESULT_INVALID_ATTRIBUTE_SYNTAX: LDAPInvalidAttributeSyntaxResult,
  189. RESULT_NO_SUCH_OBJECT: LDAPNoSuchObjectResult,
  190. RESULT_ALIAS_PROBLEM: LDAPAliasProblemResult,
  191. RESULT_INVALID_DN_SYNTAX: LDAPInvalidDNSyntaxResult,
  192. RESULT_ALIAS_DEREFERENCING_PROBLEM: LDAPAliasDereferencingProblemResult,
  193. RESULT_INAPPROPRIATE_AUTHENTICATION: LDAPInappropriateAuthenticationResult,
  194. RESULT_INVALID_CREDENTIALS: LDAPInvalidCredentialsResult,
  195. RESULT_INSUFFICIENT_ACCESS_RIGHTS: LDAPInsufficientAccessRightsResult,
  196. RESULT_BUSY: LDAPBusyResult,
  197. RESULT_UNAVAILABLE: LDAPUnavailableResult,
  198. RESULT_UNWILLING_TO_PERFORM: LDAPUnwillingToPerformResult,
  199. RESULT_LOOP_DETECTED: LDAPLoopDetectedResult,
  200. RESULT_NAMING_VIOLATION: LDAPNamingViolationResult,
  201. RESULT_OBJECT_CLASS_VIOLATION: LDAPObjectClassViolationResult,
  202. RESULT_NOT_ALLOWED_ON_NON_LEAF: LDAPNotAllowedOnNotLeafResult,
  203. RESULT_NOT_ALLOWED_ON_RDN: LDAPNotAllowedOnRDNResult,
  204. RESULT_ENTRY_ALREADY_EXISTS: LDAPEntryAlreadyExistsResult,
  205. RESULT_OBJECT_CLASS_MODS_PROHIBITED: LDAPObjectClassModsProhibitedResult,
  206. RESULT_AFFECT_MULTIPLE_DSAS: LDAPAffectMultipleDSASResult,
  207. RESULT_OTHER: LDAPOtherResult,
  208. RESULT_LCUP_RESOURCES_EXHAUSTED: LDAPLCUPResourcesExhaustedResult,
  209. RESULT_LCUP_SECURITY_VIOLATION: LDAPLCUPSecurityViolationResult,
  210. RESULT_LCUP_INVALID_DATA: LDAPLCUPInvalidDataResult,
  211. RESULT_LCUP_UNSUPPORTED_SCHEME: LDAPLCUPUnsupportedSchemeResult,
  212. RESULT_LCUP_RELOAD_REQUIRED: LDAPLCUPReloadRequiredResult,
  213. RESULT_CANCELED: LDAPCanceledResult,
  214. RESULT_NO_SUCH_OPERATION: LDAPNoSuchOperationResult,
  215. RESULT_TOO_LATE: LDAPTooLateResult,
  216. RESULT_CANNOT_CANCEL: LDAPCannotCancelResult,
  217. RESULT_ASSERTION_FAILED: LDAPAssertionFailedResult,
  218. RESULT_AUTHORIZATION_DENIED: LDAPAuthorizationDeniedResult,
  219. RESULT_E_SYNC_REFRESH_REQUIRED: LDAPESyncRefreshRequiredResult}
  220. class LDAPExceptionError(LDAPException):
  221. pass
  222. # configuration exceptions
  223. class LDAPConfigurationError(LDAPExceptionError):
  224. pass
  225. class LDAPUnknownStrategyError(LDAPConfigurationError):
  226. pass
  227. class LDAPUnknownAuthenticationMethodError(LDAPConfigurationError):
  228. pass
  229. class LDAPSSLConfigurationError(LDAPConfigurationError):
  230. pass
  231. class LDAPDefinitionError(LDAPConfigurationError):
  232. pass
  233. class LDAPPackageUnavailableError(LDAPConfigurationError, ImportError):
  234. pass
  235. class LDAPConfigurationParameterError(LDAPConfigurationError):
  236. pass
  237. # abstract layer exceptions
  238. class LDAPKeyError(LDAPExceptionError, KeyError, AttributeError):
  239. pass
  240. class LDAPObjectError(LDAPExceptionError, ValueError):
  241. pass
  242. class LDAPAttributeError(LDAPExceptionError, ValueError, TypeError):
  243. pass
  244. class LDAPCursorError(LDAPExceptionError):
  245. pass
  246. class LDAPObjectDereferenceError(LDAPExceptionError):
  247. pass
  248. # security exceptions
  249. class LDAPSSLNotSupportedError(LDAPExceptionError, ImportError):
  250. pass
  251. class LDAPInvalidTlsSpecificationError(LDAPExceptionError):
  252. pass
  253. class LDAPInvalidHashAlgorithmError(LDAPExceptionError, ValueError):
  254. pass
  255. # connection exceptions
  256. class LDAPBindError(LDAPExceptionError):
  257. pass
  258. class LDAPInvalidServerError(LDAPExceptionError):
  259. pass
  260. class LDAPSASLMechanismNotSupportedError(LDAPExceptionError):
  261. pass
  262. class LDAPConnectionIsReadOnlyError(LDAPExceptionError):
  263. pass
  264. class LDAPChangeError(LDAPExceptionError, ValueError):
  265. pass
  266. class LDAPServerPoolError(LDAPExceptionError):
  267. pass
  268. class LDAPServerPoolExhaustedError(LDAPExceptionError):
  269. pass
  270. class LDAPInvalidPortError(LDAPExceptionError):
  271. pass
  272. class LDAPStartTLSError(LDAPExceptionError):
  273. pass
  274. class LDAPCertificateError(LDAPExceptionError):
  275. pass
  276. class LDAPUserNameNotAllowedError(LDAPExceptionError):
  277. pass
  278. class LDAPUserNameIsMandatoryError(LDAPExceptionError):
  279. pass
  280. class LDAPPasswordIsMandatoryError(LDAPExceptionError):
  281. pass
  282. class LDAPInvalidFilterError(LDAPExceptionError):
  283. pass
  284. class LDAPInvalidScopeError(LDAPExceptionError, ValueError):
  285. pass
  286. class LDAPInvalidDereferenceAliasesError(LDAPExceptionError, ValueError):
  287. pass
  288. class LDAPInvalidValueError(LDAPExceptionError, ValueError):
  289. pass
  290. class LDAPControlError(LDAPExceptionError, ValueError):
  291. pass
  292. class LDAPExtensionError(LDAPExceptionError, ValueError):
  293. pass
  294. class LDAPLDIFError(LDAPExceptionError):
  295. pass
  296. class LDAPSchemaError(LDAPExceptionError):
  297. pass
  298. class LDAPSASLPrepError(LDAPExceptionError):
  299. pass
  300. class LDAPSASLBindInProgressError(LDAPExceptionError):
  301. pass
  302. class LDAPMetricsError(LDAPExceptionError):
  303. pass
  304. class LDAPObjectClassError(LDAPExceptionError):
  305. pass
  306. class LDAPInvalidDnError(LDAPExceptionError):
  307. pass
  308. class LDAPResponseTimeoutError(LDAPExceptionError):
  309. pass
  310. class LDAPTransactionError(LDAPExceptionError):
  311. pass
  312. # communication exceptions
  313. class LDAPCommunicationError(LDAPExceptionError):
  314. pass
  315. class LDAPSocketOpenError(LDAPCommunicationError):
  316. pass
  317. class LDAPSocketCloseError(LDAPCommunicationError):
  318. pass
  319. class LDAPSocketReceiveError(LDAPCommunicationError, socket.error):
  320. pass
  321. class LDAPSocketSendError(LDAPCommunicationError, socket.error):
  322. pass
  323. class LDAPSessionTerminatedByServerError(LDAPCommunicationError):
  324. pass
  325. class LDAPUnknownResponseError(LDAPCommunicationError):
  326. pass
  327. class LDAPUnknownRequestError(LDAPCommunicationError):
  328. pass
  329. class LDAPReferralError(LDAPCommunicationError):
  330. pass
  331. # pooling exceptions
  332. class LDAPConnectionPoolNameIsMandatoryError(LDAPExceptionError):
  333. pass
  334. class LDAPConnectionPoolNotStartedError(LDAPExceptionError):
  335. pass
  336. # restartable strategy
  337. class LDAPMaximumRetriesError(LDAPExceptionError):
  338. def __str__(self):
  339. s = []
  340. if self.args:
  341. if isinstance(self.args, tuple):
  342. if len(self.args) > 0:
  343. s.append('LDAPMaximumRetriesError: ' + str(self.args[0]))
  344. if len(self.args) > 1:
  345. s.append('Exception history:')
  346. prev_exc = ''
  347. for i, exc in enumerate(self.args[1]): # args[1] contains exception history
  348. if str(exc[1]) != prev_exc:
  349. s.append((str(i).rjust(5) + ' ' + str(exc[0]) + ': ' + str(exc[1]) + ' - ' + str(exc[2])))
  350. prev_exc = str(exc[1])
  351. if len(self.args) > 2:
  352. s.append('Maximum number of retries reached: ' + str(self.args[2]))
  353. else:
  354. s = [LDAPExceptionError.__str__(self)]
  355. return sep.join(s)
  356. # exception factories
  357. def communication_exception_factory(exc_to_raise, exc):
  358. """
  359. Generates a new exception class of the requested type (subclass of LDAPCommunication) merged with the exception raised by the interpreter
  360. """
  361. if exc_to_raise.__name__ in [cls.__name__ for cls in LDAPCommunicationError.__subclasses__()]:
  362. return type(exc_to_raise.__name__, (exc_to_raise, type(exc)), dict())
  363. else:
  364. raise LDAPExceptionError('unable to generate exception type ' + str(exc_to_raise))
  365. def start_tls_exception_factory(exc_to_raise, exc):
  366. """
  367. Generates a new exception class of the requested type (subclass of LDAPCommunication) merged with the exception raised by the interpreter
  368. """
  369. if exc_to_raise.__name__ == 'LDAPStartTLSError':
  370. return type(exc_to_raise.__name__, (exc_to_raise, type(exc)), dict())
  371. else:
  372. raise LDAPExceptionError('unable to generate exception type ' + str(exc_to_raise))