mal_s3_upload.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/python
  2. # Greg Martin
  3. # Threat Stream Inc. Copyright (c) 2013. All rights reserved.
  4. # www.threatstream.com
  5. #
  6. import sys, os
  7. import boto
  8. from boto.s3.key import Key
  9. import hashlib, magic, gzip
  10. unique_string = 'ADD_YOUR_UNIQUE_STRING_HERE'
  11. if len(sys.argv) > 1:
  12. arg = sys.argv[1]
  13. else:
  14. print('Usage: ./malware_s3_upload <filename>\n')
  15. sys.exit()
  16. # get magic value
  17. def get_magic(file):
  18. fm = magic.from_file(file)
  19. return fm
  20. # Get hash digests
  21. def get_hashes(file):
  22. md5 = hashlib.md5()
  23. sha256 = hashlib.sha256()
  24. with open(file, 'rb') as f:
  25. for chunk in iter(lambda: f.read(8192), b''):
  26. md5.update(chunk)
  27. sha256.update(chunk)
  28. hashes = {'md5': md5.hexdigest(), 'sha256': sha256.hexdigest(), }
  29. return hashes
  30. def upload_s3(filename, md5, sha256, filetype):
  31. try:
  32. # Connect and upload to S3 bucket
  33. conn = boto.connect_s3()
  34. bucket = conn.create_bucket(unique_string.lower() + '_malware')
  35. k = Key(bucket)
  36. # Set unique_id
  37. k.key = sha256
  38. k.set_metadata('md5_hash', md5)
  39. k.set_metadata('file_type', filetype)
  40. k.set_contents_from_filename(filename)
  41. return 'success'
  42. except:
  43. return 'upload to s3 failed, make sure your aws keys are set in ~/.boto'
  44. def gzip_file(filename):
  45. f_in = open(filename, 'rb')
  46. f_out = gzip.open(filename + '.gz', 'wb')
  47. f_out.writelines(f_in)
  48. f_out.close()
  49. f_in.close()
  50. def main():
  51. # main code
  52. if len(sys.argv) > 1:
  53. arg = sys.argv[1]
  54. else:
  55. print('Usage: ./malware_s3_upload <filename>\n')
  56. sys.exit()
  57. # get file type and hashes before compression
  58. file_type = get_magic(arg)
  59. md5_hash = get_hashes(arg)['md5']
  60. sha256_hash = get_hashes(arg)['sha256']
  61. # gzip file
  62. gzip_file(arg)
  63. # upload to s3
  64. print('Uploading gzipped ' + arg + ' to s3:\n')
  65. print(upload_s3(arg + '.gz', md5_hash, sha256_hash, file_type))
  66. # delete local gzipped file
  67. os.unlink(arg + '.gz')
  68. if __name__ == "__main__":
  69. main()