utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program 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
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, see <http://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. else:
  43. return result
  44. def sanitize_domain_name(input_string, assert_sanitized=False):
  45. return _sanitize_name(input_string, {}, assert_sanitized)
  46. def sanitize_service_name(input_string, assert_sanitized=False):
  47. return _sanitize_name(input_string, {'+'}, assert_sanitized)