選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

287 行
10 KiB

  1. """
  2. """
  3. # Created on 2013.12.08
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2013 - 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 base64 import b64encode
  25. from datetime import datetime
  26. from .. import STRING_TYPES
  27. from ..core.exceptions import LDAPLDIFError, LDAPExtensionError
  28. from ..protocol.persistentSearch import EntryChangeNotificationControl
  29. from ..utils.asn1 import decoder
  30. # LDIF converter RFC 2849 compliant
  31. LDIF_LINE_LENGTH = 78
  32. def safe_ldif_string(bytes_value):
  33. if not bytes_value:
  34. return True
  35. # check SAFE-INIT-CHAR: < 127, not NUL, LF, CR, SPACE, COLON, LESS-THAN
  36. if bytes_value[0] > 127 or bytes_value[0] in [0, 10, 13, 32, 58, 60]:
  37. return False
  38. # check SAFE-CHAR: < 127 not NUL, LF, CR
  39. if 0 in bytes_value or 10 in bytes_value or 13 in bytes_value:
  40. return False
  41. # check last char for SPACE
  42. if bytes_value[-1] == 32:
  43. return False
  44. for byte in bytes_value:
  45. if byte > 127:
  46. return False
  47. return True
  48. def _convert_to_ldif(descriptor, value, base64):
  49. if not value:
  50. value = ''
  51. if isinstance(value, STRING_TYPES):
  52. value = bytearray(value, encoding='utf-8')
  53. if base64 or not safe_ldif_string(value):
  54. try:
  55. encoded = b64encode(value)
  56. except TypeError:
  57. encoded = b64encode(str(value)) # patch for Python 2.6
  58. if not isinstance(encoded, str): # in Python 3 b64encode returns bytes in Python 2 returns str
  59. encoded = str(encoded, encoding='ascii') # Python 3
  60. line = descriptor + ':: ' + encoded
  61. else:
  62. if str is not bytes: # Python 3
  63. value = str(value, encoding='ascii')
  64. else: # Python 2
  65. value = str(value)
  66. line = descriptor + ': ' + value
  67. return line
  68. def add_controls(controls, all_base64):
  69. lines = []
  70. if controls:
  71. for control in controls:
  72. line = 'control: ' + control[0]
  73. line += ' ' + ('true' if control[1] else 'false')
  74. if control[2]:
  75. lines.append(_convert_to_ldif(line, control[2], all_base64))
  76. return lines
  77. def add_attributes(attributes, all_base64):
  78. lines = []
  79. oc_attr = None
  80. # objectclass first, even if this is not specified in the RFC
  81. for attr in attributes:
  82. if attr.lower() == 'objectclass':
  83. for val in attributes[attr]:
  84. lines.append(_convert_to_ldif(attr, val, all_base64))
  85. oc_attr = attr
  86. break
  87. # remaining attributes
  88. for attr in attributes:
  89. if attr != oc_attr and attr in attributes:
  90. for val in attributes[attr]:
  91. lines.append(_convert_to_ldif(attr, val, all_base64))
  92. return lines
  93. def sort_ldif_lines(lines, sort_order):
  94. # sort lines as per custom sort_order
  95. # sort order is a list of descriptors, lines will be sorted following the same sequence
  96. return sorted(lines, key=lambda x: ldif_sort(x, sort_order)) if sort_order else lines
  97. def search_response_to_ldif(entries, all_base64, sort_order=None):
  98. lines = []
  99. if entries:
  100. for entry in entries:
  101. if not entry:
  102. continue
  103. if 'dn' in entry:
  104. lines.append(_convert_to_ldif('dn', entry['dn'], all_base64))
  105. lines.extend(add_attributes(entry['raw_attributes'], all_base64))
  106. else:
  107. raise LDAPLDIFError('unable to convert to LDIF-CONTENT - missing DN')
  108. if sort_order:
  109. lines = sort_ldif_lines(lines, sort_order)
  110. lines.append('')
  111. if lines:
  112. lines.append('# total number of entries: ' + str(len(entries)))
  113. return lines
  114. def add_request_to_ldif(entry, all_base64, sort_order=None):
  115. lines = []
  116. if 'entry' in entry:
  117. lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))
  118. lines.extend(add_controls(entry['controls'], all_base64))
  119. lines.append('changetype: add')
  120. lines.extend(add_attributes(entry['attributes'], all_base64))
  121. if sort_order:
  122. lines = sort_ldif_lines(lines, sort_order)
  123. else:
  124. raise LDAPLDIFError('unable to convert to LDIF-CHANGE-ADD - missing DN ')
  125. return lines
  126. def delete_request_to_ldif(entry, all_base64, sort_order=None):
  127. lines = []
  128. if 'entry' in entry:
  129. lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))
  130. lines.append(add_controls(entry['controls'], all_base64))
  131. lines.append('changetype: delete')
  132. if sort_order:
  133. lines = sort_ldif_lines(lines, sort_order)
  134. else:
  135. raise LDAPLDIFError('unable to convert to LDIF-CHANGE-DELETE - missing DN ')
  136. return lines
  137. def modify_request_to_ldif(entry, all_base64, sort_order=None):
  138. lines = []
  139. if 'entry' in entry:
  140. lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))
  141. lines.extend(add_controls(entry['controls'], all_base64))
  142. lines.append('changetype: modify')
  143. if 'changes' in entry:
  144. for change in entry['changes']:
  145. lines.append(['add', 'delete', 'replace', 'increment'][change['operation']] + ': ' + change['attribute']['type'])
  146. for value in change['attribute']['value']:
  147. lines.append(_convert_to_ldif(change['attribute']['type'], value, all_base64))
  148. lines.append('-')
  149. if sort_order:
  150. lines = sort_ldif_lines(lines, sort_order)
  151. return lines
  152. def modify_dn_request_to_ldif(entry, all_base64, sort_order=None):
  153. lines = []
  154. if 'entry' in entry:
  155. lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))
  156. lines.extend(add_controls(entry['controls'], all_base64))
  157. lines.append('changetype: modrdn') if 'newSuperior' in entry and entry['newSuperior'] else lines.append('changetype: moddn')
  158. lines.append(_convert_to_ldif('newrdn', entry['newRdn'], all_base64))
  159. lines.append('deleteoldrdn: ' + ('1' if entry['deleteOldRdn'] else '0'))
  160. if 'newSuperior' in entry and entry['newSuperior']:
  161. lines.append(_convert_to_ldif('newsuperior', entry['newSuperior'], all_base64))
  162. if sort_order:
  163. lines = sort_ldif_lines(lines, sort_order)
  164. else:
  165. raise LDAPLDIFError('unable to convert to LDIF-CHANGE-MODDN - missing DN ')
  166. return lines
  167. def operation_to_ldif(operation_type, entries, all_base64=False, sort_order=None):
  168. if operation_type == 'searchResponse':
  169. lines = search_response_to_ldif(entries, all_base64, sort_order)
  170. elif operation_type == 'addRequest':
  171. lines = add_request_to_ldif(entries, all_base64, sort_order)
  172. elif operation_type == 'delRequest':
  173. lines = delete_request_to_ldif(entries, all_base64, sort_order)
  174. elif operation_type == 'modifyRequest':
  175. lines = modify_request_to_ldif(entries, all_base64, sort_order)
  176. elif operation_type == 'modDNRequest':
  177. lines = modify_dn_request_to_ldif(entries, all_base64, sort_order)
  178. else:
  179. lines = []
  180. ldif_record = []
  181. # check max line length and split as per note 2 of RFC 2849
  182. for line in lines:
  183. if line:
  184. ldif_record.append(line[0:LDIF_LINE_LENGTH])
  185. ldif_record.extend([' ' + line[i: i + LDIF_LINE_LENGTH - 1] for i in range(LDIF_LINE_LENGTH, len(line), LDIF_LINE_LENGTH - 1)] if len(line) > LDIF_LINE_LENGTH else [])
  186. else:
  187. ldif_record.append('')
  188. return ldif_record
  189. def add_ldif_header(ldif_lines):
  190. if ldif_lines:
  191. ldif_lines.insert(0, 'version: 1')
  192. return ldif_lines
  193. def ldif_sort(line, sort_order):
  194. for i, descriptor in enumerate(sort_order):
  195. if line and line.startswith(descriptor):
  196. return i
  197. return len(sort_order) + 1
  198. def decode_persistent_search_control(change):
  199. if 'controls' in change and '2.16.840.1.113730.3.4.7' in change['controls']:
  200. decoded = dict()
  201. decoded_control, unprocessed = decoder.decode(change['controls']['2.16.840.1.113730.3.4.7']['value'], asn1Spec=EntryChangeNotificationControl())
  202. if unprocessed:
  203. raise LDAPExtensionError('unprocessed value in EntryChangeNotificationControl')
  204. if decoded_control['changeType'] == 1: # add
  205. decoded['changeType'] = 'add'
  206. elif decoded_control['changeType'] == 2: # delete
  207. decoded['changeType'] = 'delete'
  208. elif decoded_control['changeType'] == 4: # modify
  209. decoded['changeType'] = 'modify'
  210. elif decoded_control['changeType'] == 8: # modify_dn
  211. decoded['changeType'] = 'modify dn'
  212. else:
  213. raise LDAPExtensionError('unknown Persistent Search changeType ' + str(decoded_control['changeType']))
  214. decoded['changeNumber'] = decoded_control['changeNumber'] if 'changeNumber' in decoded_control and decoded_control['changeNumber'] is not None and decoded_control['changeNumber'].hasValue() else None
  215. decoded['previousDN'] = decoded_control['previousDN'] if 'previousDN' in decoded_control and decoded_control['previousDN'] is not None and decoded_control['previousDN'].hasValue() else None
  216. return decoded
  217. return None
  218. def persistent_search_response_to_ldif(change):
  219. ldif_lines = ['# ' + datetime.now().isoformat()]
  220. control = decode_persistent_search_control(change)
  221. if control:
  222. if control['changeNumber']:
  223. ldif_lines.append('# change number: ' + str(control['changeNumber']))
  224. ldif_lines.append(control['changeType'])
  225. if control['previousDN']:
  226. ldif_lines.append('# previous dn: ' + str(control['previousDN']))
  227. ldif_lines += operation_to_ldif('searchResponse', [change])
  228. return ldif_lines[:-1] # removes "total number of entries"