def test_case_utils_test_b_literal_str(self):
     """Tests the literal string functions with u\'butter\'"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         theResult = (utils.literal_str(b'u\'butter\'')
                      in utils.literal_str(str(u'u\'butter\'')))
         theResult_temp = (utils.literal_str(str(u'u\'butter\''))
                           in utils.literal_str(b'u\'butter\''))
         theResult = (theResult is True) and (theResult_temp is True)
         theResult_temp = None
         del theResult_temp
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     assert theResult
예제 #2
0
def main(argv=None):
    """The main event."""
    try:
        args = parseArgs(argv)
        tainted_input = None
        chroot_path = str(u'/tmp')
        tainted_uid = os.geteuid()
        tainted_gid = os.getegid()
        os.umask(137)
        if args.uid is not None and taint_int(args.uid):
            tainted_uid = args.uid
        if args.gid is not None:
            tainted_gid = args.gid
        if args.chroot_path is not None:
            chroot_path = args.chroot_path
        if args.unsafe_input is not None:
            tainted_input = [utils.literal_str(x) for x in args.unsafe_input]
        if args.unsafe_output is not False:
            unsafe_output = unsafe_main(tainted_input, chroot_path,
                                        tainted_uid, tainted_gid, True)
            print(utils.literal_str(unsafe_output))
        else:
            unsafe_main(tainted_input, chroot_path, tainted_uid, tainted_gid,
                        False)
    except Exception as mainErr:
        remediation.error_breakpoint(
            mainErr, str(u'MAIN FAILED DURING UNSAFE COMMAND. ABORT.'))
        mainErr = None
        del mainErr
    return False
 def test_case_utils_test_a_literal_str(self):
     """Tests the literal string functions"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         u_test = str(u'test')
         try:
             b_test = b'test'
         except Exception:
             b_test = str(b'test')
         theResult = utils.literal_str(b_test) in utils.literal_str(u_test)
         theResult = ((theResult is True)
                      and (utils.literal_str(u_test)
                           in utils.literal_str(b_test)))
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     assert theResult
def gen_html_ul(somelist=None, tagid=None, name=None):
    """
	Generates a list html ul taglet.
	param somelist -- The content of the ul taglet.
	param name -- The optional name of the li taglet.
	param tagid -- The optional tagid of the li taglet.
	Returns:
	str -- the html string of the li taglet.
	"""
    if somelist is None or somelist is [None]:
        return None
    items = [gen_html_li(x) for x in somelist]
    theresult = None
    if tagid is not None and has_special_html_chars(tagid) is not True:
        if name is None or has_special_html_chars(name) is True:
            name = utils.literal_str(tagid)
        theresult = str(u'<ul name=\"{}\" id=\"{}\">').format(
            utils.literal_str(name), utils.literal_str(tagid))
        for item in items:
            theresult = str(theresult + item)
    elif name is not None and has_special_html_chars(name) is not True:
        theresult = str(u'<ul name=\"{}\">').format(utils.literal_str(name))
        for item in items:
            theresult = str(theresult + item)
    else:
        theresult = str(u'<ul>')
        for item in items:
            theresult = str(theresult + item)
    theresult = str(theresult + u'</ul>')
    return theresult
 def test_case_utils_bad_literal_str(self):
     """Tests the literal string functions with ABC"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         the_test_cases = [(utils.literal_str(bytes(int('0x1f', 0))),
                            utils.literal_str(bytes(int('0x1f', 0)))),
                           (utils.literal_str(bytes(int('0xee', 0))),
                            utils.literal_str(bytes(int('0xee', 0)))),
                           (utils.literal_str(bytes(int('0x05', 0))),
                            utils.literal_str(bytes(int('0x05', 0))))]
         for testcase in the_test_cases:
             if theResult is True:
                 if testcase[0] is None:
                     continue
                 if utils.literal_str(testcase[0]) is None:
                     continue
                 if utils.literal_str(testcase[1]) is not None:
                     self.assertEqual(utils.literal_str(testcase[0]),
                                      utils.literal_str(testcase[1]))
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del (err)
         theResult = False
     assert theResult
 def test_case_utils_Pangram_literal_str(self):
     """Tests the literal string functions with a Pangram"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         theResult = utils.literal_str(
             b'The quick brown fox jumps over the lazy dog'
         ) in utils.literal_str(
             str(u'The quick brown fox jumps over the lazy dog'))  # noqa
         theResult = (theResult is True) and (
             utils.literal_str(
                 str(u'The quick brown fox jumps over the lazy dog'))
             in utils.literal_str(
                 b'The quick brown fox jumps over the lazy dog'))  # noqa
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     assert theResult
 def test_case_utils_fuzz_x_str(self):  # noqa
     """Tests the literal string functions with a fuzzed input"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from piaplib import keyring as keyring
         if keyring.__name__ is None:
             raise ImportError("Failed to import keyring")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         from keyring import rand as rand
         if rand.__name__ is None:
             raise ImportError("Failed to import rand")
         the_test_cases = []
         for test_count in range(300):
             temp = rand.randChar(1)
             the_test_cases.append(
                 (utils.literal_str(temp), utils.literal_str(str(temp))))
         for testcase in the_test_cases:
             if theResult is True:
                 if testcase[0] is not None:
                     if testcase[1] is not None:
                         theResult = (utils.xstr(testcase[0])
                                      in utils.xstr(testcase[1]))
                     if utils.literal_str(testcase[1]) is not None:
                         theResult_temp = (utils.xstr(testcase[0])
                                           in utils.xstr(testcase[1]))
                         theResult = (theResult is True) and (theResult_temp
                                                              is True)
                         if theResult is not True:
                             print("NEW test")
                             print(str(testcase))
                             print(repr(testcase))
                         theResult_temp = None
                         del theResult_temp
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     assert theResult
def get_client_arp_status_raw(client_ip=None, lan_interface=None):
	"""list the raw status of client sta."""
	if lan_interface not in interfaces.INTERFACE_CHOICES:
		lan_interface = interfaces.INTERFACE_CHOICES[0]
	arguments = [str("/usr/sbin/arp"), str("-i"), str(lan_interface), str("-a")]
	theRawClientState = None
	try:
		output = subprocess.check_output(arguments, stderr=subprocess.STDOUT)
		if (output is not None) and (len(output) > 0):
			lines = [
				utils.literal_str(x) for x in output.splitlines() if isLineForSTA(x, client_ip)
			]
			theRawClientState = str("")
			for line in lines:
				if (line is not None) and (len(line) > 0):
					theRawClientState = str("{}{}\n").format(str(theRawClientState), str(line))
			del lines
		else:
			theRawClientState = None
	except subprocess.CalledProcessError as subErr:
		subErr = None
		del subErr
		theRawClientState = None
	except Exception as cmdErr:
		print(str("ERROR: get_client_arp_status_raw - 403"))
		print(str(type(cmdErr)))
		print(str(cmdErr))
		print(str(cmdErr.args))
		theRawClientState = None
	return theRawClientState
def get_user_name(user_name=None, use_html=False):
	if user_name is None:
		return None
	if use_html is not True:
		temp = get_user_list()
		if utils.literal_str(user_name) in temp:
			temp = None
			del temp
			return utils.literal_str(user_name)
		else:
			temp = None
			del temp
			return None
	else:
		user = utils.literal_str(get_user_name(user_name, False))
		return html_generator.gen_html_td(user, str(u'user_name_{}').format(user))
def show_user(user_name=None, is_verbose=False, use_html=False):
	"""show the given user."""
	theResult = None
	try:
		if use_html is True:
			format_pattern = str(u'{}{}{}{}')
		else:
			format_pattern = str(u'{} {} {} {}')
		theResult = str(format_pattern).format(
			get_user_name(user_name, use_html),
			get_user_ttys(user_name, use_html),
			get_user_ip(user_name, use_html),
			get_user_status(get_user_name(user_name, False), use_html)
		)
		if use_html:
			the_temp_Result = html_generator.gen_html_tr(
				theResult,
				str(u'user_status_row_{}').format(get_user_name(user_name, False))
			)
			theResult = utils.literal_str(the_temp_Result)
	except Exception as cmdErr:
		if not use_html:
			logs.log(str(type(cmdErr)), "Error")
			logs.log(str(cmdErr), "Error")
			logs.log(str((cmdErr.args)), "Error")
		theResult = "UNKNOWN"
	return theResult
def has_special_html_chars(raw_str=None):
    """
	Determines if the string have special html charterers.
	param somestr -- The string to test.
	Returns:
	True -- if the string has special charterers.
	False -- otherwise.
	"""
    try:
        somestr = utils.literal_str(raw_str)
        if somestr is None:
            return True
        badchars = [
            u'\"', u'\'', u'\\', u'%', u'>', u'<', u'=',
            str("""\""""),
            str("""\'"""),
            str("""\\"""),
            str("""%"""),
            str(""">"""),
            str("""<"""),
            str("""='""")
        ]
        for badchar in badchars:
            if badchar in somestr:
                return True
    except Exception as badinput:
        print(str("Bad html render string input."))
        print(str(type(badinput)))
        badinput = None
        del badinput
        return True
    return False
