utils.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 boring-stuff <boring-stuff@users.noreply.github.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. def _sanitize_char(input_char, extra_allowed_characters):
  20. input_char_ord = ord(input_char)
  21. if (ord('a') <= input_char_ord <= ord('z')) \
  22. or (ord('A') <= input_char_ord <= ord('Z')) \
  23. or (ord('0') <= input_char_ord <= ord('9')) \
  24. or (input_char in ['@', '_', '-', '.']) \
  25. or (input_char in extra_allowed_characters):
  26. result = input_char
  27. else:
  28. result = '_'
  29. return result
  30. # This function needs to be synchronized with qrexec-daemon.c's sanitize_name()
  31. # from the qubes-core-admin-linux repository.
  32. #
  33. # See https://github.com/QubesOS/qubes-core-admin-linux/blob/
  34. # 4f0878ccbf8a95f8264b54d2b6f4dc433ca0793a/qrexec/qrexec-daemon.c#L627-L646
  35. #
  36. def _sanitize_name(input_string, extra_allowed_characters, assert_sanitized):
  37. result = ''.join(_sanitize_char(character, extra_allowed_characters)
  38. for character in input_string)
  39. if assert_sanitized:
  40. assert input_string == result, \
  41. 'Input string was expected to be sanitized, but was not.'
  42. return result
  43. def sanitize_domain_name(input_string, assert_sanitized=False):
  44. return _sanitize_name(input_string, {}, assert_sanitized)
  45. def sanitize_service_name(input_string, assert_sanitized=False):
  46. return _sanitize_name(input_string, {'+'}, assert_sanitized)