-
Notifications
You must be signed in to change notification settings - Fork 0
/
amufi_flash.py
executable file
·268 lines (233 loc) · 9.14 KB
/
amufi_flash.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""amufi_flash.py a script that flashes a new subcultron image onto sd cards, with extras."""
__author__ = "Daniel E. Moser"
__date__ = "09.04.2018"
__email__ = "[email protected]"
import argparse
import configparser
import fileinput
import os
import re
import subprocess
import sys
import time
import requests
dir_path = os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(dir_path, 'config.ini')
dev_null = open(os.devnull, 'w')
def initArgParse():
"""Parse cmd-line arguments and return the parser
"""
# cmd line argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('dev', action='store',
help='device location of sd card')
parser.add_argument('-p', '--partition', action='store_true',
help='partition sd-card to "system" and "data" partition')
parser.add_argument('-f', '--format', action='store_true',
help='format sd-card partitions to ext4')
parser.add_argument('-c', '--copy_image', action='store_true',
help='copy image to "system" parition')
parser.add_argument('-n', '--number', action='store',
help='specify the agent-number the image should be configured for')
parser.add_argument('-i', '--image', action='store',
help="specify imagefile to be copied, default can be configured in 'config.ini'")
parser.add_argument('-g', '--garbage', action='store_true',
help='add some prime garbage to the output')
parser.add_argument('-s', '--size', action='store_true',
help='get size in bytes of device')
parser.add_argument('-cr', '--cardreader', action='store_true',
help='use cardreader instead of usb (changes partition prefix)')
parser.add_argument('--fish', action='store_true',
help='the target agent is an aFish')
return parser.parse_args()
def checks(args, conf):
"""Check for signs of trying to overwrite the wrong device. Several additional checks to mitigate risks of overwriting data unintentionally or using nonexistent image.
"""
dev = args.dev
# device exists
if not os.path.exists(dev):
print("Error: device '{}' does not exist.".format(dev))
sys.exit()
print('* Device path OK')
# check for signs that it is the wrong device by comparing to the size of bytes specified in conf.
fd = os.open(dev, os.O_RDONLY)
try:
size = int(os.lseek(fd, 0, os.SEEK_END))
finally:
os.close(fd)
if size != int(conf['DEFAULT']['SDSize']):
print("WARNING: Device '{}' has a different size than specified in the conf file!".format(dev))
print("WARNING: Specified: {}".format(conf['DEFAULT']['SDSize']))
print("WARNING: Detected : {}".format(size))
print("continue? [N]/y")
k = input()
if k != 'y':
sys.exit()
print('* Device size OK')
# if copying image: image exists?
try:
# image from cmd-line arg
if args.image:
img = os.path.join(dir_path, args.image)
if not os.path.exists(img):
print("Error: image '{}' does not exist.".format(img))
sys.exit()
# image specified in 'config/ini'
img = os.path.join(dir_path, conf['DEFAULT']['Image'])
if not os.path.exists(img):
print("Error: image '{}' does not exist.".format(img))
sys.exit()
except NameError:
pass
print('* Image path OK')
print("*** Basic checks OK. \n")
def copy(args, conf):
""" Flash the system partition of the sd with the image specified in 'config.ini' or in the 'image' cmd-line argument. Test if flashing was successful.
"""
img = os.path.join(dir_path, conf['DEFAULT']['Image'])
dev = args.dev
print("Flashing device {} with image {}.".format(dev, img))
# create flashing command
cmd = ['dd', str('if={}'.format(img)), str(
'of={}'.format(dev)), str('bs=4M')]
# execute command
try:
subprocess.call(cmd, stdout=dev_null)
except subprocess.CalledProcessError:
print("subprocess error while calling '{}'.".format(" ".join(cmd)))
sys.exit()
print("Flashing done.\n")
def partition(args, conf):
"""Construct the fdisk partition command and call the partition bash script to execute the command with the given options
"""
dev = args.dev
print("* Partitioning the unused space on device {} for a data partition.".format(dev))
# create partition command
partition_script_path = os.path.join(dir_path, 'partition.sh')
cmd = [partition_script_path, str(args.dev)]
# execute partition command
try:
subprocess.call(cmd, stdout=dev_null, stderr=dev_null)
except subprocess.CalledProcessError:
print("subprocess error while calling '{}'.".format(" ".join(cmd)))
sys.exit()
# the 'Re-reading the partition table failed.: Device or resource busy' warning is suppressed here,
# since partprobe is called to update partitiontable in kernel here
try:
cmd = ['partprobe' , dev]
subprocess.call(cmd, stdout=dev_null)
except subprocess.CalledProcessError:
print("subprocess error while calling '{}'.".format(cmd))
sys.exit()
print("*** Partitioning done.\n")
def format(args, conf):
"""Format partitions3 to ext4
"""
dev = args.dev
# determine correct partition prefix
if args.cardreader:
part = conf['CARDREADER']['DataPart']
else:
part = conf['DEFAULT']['DataPart']
print("* Formatting data partition {}{} to ext4.".format(dev,part))
# create format partition commands
cmd = ['mkfs.ext4', '-L', 'data', '-F', dev+part]
try:
subprocess.call(cmd, stdout=dev_null)
except subprocess.CalledProcessError:
print("subprocess error while calling '{}'.".format(" ".join(cmd)))
sys.exit()
print("*** Formatting done.\n")
def number(args, conf):
"""Configure the hostname, and ip settings of the target device.
"""
dev = args.dev
# determine correct partition prefix
if args.cardreader:
part = conf['CARDREADER']['SysPart']
else:
part = conf['DEFAULT']['SysPart']
# mount flashed image to 'mnt'
mnt_folder = conf['DEFAULT']['Mountpoint']
if not os.path.exists(mnt_folder):
os.system('mkdir {}'.format(mnt_folder))
mount_return_code = os.WEXITSTATUS(os.system("mount {}{} mnt".format(dev, part)))
if mount_return_code != 32 and mount_return_code != 0: # 32 means already mounted
print("Error: could not mount {}{}".format(dev, part))
sys.exit()
if args.fish:
NEW_HOSTNAME = "aFish"+args.number
else:
NEW_HOSTNAME = "aMussel"+args.number
# hostname file
print("* Setting hostname in file "+conf["PATHS"]["HostNamePath"]+" to "+NEW_HOSTNAME)
f = open(conf["PATHS"]["HostNamePath"], 'w')
f.write(NEW_HOSTNAME+ os.linesep)
f.close()
# hosts file
print("* Setting hostname in file "+conf["PATHS"]["HostsPath"]+" to "+NEW_HOSTNAME)
r = re.compile(r"(127\.0\.1\.1).*$")
with fileinput.FileInput(conf["PATHS"]["HostsPath"], inplace=True, backup='.bak') as file:
for line in file:
print(r.sub(r"\1 %s" % NEW_HOSTNAME, line), end='')
# interfaces file
if args.fish:
ip_num = '2'+str(args.number).zfill(2)
else:
ip_num = args.number
print("* Setting ip in file "+conf["PATHS"]["InterfacesPath"]+" to end with "+ip_num)
r = re.compile(r"(address).*$")
with fileinput.FileInput(conf["PATHS"]["InterfacesPath"], inplace=True, backup='.bak') as file:
for line in file:
print(r.sub(r"\1 %s" % "10.0.200."+ip_num, line), end='')
# unmount and remove temp mnt folder
os.system('umount {}'.format(mnt_folder))
print("*** Numbering done.")
def garbage():
"""garbage
"""
try:
print("\n!@#$%^@##$%^&*#$%^&*()(**%#$#@%&*\n")
r = requests.get('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
print(r.json()['message'])
print(" - Donald J. Trump")
except Exception:
print("No connection to good vibes at the moment.")
def main():
"""Main function
"""
# configuragtion/argument parsing
conf = configparser.ConfigParser()
conf.read(conf_file)
args = initArgParse()
# program start
print("###############")
print("# aMuFi_Flash #\n")
# check device size only:
if args.size:
fd = os.open(args.dev, os.O_RDONLY)
try:
size = int(os.lseek(fd, 0, os.SEEK_END))
print(size)
finally:
os.close(fd)
print("Device {} size: {}".format(args.dev, size))
sys.exit()
# copy:
if args.copy_image:
copy(args, conf)
# partition:
if args.partition:
partition(args, conf)
# format:
if args.format:
format(args, conf)
# # number configs
if args.number:
number(args, conf)
# good vibes
if args.garbage:
garbage()
if __name__ == "__main__":
main()