PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/extra/safe2bin/safe2bin.py

https://github.com/filippocld/sqlmap
Python | 120 lines | 114 code | 1 blank | 5 comment | 0 complexity | 6ac48a437824451bf6ab3a194846ba6b MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause
  1. #!/usr/bin/env python
  2. """
  3. safe2bin.py - Simple safe(hex) to binary format converter
  4. Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
  5. See the file 'doc/COPYING' for copying permission
  6. """
  7. import binascii
  8. import re
  9. import string
  10. import os
  11. import sys
  12. from optparse import OptionError
  13. from optparse import OptionParser
  14. # Regex used for recognition of hex encoded characters
  15. HEX_ENCODED_CHAR_REGEX = r"(?P<result>\\x[0-9A-Fa-f]{2})"
  16. # Raw chars that will be safe encoded to their slash (\) representations (e.g. newline to \n)
  17. SAFE_ENCODE_SLASH_REPLACEMENTS = "\t\n\r\x0b\x0c"
  18. # Characters that don't need to be safe encoded
  19. SAFE_CHARS = "".join(filter(lambda x: x not in SAFE_ENCODE_SLASH_REPLACEMENTS, string.printable.replace('\\', '')))
  20. # String used for temporary marking of slash characters
  21. SLASH_MARKER = "__SLASH__"
  22. def safecharencode(value):
  23. """
  24. Returns safe representation of a given basestring value
  25. >>> safecharencode(u'test123')
  26. u'test123'
  27. >>> safecharencode(u'test\x01\x02\xff')
  28. u'test\\01\\02\\03\\ff'
  29. """
  30. retVal = value
  31. if isinstance(value, basestring):
  32. if any(_ not in SAFE_CHARS for _ in value):
  33. retVal = re.sub(r'(?i)(?!\\x[0-9A-F]{2})\\', SLASH_MARKER, value)
  34. for char in SAFE_ENCODE_SLASH_REPLACEMENTS:
  35. retVal = retVal.replace(char, repr(char).strip('\''))
  36. retVal = retVal.replace(SLASH_MARKER, '\\\\')
  37. retVal = reduce(lambda x, y: x + (y if (y in string.printable or ord(y) > 255) else '\\x%02x' % ord(y)), retVal, unicode())
  38. elif isinstance(value, list):
  39. for i in xrange(len(value)):
  40. retVal[i] = safecharencode(value[i])
  41. return retVal
  42. def safechardecode(value):
  43. """
  44. Reverse function to safecharencode
  45. """
  46. retVal = value
  47. if isinstance(value, basestring):
  48. regex = re.compile(HEX_ENCODED_CHAR_REGEX)
  49. while True:
  50. match = regex.search(retVal)
  51. if match:
  52. retVal = retVal.replace(match.group("result"), unichr(ord(binascii.unhexlify(match.group("result").lstrip('\\x')))))
  53. else:
  54. break
  55. retVal = retVal.replace('\\\\', SLASH_MARKER)
  56. for char in SAFE_ENCODE_SLASH_REPLACEMENTS[::-1]:
  57. retVal = retVal.replace(repr(char).strip('\''), char)
  58. retVal = retVal.replace(SLASH_MARKER, '\\')
  59. elif isinstance(value, (list, tuple)):
  60. for i in xrange(len(value)):
  61. retVal[i] = safechardecode(value[i])
  62. return retVal
  63. def main():
  64. usage = '%s -i <input file> [-o <output file>]' % sys.argv[0]
  65. parser = OptionParser(usage=usage, version='0.1')
  66. try:
  67. parser.add_option('-i', dest='inputFile', help='Input file')
  68. parser.add_option('-o', dest='outputFile', help='Output file')
  69. (args, _) = parser.parse_args()
  70. if not args.inputFile:
  71. parser.error('Missing the input file, -h for help')
  72. except (OptionError, TypeError), e:
  73. parser.error(e)
  74. if not os.path.isfile(args.inputFile):
  75. print 'ERROR: the provided input file \'%s\' is not a regular file' % args.inputFile
  76. sys.exit(1)
  77. f = open(args.inputFile, 'r')
  78. data = f.read()
  79. f.close()
  80. if not args.outputFile:
  81. args.outputFile = args.inputFile + '.bin'
  82. f = open(args.outputFile, 'wb')
  83. f.write(safechardecode(data))
  84. f.close()
  85. if __name__ == '__main__':
  86. main()