jcomeau_ictx

CFE nvram modification tool that doesn't change order

Jul 18th, 2013
152
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2. 'extract and write nvram variables to CFE image'
  3. import sys
  4. NVRAM_OFFSET = 4096
  5. NVRAM_SIZE = 4096
  6. NVRAM_HEADER_SIZE = 20
  7. NVRAM_DATA_OFFSET = NVRAM_OFFSET + NVRAM_HEADER_SIZE
  8. def extract(filename):
  9. data = read(filename)
  10. nvram = data[NVRAM_OFFSET:NVRAM_OFFSET + NVRAM_SIZE]
  11. return filter(None, nvram[NVRAM_HEADER_SIZE:].split('\0'))
  12. def modify(cfefile, changesfile):
  13. values = [line.split('=', 1) for line in extract(cfefile)]
  14. valuesdict = dict(values)
  15. changes = dict([line.split('=', 1) for line in readlines(changesfile)])
  16. valuesdict.update(changes)
  17. for index in range(len(values)):
  18. key, value = values[index]
  19. if valuesdict[key] != value:
  20. print >>sys.stderr, 'changing value of "%s" from "%s" to "%s"' % (
  21. key, value, valuesdict[key])
  22. values[index][1] = valuesdict[key]
  23. del valuesdict[key]
  24. if valuesdict:
  25. print >>sys.stderr, 'failed! remaining data: %s' % valuesdict
  26. sys.exit(1)
  27. nvram_data = '\0'.join(['='.join([k, v]) for [k, v] in values])
  28. data = read(cfefile)
  29. padding = '\0' * (NVRAM_SIZE - NVRAM_HEADER_SIZE)
  30. data = data[:NVRAM_DATA_OFFSET] + \
  31. (nvram_data + padding)[:len(padding)] + \
  32. data[NVRAM_OFFSET + NVRAM_SIZE:]
  33. write(cfefile, data)
  34. def read(filename):
  35. input = open(filename)
  36. data = input.read()
  37. input.close()
  38. return data
  39. def readlines(filename):
  40. input = open(filename)
  41. data = input.readlines()
  42. input.close()
  43. return map(str.rstrip, data)
  44. def write(filename, data):
  45. output = open(filename, 'w')
  46. output.write(data)
  47. output.close()
  48. if __name__ == '__main__':
  49. if len(sys.argv) > 1:
  50. if sys.argv[1] == 'extract':
  51. for line in extract(sys.argv[2]):
  52. print line
  53. elif sys.argv[1] == 'modify':
  54. modify(*sys.argv[2:])
  55. else:
  56. print >>sys.stderr, 'only "extract" or "modify" accepted'
  57. else:
  58. print >> sys.stderr, \
  59. 'usage: %s extract binfile | modify binfile changesfile' % sys.argv[0]
RAW Paste Data