def gen_html_label(content=None,
                   role=HTML_LABEL_ROLES[0],
                   tagid=None,
                   name=None):
    """
	Generates a table data html label taglet.
	param content -- The content of the td taglet.
	param role -- The label class of the span taglet.
	param name -- The optional name of the td taglet.
	param tagid -- The optional tagid of the td taglet.
	Returns:
	str -- the html string of the td taglet.
	"""
    # WARN: not ready for prod - check types, errors, etc,
    # security auditors: if you are reading this you found something
    # I forgot to make ready for prod. patches welcome. CWE-20 BUG
    if tagid is not None and has_special_html_chars(tagid) is not True:
        if name is not None and has_special_html_chars(name) is not True:
            return str(
                u'<span class=\"label label-{}\" name=\"{}\" id=\"{}\">{}</span>'
            ).format(role, utils.literal_str(name), utils.literal_str(tagid),
                     utils.literal_str(content))
        else:
            return str(
                u'<span class=\"label label-{}\" id=\"{}\">{}</span>').format(
                    role, has_special_html_chars(tagid),
                    utils.literal_str(content))
    elif name is not None and has_special_html_chars(name) is not True:
        return str(
            u'<span class=\"label label-{}\" name=\"{}\">{}</span>').format(
                role, utils.literal_str(name), utils.literal_str(content))
    else:
        return str(u'<span class=\"label label-{}\">{}</span>').format(
            role, utils.literal_str(content))
