Skip to content

Commit

Permalink
[device/juniper] Mitigation for security vulnerability (#11838)
Browse files Browse the repository at this point in the history
Signed-off-by: maipbui maibui@microsoft.com
Dependency: [https://github.com/sonic-net/sonic-buildimage/pull/12065](https://github.com/sonic-net/sonic-buildimage/pull/12065)
#### Why I did it
`commands` module is not secure
command injection in `getstatusoutput` being used without a static string
#### How I did it
Eliminate `commands` module, use `subprocess` module only
Convert Python 2 to Python 3
  • Loading branch information
maipbui authored and StormLiangMS committed Dec 10, 2022
1 parent 9b7a04d commit 4963c1c
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 136 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,9 @@

import binascii
import os
import sys
import subprocess
from sonic_eeprom import eeprom_tlvinfo

if sys.version_info[0] < 3:
import commands
else:
import subprocess as commands
from sonic_py_common.general import getstatusoutput_noshell


def fantype_detect():
Expand All @@ -56,9 +52,7 @@ def fantype_detect():
for filename in os.listdir(refpgaTMC_path):
if filename.endswith('_type'):
fantype_path = os.path.join(refpgaTMC_path, filename)
cat_string = "cat "
fantype_string = cat_string + fantype_path
status, fan_type = commands.getstatusoutput(fantype_string)
status, fan_type = getstatusoutput_noshell(['cat', fantype_path])
if ((fan_type == AFO) or (fan_type == AFI)):
return fan_type
else:
Expand Down Expand Up @@ -176,17 +170,21 @@ def main():
eeprom_file.write("Main board eeprom (0x57)\r\n")
eeprom_file.write("===============================\r\n")

MainEepromCreate = 'sudo echo 24c02 0x57 > /sys/bus/i2c/devices/i2c-0/new_device'
MainEepromCreate = '24c02 0x57'
out_file = '/sys/bus/i2c/devices/i2c-0/new_device'
# Write the contents of Main Board EEPROM to file
try:
os.system(MainEepromCreate)
with open(out_file, 'w') as file:
file.write(MainEepromCreate)
except OSError:
print('Error: Execution of "%s" failed', MainEepromCreate)
return False

MainEepromFileCmd = 'cat /sys/bus/i2c/devices/i2c-0/0-0057/eeprom > /etc/init.d/MainEeprom_qfx5200_ascii'
MainEepromFileCmd = ['cat', '/sys/bus/i2c/devices/i2c-0/0-0057/eeprom']
out_file = '/etc/init.d/MainEeprom_qfx5200_ascii'
try:
os.system(MainEepromFileCmd)
with open(out_file, 'w') as file:
subprocess.call(MainEepromFileCmd, universal_newlines=True, stdout=file)
except OSError:
print('Error: Execution of "%s" failed', MainEepromFileCmd)
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
# components is subject to the terms and conditions of the respective license
# as noted in the Third-Party source code file.

import os
import binascii
import subprocess
from sonic_eeprom import eeprom_tlvinfo


Expand Down Expand Up @@ -81,10 +81,12 @@ def main():
eeprom_file.write("Vendor Name=%s\r\n" % eeprom_qfx5210.vendor_name_str())
eeprom_file.write("Manufacture Name=%s\r\n" % eeprom_qfx5210.manufacture_name_str())

CPUeepromFileCmd = 'cat /sys/devices/pci0000:00/0000:00:1f.3/i2c-0/0-0056/eeprom > /etc/init.d/eeprom_qfx5210_ascii'
CPUeepromFileCmd = ['cat', '/sys/devices/pci0000:00/0000:00:1f.3/i2c-0/0-0056/eeprom']
# Write the contents of CPU EEPROM to file
out_file = '/etc/init.d/eeprom_qfx5210_ascii'
try:
os.system(CPUeepromFileCmd)
with open(out_file, 'w') as file:
subprocess.call(CPUeepromFileCmd, universal_newlines=True, stdout=file)
except OSError:
print('Error: Execution of "%s" failed', CPUeepromFileCmd)
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@

try:
import os
import commands
import subprocess
import logging
import logging.config
import logging.handlers
import time
import glob
import re
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e:
raise ImportError('%s - required module not found' % str(e))

Expand Down Expand Up @@ -172,24 +172,27 @@ def get_fan_dutycycle(self):
pwm_value = 0
pwm_value1 = 0
device_path = self._pwm_input_path_mapping[x]
cmd = ("sudo cat %s" %(device_path))
status, pwm_value = commands.getstatusoutput(cmd)
cmd = ["sudo", "cat", device_path]
status, pwm_value = getstatusoutput_noshell(cmd)
pwm_value1 = int(pwm_value)
time.sleep(0.25)
if int(pwm_value1) > 0:
ret_value = fan_speed.get(int(pwm_value))
break

return int(ret_value)

def write_file(self, text, file):
with open(file, 'w') as f:
f.write(text + '\n')

def set_fan_dutycycle(self, val):
fan_speed = {35: 86, 55: 139, 75: 192, 90: 230,100: 255}
for x in range(self.PWMINPUT_NUM):
device_path = self._pwm_input_path_mapping[x]
pwm_value = fan_speed.get(val)
pwm_value1 = str(pwm_value)
cmd = ("sudo echo %s > %s" %(pwm_value1,device_path))
os.system(cmd)
self.write_file(pwm_value1,device_path)
time.sleep(0.25)
logging.debug('Setting PWM value: %s to all fans', pwm_value1)
return True
Expand All @@ -198,8 +201,8 @@ def get_check_fan_dutycycle(self):
pwm_str = ''
for x in range(self.PWMINPUT_NUM):
device_path = self._pwm_input_path_mapping[x]
cmd = ("sudo cat %s" %(device_path))
status, pwm_value = commands.getstatusoutput(cmd)
cmd = ["sudo", "cat", device_path]
status, pwm_value = getstatusoutput_noshell(cmd)
pwm_str += pwm_value
if (x != self.PWMINPUT_NUM -1):
pwm_str += ', '
Expand Down Expand Up @@ -495,8 +498,8 @@ def getSensorTemp(self):
else:
proc = subprocess.Popen("bcmcmd \"show temp\" | grep \"maximum peak temperature\" | awk '{ print $5 }' > /var/log/asic_value 2>&1 & ",shell=True)
time.sleep(2)
cmd = "kill -9 %s"%(proc.pid)
commands.getstatusoutput(cmd)
cmd = ["kill", "-9", proc.pid]
getstatusoutput_noshell(cmd)

if os.stat("/var/log/asic_value").st_size == 0:
value = PrevASICValue
Expand Down Expand Up @@ -568,7 +571,7 @@ def getSensorTemp(self):
or SensorFlag[8][11] or SensorFlag[9][11] or SensorFlag[10][11] or SensorFlag[11][11]):

logging.debug('Fire Threshold reached: System is going to shutdown now')
os.system("echo 'CRITICAL: Fire Threshold reached: System is going to shutdown now' > /dev/console")
self.write_file('CRITICAL: Fire Threshold reached: System is going to shutdown now', "/dev/console")


logging.debug('Executing poweroff command')
Expand All @@ -583,8 +586,8 @@ def getSensorTemp(self):

monitorlog_file.close()

cmd = "poweroff"
os.system(cmd)
cmd = ["poweroff"]
subprocess.call(cmd)

# CHECK IF ANY TEMPERATURE SENSORS is running at RED warning , IF YES, SET THE ALARM LED TO 'RED'
elif (SensorFlag[0][10] or SensorFlag[1][10] or SensorFlag[2][10] or SensorFlag[3][10] or SensorFlag[4][10] or SensorFlag[5][10] or SensorFlag[6][10] or SensorFlag[7][10]
Expand Down Expand Up @@ -878,8 +881,7 @@ def set_Default_fan_dutycycle(self, val):
pwm_value = fan_speed.get(val)
pwm_value1 = str(pwm_value)
time.sleep(0.25)
cmd = ("sudo echo %s > %s" %(pwm_value1,device_path))
os.system(cmd)
self.write_file(pwm_value1, device_path)

logging.debug('Setting Default PWM value: 86 to all fans')
return True
Expand All @@ -888,8 +890,8 @@ def get_Initial_fan_dutycycle(self):
pwm_str = ''
for x in range(self.PWMINPUT_NUM):
device_path = self._pwm_input_path_mapping[x]
cmd = ("sudo cat %s" %(device_path))
status, pwm_value = commands.getstatusoutput(cmd)
cmd = ["sudo", "cat", device_path]
status, pwm_value = getstatusoutput_noshell(cmd)
pwm_str += pwm_value
if (x != self.PWMINPUT_NUM -1):
pwm_str += ', '
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@
import sys
import logging
import time
import subprocess
from sonic_py_common.general import getstatusoutput_noshell

PROJECT_NAME = 'QFX5200-32C'
verbose = False
DEBUG = False
FORCE = 0

if DEBUG == True:
print sys.argv[0]
print 'ARGV :', sys.argv[1:]
print(sys.argv[0])
print('ARGV :', sys.argv[1:])

i2c_prefix = '/sys/bus/i2c/devices/'

Expand Down Expand Up @@ -70,7 +72,7 @@

def my_log(txt):
if DEBUG == True:
print txt
print(txt)
return

def log_os_system(cmd, show):
Expand All @@ -83,6 +85,10 @@ def log_os_system(cmd, show):
if show:
print('Failed :'+cmd)
return status, output

def write_file(text, file):
with open(file, 'w') as f:
f.write(text + '\n')

def driver_install():
global FORCE
Expand All @@ -106,7 +112,7 @@ def device_install():
for i in range(0,len(mknod)):
status, output = log_os_system(mknod[i], 1)
if status:
print output
print(output)
if FORCE == 0:
return status

Expand All @@ -123,7 +129,7 @@ def do_install():
if FORCE == 0:
return status
else:
print PROJECT_NAME.upper()+" devices detected...."
print(PROJECT_NAME.upper()+" devices detected....")
return

def main():
Expand All @@ -139,70 +145,71 @@ def main():


# Enabling REFPGA
EnableREFFGACmd = 'busybox devmem 0xFED50011 8 0x53'
EnableREFFGACmd = ['busybox', 'devmem', '0xFED50011', '8', '0x53']
try:
os.system(EnableREFFGACmd)
subprocess.call(EnableREFFGACmd)
except OSError:
print 'Error: Execution of "%s" failed', EnableREFFGACmd
print('Error: Execution of "%s" failed', EnableREFFGACmd)
return False

time.sleep(2)

# Create CPU Board EEPROM device
CreateEEPROMdeviceCmd = 'sudo echo 24c02 0x51 > /sys/bus/i2c/devices/i2c-0/new_device'
CreateEEPROMdeviceCmd = '24c02 0x51'
file = '/sys/bus/i2c/devices/i2c-0/new_device'
try:
os.system(CreateEEPROMdeviceCmd)
write_file(CreateEEPROMdeviceCmd, file)
except OSError:
print 'Error: Execution of "%s" failed', CreateEEPROMdeviceCmd
print('Error: Execution of "%s" failed', CreateEEPROMdeviceCmd)
return False

time.sleep(1)

#Retrieve the Base MAC Address from EEPROM
status, macAddress = commands.getstatusoutput("decode-syseeprom -m 0x24")
status, macAddress = getstatusoutput_noshell(["decode-syseeprom", "-m", "0x24"])
if status:
print 'Error: Could not retrieve BASE MAC Address from EEPROM'
print('Error: Could not retrieve BASE MAC Address from EEPROM')
return False

#Make eth0 interface down
status, eth0Down = commands.getstatusoutput("ifconfig eth0 down")
status, eth0Down = getstatusoutput_noshell(["ifconfig", "eth0", "down"])
if status:
print 'Error: Could not make eth0 interface down'
print('Error: Could not make eth0 interface down')
return False

#Assign BASE MAC ADDRESS retieved from CPU board EEPROM to eth0 interface
mac_address_prog = "ifconfig eth0 hw ether " + str(macAddress)
mac_address_prog = ["ifconfig", "eth0", "hw", "ether", str(macAddress)]

status, MACAddressProg = commands.getstatusoutput(mac_address_prog)
status, MACAddressProg = getstatusoutput_noshell(mac_address_prog)
if status:
print 'Error: Could not set up "macAddress" for eth0 interface'
print('Error: Could not set up "macAddress" for eth0 interface')
return False

#Make eth0 interface up
status, eth0UP = commands.getstatusoutput("ifconfig eth0 up")
status, eth0UP = getstatusoutput_noshell(["ifconfig", "eth0", "up"])
if status:
print 'Error: Could not make eth0 interface up'
print('Error: Could not make eth0 interface up')
return False

# Juniper QFX5200 platform drivers install
do_install()
time.sleep(2)

# Juniper SFP Intialization
JuniperSFPInitCmd = 'python /usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_sfp_init.py'
JuniperSFPInitCmd = ['python', '/usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_sfp_init.py']
try:
os.system(JuniperSFPInitCmd)
subprocess.call(JuniperSFPInitCmd)
except OSError:
print 'Error: Execution of "%s" failed', JuniperSFPInitCmd
print('Error: Execution of "%s" failed', JuniperSFPInitCmd)
return False

time.sleep(1)
# Invoking the script which retrieves the data from CPU Board and Main Board EEPROM and storing in file
EEPROMDataCmd = 'python /usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py'
EEPROMDataCmd = ['python', '/usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py']
try:
os.system(EEPROMDataCmd)
subprocess.call(EEPROMDataCmd)
except OSError:
print 'Error: Execution of "%s" failed', EEPROMDataCmd
print('Error: Execution of "%s" failed', EEPROMDataCmd)
return False

for x in range(PWMINPUT_NUM):
Expand All @@ -218,16 +225,16 @@ def main():
hwmon_dir)
device_path = pwm_input_path_mapping[x]
time.sleep(1)
cmd = ("sudo echo 22500 > %s" %device_path)
os.system(cmd)
cmd = "22500"
write_file(cmd, device_path)

numsensors_input_path_mapping[x] = NUMSENSORS_PATH.format(
hwmon_input_node_mapping[x],
hwmon_dir)
numsensors_path = numsensors_input_path_mapping[x]
time.sleep(1)
cmd = ("sudo echo 0 > %s" %numsensors_path)
os.system(cmd)
cmd = "0"
write_file(cmd, numsensors_path)

return True

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python
import os
import commands
from sonic_py_common.general import getstatusoutput_noshell

def fantype_detect():

Expand All @@ -15,9 +15,8 @@ def fantype_detect():
for filename in os.listdir(refpgaTMC_path):
if filename.endswith('_type'):
fantype_path = os.path.join(refpgaTMC_path, filename)
cat_string = "cat "
fantype_string = cat_string + fantype_path
status,fan_type=commands.getstatusoutput(fantype_string)
fantype_string = ["cat", fantype_path]
status, fan_type = getstatusoutput_noshell(fantype_string)
if ((fan_type == AFO) or (fan_type == AFI)):
return fan_type
else:
Expand Down
Loading

0 comments on commit 4963c1c

Please sign in to comment.