Skip to content
This repository was archived by the owner on Sep 12, 2024. It is now read-only.

Commit d3ffe95

Browse files
committed
avoid using dmidecode
I didn't see any reason to depend on root privileges for dmidecode when you can just fetch the data directly as an unprivileged user
1 parent 679aa36 commit d3ffe95

File tree

7 files changed

+38
-77
lines changed

7 files changed

+38
-77
lines changed

Providers/Scripts/2.4x-2.5x/Scripts/nxOMSAutomationWorker.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -347,15 +347,9 @@ def get_optional_metadata():
347347
vm_id = unknown
348348
is_azure_vm = False
349349
try:
350-
proc = subprocess.Popen(["sudo", "-u", AUTOMATION_USER, "python2", OMS_UTIL_FILE_PATH, "--dmidecode"],
351-
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
352-
dmidecode, error = proc.communicate()
353-
if proc.returncode != 0 or not dmidecode:
354-
raise Exception("Unable to invoke omsutil.py --dmidecode: %s" % error)
355-
is_azure_vm = linuxutil.is_azure_vm(dmidecode)
356-
if is_azure_vm:
350+
if linuxutil.is_azure_vm():
357351
asset_tag = linuxutil.get_azure_vm_asset_tag()
358-
vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
352+
vm_id = linuxutil.get_vm_unique_id()
359353
except Exception, e:
360354
log(INFO, "unable to get_optional_metadata: %s" % str(e))
361355

Providers/Scripts/2.6x-2.7x/Scripts/nxOMSAutomationWorker.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -347,15 +347,9 @@ def get_optional_metadata():
347347
vm_id = unknown
348348
is_azure_vm = False
349349
try:
350-
proc = subprocess.Popen(["sudo", "-u", AUTOMATION_USER, "python2", OMS_UTIL_FILE_PATH, "--dmidecode"],
351-
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
352-
dmidecode, error = proc.communicate()
353-
if proc.returncode != 0 or not dmidecode:
354-
raise Exception("Unable to invoke omsutil.py --dmidecode: %s" % error)
355-
is_azure_vm = linuxutil.is_azure_vm(dmidecode)
356-
if is_azure_vm:
350+
if linuxutil.is_azure_vm():
357351
asset_tag = linuxutil.get_azure_vm_asset_tag()
358-
vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
352+
vm_id = linuxutil.get_vm_unique_id()
359353
except Exception, e:
360354
log(INFO, "unable to get_optional_metadata: %s" % str(e))
361355

Providers/Scripts/3.x/Scripts/nxOMSAutomationWorker.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,10 @@ def Set_Marshall(ResourceSettings):
124124
proxy_conf_path = PROXY_CONF_PATH_LEGACY
125125

126126
workspace_id = settings.workspace_id.decode() if isinstance(settings.workspace_id, bytes) else settings.workspace_id
127-
127+
128128
agent_service_zone = settings.azure_dns_agent_svc_zone
129129
azure_dns_agent_svc_zone = agent_service_zone.decode() if isinstance(agent_service_zone, bytes) else agent_service_zone
130-
130+
131131
args = ["python3", REGISTRATION_FILE_PATH, "--register", "-w", workspace_id, "-a", agent_id,
132132
"-c", OMS_CERTIFICATE_PATH, "-k", OMS_CERT_KEY_PATH, "-f", WORKING_DIRECTORY_PATH, "-s",
133133
WORKER_STATE_DIR, "-e", azure_dns_agent_svc_zone, "-p", proxy_conf_path, "-g",
@@ -364,16 +364,9 @@ def get_optional_metadata():
364364
vm_id = unknown
365365
is_azure_vm = False
366366
try:
367-
proc = subprocess.Popen(["sudo", "-u", AUTOMATION_USER, "python3", OMS_UTIL_FILE_PATH, "--dmidecode"],
368-
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
369-
dmidecode, error = proc.communicate()
370-
dmidecode = dmidecode.decode("utf-8")
371-
if proc.returncode != 0 or not dmidecode:
372-
raise Exception("Unable to invoke omsutil.py --dmidecode: %s" % error.decode())
373-
is_azure_vm = linuxutil.is_azure_vm(dmidecode)
374-
if is_azure_vm:
367+
if linuxutil.is_azure_vm():
375368
asset_tag = linuxutil.get_azure_vm_asset_tag()
376-
vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
369+
vm_id = linuxutil.get_vm_unique_id()
377370
except Exception as e:
378371
log(INFO, "unable to get_optional_metadata: %s" % str(e))
379372

@@ -620,7 +613,7 @@ def config_file_to_kv_pair(filename):
620613
def start_worker_manager_process(workspace_id):
621614
"""
622615
Start the worker_manager_process
623-
:param workspace_id:
616+
:param workspace_id:
624617
:return: the pid of the worker manager process
625618
"""
626619
proc = subprocess.Popen(["sudo", "-u", AUTOMATION_USER, "python3", WORKER_MANAGER_START_PATH, OMS_CONF_FILE_PATH,
@@ -843,4 +836,4 @@ def log(level, message):
843836
try:
844837
LG().Log(logging.getLevelName(level), message)
845838
except:
846-
pass
839+
pass

Providers/nxOMSAutomationWorker/automationworker/3.x/scripts/onboarding3.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def generate_hmac(str_to_sign, secret):
9494
secret = secret.encode('utf-8')
9595
cmd = ['echo -n "' + str(message.decode("utf-8")) + '" | openssl dgst -sha256 -binary -hmac "' + str(secret.decode("utf-8")) + '"']
9696
process, signed_message, error = linuxutil.popen_communicate(cmd, shell=True)
97-
97+
9898
error = error.decode() if isinstance(error, bytes) else error
9999
if process.returncode != 0:
100100
raise Exception("Unable to generate signature. " + str(error))
@@ -266,17 +266,15 @@ def register(options):
266266
vm_id = unknown
267267
is_azure_vm = False
268268
try:
269-
dmidecode = invoke_dmidecode()
270-
is_azure_vm = linuxutil.is_azure_vm(dmidecode)
271-
if is_azure_vm:
269+
if linuxutil.is_azure_vm():
272270
asset_tag = linuxutil.get_azure_vm_asset_tag()
273271
else:
274272
asset_tag = False
275-
vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
273+
vm_id = linuxutil.get_vm_unique_id()
276274
except Exception as e:
277275
print (str(e))
278276
pass
279-
277+
280278
# generate payload for registration request
281279
date = datetime.datetime.utcnow().isoformat() + "0-00:00"
282280
payload = {'RunbookWorkerGroup': hybrid_worker_group_name,
@@ -425,4 +423,3 @@ def environment_prerequisite_validation():
425423
nxautomation_group_name = "nxautomation"
426424
if linuxutil.is_existing_group(omiusers_group_name) is False:
427425
raise Exception("Missing group : " + nxautomation_group_name + ".")
428-

Providers/nxOMSAutomationWorker/automationworker/3.x/worker/linuxutil.py

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -90,39 +90,28 @@ def get_azure_vm_asset_tag():
9090
return "7783-7084-3265-9085-8269-3286-77"
9191

9292

93-
def is_azure_vm(dmidecode_output):
94-
"""Detects azure vm from dmidecode output.
95-
96-
Note : is an asset tag "7783-7084-3265-9085-8269-3286-77" is present then this is an azure vm.
97-
98-
Returns:
99-
bool, true if the host is an azure vm.
100-
"""
101-
#print("linux util dmidecode : "+ str(dmidecode_output))
102-
asset_tags = re.findall(get_azure_vm_asset_tag(), dmidecode_output)
103-
104-
for tag in asset_tags:
105-
if get_azure_vm_asset_tag() in tag:
106-
return True
107-
108-
return False
93+
def is_azure_vm():
94+
try:
95+
with open('/sys/devices/virtual/dmi/id/chassis_asset_tag', 'r') as file:
96+
return file.read().strip() == get_azure_vm_asset_tag()
97+
except (FileNotFoundError, PermissionError):
98+
print("File not found or permission denied")
99+
return False
109100

110101

111-
def get_vm_unique_id_from_dmidecode(byteorder, dmidecode_output):
102+
def get_vm_unique_id():
112103
"""Extract the host UUID from dmidecode output.
113104
114105
Returns:
115106
string, the host UUID.
116107
"""
117-
uuid_prefix = "UUID: "
118-
uuids = re.findall(uuid_prefix + "[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}",
119-
dmidecode_output.upper())
120-
if len(uuids) < 1:
108+
byteorder = sys.byteorder
109+
try:
110+
with open('/sys/devices/virtual/dmi/id/product_uuid', 'r') as file:
111+
uuid = file.read().strip().lower()
112+
except (FileNotFoundError, PermissionError):
121113
raise Exception("No host UUID found.")
122114

123-
# if multiple UUIDs are found take the first one
124-
uuid = uuids[0].split(uuid_prefix)[1].strip()
125-
126115
# azure uuids are big endian
127116
if byteorder == "big":
128117
return uuid
@@ -139,8 +128,8 @@ def get_vm_unique_id_from_dmidecode(byteorder, dmidecode_output):
139128
def convert_to_big_endian(little_endian_value):
140129
"""Converts the little endian representation of the value into a big endian representation of the value"""
141130
"""
142-
Little and big endian are two ways of storing multibyte data-types ( int, float, etc).
143-
In little endian machines, last byte of binary representation of the multibyte data-type is stored first.
131+
Little and big endian are two ways of storing multibyte data-types ( int, float, etc).
132+
In little endian machines, last byte of binary representation of the multibyte data-type is stored first.
144133
On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first.
145134
"""
146135
codecs_decoded = codecs.decode(little_endian_value, "hex")

Providers/nxOMSAutomationWorker/automationworker/scripts/onboarding2.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def register(options):
246246
if os.path.isdir(DIY_STATE_PATH) is False:
247247
try:
248248
os.makedirs(DIY_STATE_PATH)
249-
except Exception, ex:
249+
except Exception, ex:
250250
print("Registration unsuccessful.")
251251
print("Cannot create directory for certs/conf. Because of the following exception : " + str(ex))
252252
return
@@ -259,13 +259,11 @@ def register(options):
259259
vm_id = unknown
260260
is_azure_vm = False
261261
try:
262-
dmidecode = invoke_dmidecode()
263-
is_azure_vm = linuxutil.is_azure_vm(dmidecode)
264-
if is_azure_vm:
262+
if linuxutil.is_azure_vm():
265263
asset_tag = linuxutil.get_azure_vm_asset_tag()
266264
else:
267265
asset_tag = False
268-
vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
266+
vm_id = linuxutil.get_vm_unique_id()
269267
except Exception, e:
270268
print str(e)
271269
pass
@@ -421,5 +419,3 @@ def environment_prerequisite_validation():
421419
nxautomation_group_name = "nxautomation"
422420
if linuxutil.is_existing_group(omiusers_group_name) is False:
423421
raise Exception("Missing group : " + nxautomation_group_name + ".")
424-
425-

Providers/nxOMSAutomationWorker/automationworker/worker/linuxutil.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -104,21 +104,19 @@ def is_azure_vm(dmidecode_output):
104104
return False
105105

106106

107-
def get_vm_unique_id_from_dmidecode(byteorder, dmidecode_output):
107+
def get_vm_unique_id():
108108
"""Extract the host UUID from dmidecode output.
109109
110110
Returns:
111111
string, the host UUID.
112112
"""
113-
uuid_prefix = "UUID: "
114-
uuids = re.findall(uuid_prefix + "[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}",
115-
dmidecode_output.upper())
116-
if len(uuids) < 1:
113+
byteorder = sys.byteorder
114+
try:
115+
with open('/sys/devices/virtual/dmi/id/product_uuid', 'r') as file:
116+
uuid = file.read().strip().lower()
117+
except (FileNotFoundError, PermissionError):
117118
raise Exception("No host UUID found.")
118119

119-
# if multiple UUIDs are found take the first one
120-
uuid = uuids[0].split(uuid_prefix)[1].strip()
121-
122120
# azure uuids are big endian
123121
if byteorder == "big":
124122
return uuid

0 commit comments

Comments
 (0)