def isLineForSTA(someLine=None, staname=None):
	"""determins if a raw output line is for a STA"""
	doesMatch = False
	try:
		doesMatch = utils.isLineForMatch(someLine, staname)
		if (doesMatch is False) and (utils.literal_str(someLine) is not None):
			if str(staname) in utils.extractIPv4(utils.literal_str(someLine)):
				doesMatch = True
			else:
				doesMatch = False
	except Exception as matchErr:
		print(str(type(matchErr)))
		print(str(matchErr))
		print(str(matchErr.args))
		matchErr = None
		del matchErr
		doesMatch = False
	return doesMatch
 def _test_case_utils_super_fuzz_literal_str(self):
     """Tests the literal string functions with random strings"""
     theResult = True
     try:
         from piaplib import pku as pku
         from pku import utils as utils
         import os
         for depends in [os, utils, pku]:
             if depends.__name__ is None:
                 raise ImportError("Failed to import dependancy")
         for testrun in range(1000):
             randomTest = os.urandom(10)
             testcase = [str(randomTest), utils.literal_str(randomTest)]
             if theResult is True:
                 if testcase[1] is not None:
                     theResult = (testcase[0] in testcase[1])
                 if utils.literal_str(testcase[1]) is not None:
                     theResult_temp = (testcase[0] in testcase[1])
                     theResult = (theResult is True) and (theResult_temp is
                                                          True)
                     theResult_temp = None
                     del theResult_temp
                     if theResult is not True:
                         print("NEW test")
                         print(str(testcase))
                         print(repr(testcase))
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     assert theResult
def get_client_sta_status_raw():
	"""list the raw status of client sta."""
	theRawClientState = None
	if not utils.xisfile(str("/opt/PiAP/hostapd_actions/clients")):
		return str(u'UNKNOWN')
	try:
		try:
			# hard-coded white-list cmd
			output = subprocess.check_output(
				[str("/opt/PiAP/hostapd_actions/clients")],
				stderr=subprocess.STDOUT
			)
			if (output is not None) and (len(output) > 0):
				lines = [utils.literal_str(x) for x in output.splitlines() if x is not None]
				theRawClientState = str("")
				for line in lines:
					if (line is not None) and (len(line) > 0):
						theRawClientState = str("{}{}\n").format(str(theRawClientState), str(line))
				del lines
			else:
				theRawClientState = None
		except subprocess.CalledProcessError as subErr:
			print(str(type(subErr)))
			print(str(subErr))
			print(str(subErr.args))
			subErr = None
			del subErr
			theRawClientState = u'UNKNOWN'
		except Exception as cmdErr:
			print(str("ERROR: get_client_sta_status_raw"))
			print(str(type(cmdErr)))
			print(str(cmdErr))
			print(str(cmdErr.args))
			cmdErr = None
			del cmdErr
			theRawClientState = None
	except Exception as importErr:
		print(str(importErr))
		print(str(importErr.args))
		theRawClientState = None
	return theRawClientState
 def test_case_utils_none_lit(self):
     """Tests the literal string with a None as input"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         self.assertIsNone(utils.literal_str(None))
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     self.assertTrue(theResult)
 def test_case_utils_lit_str_unicode(self):
     """Tests the literal_str with an unicode value as input"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         self.assertEqual(
             utils.literal_str(unicode(str("test"))),  # noqa
             str("test"))
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del err
         theResult = False
     self.assertTrue(theResult)
