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.
 
 
 
 

217 lines
7.1 KiB

  1. """
  2. """
  3. # Created on 2015.05.01
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2015 - 2020 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 logging import getLogger, DEBUG
  25. from copy import deepcopy
  26. from pprint import pformat
  27. from ..protocol.rfc4511 import LDAPMessage
  28. # logging levels
  29. OFF = 0
  30. ERROR = 10
  31. BASIC = 20
  32. PROTOCOL = 30
  33. NETWORK = 40
  34. EXTENDED = 50
  35. _sensitive_lines = ('simple', 'credentials', 'serversaslcreds') # must be a tuple, not a list, lowercase
  36. _sensitive_args = ('simple', 'password', 'sasl_credentials', 'saslcreds', 'server_creds')
  37. _sensitive_attrs = ('userpassword', 'unicodepwd')
  38. _hide_sensitive_data = None
  39. DETAIL_LEVELS = [OFF, ERROR, BASIC, PROTOCOL, NETWORK, EXTENDED]
  40. _max_line_length = 4096
  41. _logging_level = 0
  42. _detail_level = 0
  43. _logging_encoding = 'ascii'
  44. try:
  45. from logging import NullHandler
  46. except ImportError: # NullHandler not present in Python < 2.7
  47. from logging import Handler
  48. class NullHandler(Handler):
  49. def handle(self, record):
  50. pass
  51. def emit(self, record):
  52. pass
  53. def createLock(self):
  54. self.lock = None
  55. def _strip_sensitive_data_from_dict(d):
  56. if not isinstance(d, dict):
  57. return d
  58. try:
  59. d = deepcopy(d)
  60. except Exception: # if deepcopy goes wrong gives up and returns the dict unchanged
  61. return d
  62. for k in d.keys():
  63. if isinstance(d[k], dict):
  64. d[k] = _strip_sensitive_data_from_dict(d[k])
  65. elif k.lower() in _sensitive_args and d[k]:
  66. d[k] = '<stripped %d characters of sensitive data>' % len(d[k])
  67. return d
  68. def get_detail_level_name(level_name):
  69. if level_name == OFF:
  70. return 'OFF'
  71. elif level_name == ERROR:
  72. return 'ERROR'
  73. elif level_name == BASIC:
  74. return 'BASIC'
  75. elif level_name == PROTOCOL:
  76. return 'PROTOCOL'
  77. elif level_name == NETWORK:
  78. return 'NETWORK'
  79. elif level_name == EXTENDED:
  80. return 'EXTENDED'
  81. raise ValueError('unknown detail level')
  82. def log(detail, message, *args):
  83. if detail <= _detail_level:
  84. if _hide_sensitive_data:
  85. args = tuple([_strip_sensitive_data_from_dict(arg) if isinstance(arg, dict) else arg for arg in args])
  86. if str is not bytes: # Python 3
  87. encoded_message = (get_detail_level_name(detail) + ':' + message % args).encode(_logging_encoding, 'backslashreplace')
  88. encoded_message = encoded_message.decode()
  89. else:
  90. try:
  91. encoded_message = (get_detail_level_name(detail) + ':' + message % args).encode(_logging_encoding, 'replace')
  92. except Exception:
  93. encoded_message = (get_detail_level_name(detail) + ':' + message % args).decode(_logging_encoding, 'replace')
  94. if len(encoded_message) > _max_line_length:
  95. logger.log(_logging_level, encoded_message[:_max_line_length] + ' <removed %d remaining bytes in this log line>' % (len(encoded_message) - _max_line_length, ))
  96. else:
  97. logger.log(_logging_level, encoded_message)
  98. def log_enabled(detail):
  99. if detail <= _detail_level:
  100. if logger.isEnabledFor(_logging_level):
  101. return True
  102. return False
  103. def set_library_log_hide_sensitive_data(hide=True):
  104. global _hide_sensitive_data
  105. if hide:
  106. _hide_sensitive_data = True
  107. else:
  108. _hide_sensitive_data = False
  109. if log_enabled(ERROR):
  110. log(ERROR, 'hide sensitive data set to ' + str(_hide_sensitive_data))
  111. def get_library_log_hide_sensitive_data():
  112. return True if _hide_sensitive_data else False
  113. def set_library_log_activation_level(logging_level):
  114. if isinstance(logging_level, int):
  115. global _logging_level
  116. _logging_level = logging_level
  117. else:
  118. if log_enabled(ERROR):
  119. log(ERROR, 'invalid library log activation level <%s> ', logging_level)
  120. raise ValueError('invalid library log activation level')
  121. def get_library_log_activation_lavel():
  122. return _logging_level
  123. def set_library_log_max_line_length(length):
  124. if isinstance(length, int):
  125. global _max_line_length
  126. _max_line_length = length
  127. else:
  128. if log_enabled(ERROR):
  129. log(ERROR, 'invalid log max line length <%s> ', length)
  130. raise ValueError('invalid library log max line length')
  131. def get_library_log_max_line_length():
  132. return _max_line_length
  133. def set_library_log_detail_level(detail):
  134. if detail in DETAIL_LEVELS:
  135. global _detail_level
  136. _detail_level = detail
  137. if log_enabled(ERROR):
  138. log(ERROR, 'detail level set to ' + get_detail_level_name(_detail_level))
  139. else:
  140. if log_enabled(ERROR):
  141. log(ERROR, 'unable to set log detail level to <%s>', detail)
  142. raise ValueError('invalid library log detail level')
  143. def get_library_log_detail_level():
  144. return _detail_level
  145. def format_ldap_message(message, prefix):
  146. if isinstance(message, LDAPMessage):
  147. try: # pyasn1 prettyprint raises exception in version 0.4.3
  148. formatted = message.prettyPrint().split('\n') # pyasn1 pretty print
  149. except Exception as e:
  150. formatted = ['pyasn1 exception', str(e)]
  151. else:
  152. formatted = pformat(message).split('\n')
  153. prefixed = ''
  154. for line in formatted:
  155. if line:
  156. if _hide_sensitive_data and line.strip().lower().startswith(_sensitive_lines): # _sensitive_lines is a tuple. startswith() method checks each tuple element
  157. tag, _, data = line.partition('=')
  158. if data.startswith("b'") and data.endswith("'") or data.startswith('b"') and data.endswith('"'):
  159. prefixed += '\n' + prefix + tag + '=<stripped %d characters of sensitive data>' % (len(data) - 3, )
  160. else:
  161. prefixed += '\n' + prefix + tag + '=<stripped %d characters of sensitive data>' % len(data)
  162. else:
  163. prefixed += '\n' + prefix + line
  164. return prefixed
  165. # sets a logger for the library with NullHandler. It can be used by the application with its own logging configuration
  166. logger = getLogger('ldap3')
  167. logger.addHandler(NullHandler())
  168. # sets defaults for the library logging
  169. set_library_log_activation_level(DEBUG)
  170. set_library_log_detail_level(OFF)
  171. set_library_log_hide_sensitive_data(True)