Debian Codegraph @

test/integration/targets/ansible-galaxy-collection/files/build_bad_tar.py

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2
3 # Copyright: (c) 2020, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import hashlib
9 import io
10 import json
11 import os
12 import sys
13 import tarfile
14 from ansible.module_utils.common.file import S_IRWXU_RXG_RXO
15
16 manifest = {
17 'collection_info': {
18 'namespace': 'suspicious',
19 'name': 'test',
20 'version': '1.0.0',
21 'dependencies': {},
22 },
23 'file_manifest_file': {
24 'name': 'FILES.json',
25 'ftype': 'file',
26 'chksum_type': 'sha256',
27 'chksum_sha256': None,
28 'format': 1
29 },
30 'format': 1,
31 }
32
33 files = {
34 'files': [
35 {
36 'name': '.',
37 'ftype': 'dir',
38 'chksum_type': None,
39 'chksum_sha256': None,
40 'format': 1,
41 },
42 ],
43 'format': 1,
44 }
45
46
47 def add_file(tar_file, filename, b_content, update_files=True):
48 tar_info = tarfile.TarInfo(filename)
49 tar_info.size = len(b_content)
50 tar_info.mode = S_IRWXU_RXG_RXO
51 tar_file.addfile(tarinfo=tar_info, fileobj=io.BytesIO(b_content))
52
53 if update_files:
54 sha256 = hashlib.sha256()
55 sha256.update(b_content)
56
57 files['files'].append({
58 'name': filename,
59 'ftype': 'file',
60 'chksum_type': 'sha256',
61 'chksum_sha256': sha256.hexdigest(),
62 'format': 1
63 })
64
65
66 collection_tar = os.path.join(sys.argv[1], 'suspicious-test-1.0.0.tar.gz')
67 with tarfile.open(collection_tar, mode='w:gz') as tar_file:
68 add_file(tar_file, '../../outside.sh', b"#!/usr/bin/env bash\necho \"you got pwned\"")
69
70 b_files = json.dumps(files).encode('utf-8')
71 b_files_hash = hashlib.sha256()
72 b_files_hash.update(b_files)
73 manifest['file_manifest_file']['chksum_sha256'] = b_files_hash.hexdigest()
74 add_file(tar_file, 'FILES.json', b_files)
75 add_file(tar_file, 'MANIFEST.json', json.dumps(manifest).encode('utf-8'))
76
77 b_manifest = json.dumps(manifest).encode('utf-8')
78
79 for name, b in [('MANIFEST.json', b_manifest), ('FILES.json', b_files)]:
80 b_io = io.BytesIO(b)
81 tar_info = tarfile.TarInfo(name)
82 tar_info.size = len(b)
83 tar_info.mode = 0o0644
84 tar_file.addfile(tarinfo=tar_info, fileobj=b_io)