def gen_html_tag(tag="div", content=None, tagid=None, name=None):
    """
	Generates a table row html tr taglet.
	param tag -- The type of taglet.
	param content -- The content of the taglet.
	param name -- The optional name of the taglet.
	param tagid -- The optional tagid of the taglet.
	Returns:
	str -- the html string of the taglet.
	"""
    if tag is None or (isinstance(tag, str) is False):
        return content
    if tagid is not None and has_special_html_chars(tagid) is not True:
        if name is not None and has_special_html_chars(name) is not True:
            return str(
                u'<{thetag} name=\"{thename}\" id=\"{theid}\">{thecontent}</{thetag}>'
            ).format(thetag=utils.literal_str(tag),
                     thename=utils.literal_str(name),
                     theid=utils.literal_str(tagid),
                     thecontent=utils.literal_str(content))
        else:
            return str(
                u'<{thetag} id=\"{theid}\">{thecontent}</{thetag}>').format(
                    thetag=utils.literal_str(tag),
                    theid=utils.literal_str(tagid),
                    thecontent=utils.literal_str(content))
    elif name is not None and has_special_html_chars(name) is not True:
        return str(
            u'<{thetag} name=\"{thename}\">{thecontent}</{thetag}>').format(
                thetag=utils.literal_str(tag),
                thename=utils.literal_str(name),
                thecontent=utils.literal_str(content))
    else:
        return str(u'<{thetag}>{thecontent}</{thetag}>').format(
            thetag=utils.literal_str(tag),
            thecontent=utils.literal_str(content))
def get_user_work_status_raw(user_name=None):
	"""list the raw status of user work."""
	theRawOutput = None
	try:
		import subprocess
		output = None
		stderrors = None
		try:
			# hard-coded white-list cmds
			p1 = subprocess.Popen(
				[str("w"), str(get_w_cmd_args())],
				shell=False,
				stdout=subprocess.PIPE,
				stderr=None
			)
			p2 = subprocess.Popen(
				[
					str("tr"),
					str("-s"),
					utils.literal_str("""' '"""),
					utils.literal_str("""' '""")
				],
				shell=False,
				stdin=p1.stdout,
				stdout=subprocess.PIPE,
				close_fds=True
			)
			p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
			(output, stderrors) = p2.communicate()
		except subprocess.CalledProcessError as subErr:
			p1.kill()
			p2.kill()
			subErr = None
			del(subErr)
			theRawOutput = None
		except Exception as cmdErr:
			p1.kill()
			p2.kill()
			logs.log(str(type(cmdErr)), "Error")
			logs.log(str(cmdErr), "Error")
			logs.log(str((cmdErr.args)), "Error")
			theRawOutput = None
		finally:
			p2.wait()
			p1.wait()
		if stderrors:
			output = None
		if (isinstance(output, bytes)):
			output = output.decode('utf8')
		if output is not None and len(output) > 0:
			lines = [
				utils.literal_str(x) for x in output.splitlines() if isLineForUser(x, user_name)
			]
			theRawOutput = str("")
			for line in lines:
				if (line is not None) and (len(line) > 0):
					theRawOutput = str("{}{}\n").format(str(theRawOutput), str(line))
			del(lines)
		else:
			theRawOutput = None
	except Exception as importErr:
		logs.log(str(type(importErr)), "Warning")
		logs.log(str(importErr), "Warning")
		logs.log(str((importErr.args)), "Warning")
		theRawOutput = None
	return theRawOutput
 def test_case_utils_base_literal_str(self):
     """Tests the literal string functions with ABC"""
     theResult = True
     try:
         from piaplib import pku as pku
         if pku.__name__ is None:
             raise ImportError("Failed to import pku")
         from pku import utils as utils
         if utils.__name__ is None:
             raise ImportError("Failed to import utils")
         the_test_cases = [
             (utils.literal_str(b'a'), utils.literal_str(str(u'a'))),
             (utils.literal_str(b'A'), utils.literal_str(str(u'A'))),
             (utils.literal_str(b'b'), utils.literal_str(str(u'b'))),
             (utils.literal_str(b'B'), utils.literal_str(str(u'B'))),
             (utils.literal_str(b'c'), utils.literal_str(str(u'c'))),
             (utils.literal_str(b'C'), utils.literal_str(str(u'C'))),
             (utils.literal_str(b'a'), utils.literal_str("a")),
             (utils.literal_str(b'A'), utils.literal_str("A")),
             (utils.literal_str(b'b'), utils.literal_str("b")),
             (utils.literal_str(b'B'), utils.literal_str("B")),
             (utils.literal_str(b'c'), utils.literal_str("c")),
             (utils.literal_str(b'C'), utils.literal_str("C")),
             (utils.literal_str(b'\x1f'), utils.literal_str(str(u'\x1f'))),
             (utils.literal_str(b'\x1f'), utils.literal_str("\x1f"))
         ]
         for testcase in the_test_cases:
             if theResult is True:
                 if testcase[0] is None or testcase[1] is None:
                     continue
                 else:
                     theResult = (testcase[0] in testcase[1])
                 if utils.literal_str(testcase[0]) is None:
                     continue
                 if utils.literal_str(testcase[1]) is not None:
                     theResult_temp = (utils.literal_str(testcase[0])
                                       in utils.literal_str(testcase[1]))
                     theResult = (theResult is True) and (theResult_temp is
                                                          True)
                     theResult_temp = None
                     del (theResult_temp)
     except Exception as err:
         print(str(""))
         print(str(type(err)))
         print(str(err))
         print(str((err.args)))
         print(str(""))
         err = None
         del (err)
         theResult = False
     assert theResult
def get_system_work_status_raw(user_name=None):
	"""list the raw status of system work."""
	theuserState = None
	try:
		import subprocess
		try:
			# hard-coded white-list cmds
			p1 = subprocess.Popen(
				[utils.literal_str(get_ps_cmd_path()), str("-eo"), str("user,command")],
				shell=False,
				stdout=subprocess.PIPE,
				stderr=None,
				close_fds=True
			)
			p2 = subprocess.Popen(
				[
					str("tr"),
					str("-s"),
					utils.literal_str("""' '"""),
					utils.literal_str("""' '""")
				],
				shell=False,
				stdin=p1.stdout,
				stdout=subprocess.PIPE,
				close_fds=True
			)
			p3 = subprocess.Popen(
				[
					str("sed"),
					str("-E"),
					str("-e"),
					str(utils.literal_str("""s/[\\[\\(]{1}[^]]+[]\\)]{1}/SYSTEM/g"""))
				],
				shell=False,
				stdin=p2.stdout,
				stdout=subprocess.PIPE,
				close_fds=True
			)
			p4 = subprocess.Popen(
				[utils.literal_str(get_sort_cmd_path())],
				shell=False,
				stdin=p3.stdout,
				stdout=subprocess.PIPE,
				close_fds=True
			)
			p5 = subprocess.Popen(
				[utils.literal_str("""uniq""")],
				shell=False,
				stdin=p4.stdout,
				stdout=subprocess.PIPE,
				close_fds=True
			)
			p4.stdout.close()  # Allow p4 to receive a SIGPIPE if p5 exits.
			(output, stderrors) = p5.communicate()
			p3.stdout.close()  # Allow p4 to receive a SIGPIPE when p5 exits.
			p2.stdout.close()  # Allow p4 to receive a SIGPIPE when p5 exits.
			p1.stdout.close()  # Allow p4 to receive a SIGPIPE when p5 exits.
			if (isinstance(output, bytes)):
				output = output.decode('utf8')
			if (output is not None) and (len(output) > 0):
				lines = [
					utils.literal_str(x) for x in output.splitlines() if isLineForUser(x, user_name)
				]
				theuserState = str("")
				for line in lines:
					if (line is not None) and (len(line) > 0):
						theuserState = str("{}{}\n").format(str(theuserState), str(line))
				del lines
			else:
				theuserState = None
		except subprocess.CalledProcessError as subErr:
			subErr = None
			del subErr
			theuserState = None
		except Exception as cmdErr:
			logs.log(str(type(cmdErr)), "Error")
			logs.log(str(cmdErr), "Error")
			logs.log(str((cmdErr.args)), "Error")
			theuserState = None
	except Exception as importErr:
		logs.log(str(importErr), "Warning")
		logs.log(str((importErr.args)), "Warning")
		theuserState = None
	return theuserState