id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,000 | mailgun/talon | talon/signature/learning/dataset.py | build_detection_dataset | def build_detection_dataset(folder, dataset_filename,
sender_known=True):
"""Builds signature detection dataset using emails from folder.
folder should have the following structure:
x-- folder
| x-- P
| | | -- positive sample email 1
| | | -- positive sample email 2
| | | -- ...
| x-- N
| | | -- negative sample email 1
| | | -- negative sample email 2
| | | -- ...
If the dataset file already exist it is rewritten.
"""
if os.path.exists(dataset_filename):
os.remove(dataset_filename)
build_detection_class(os.path.join(folder, u'P'),
dataset_filename, 1)
build_detection_class(os.path.join(folder, u'N'),
dataset_filename, -1) | python | def build_detection_dataset(folder, dataset_filename,
sender_known=True):
if os.path.exists(dataset_filename):
os.remove(dataset_filename)
build_detection_class(os.path.join(folder, u'P'),
dataset_filename, 1)
build_detection_class(os.path.join(folder, u'N'),
dataset_filename, -1) | [
"def",
"build_detection_dataset",
"(",
"folder",
",",
"dataset_filename",
",",
"sender_known",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dataset_filename",
")",
":",
"os",
".",
"remove",
"(",
"dataset_filename",
")",
"build_detection... | Builds signature detection dataset using emails from folder.
folder should have the following structure:
x-- folder
| x-- P
| | | -- positive sample email 1
| | | -- positive sample email 2
| | | -- ...
| x-- N
| | | -- negative sample email 1
| | | -- negative sample email 2
| | | -- ...
If the dataset file already exist it is rewritten. | [
"Builds",
"signature",
"detection",
"dataset",
"using",
"emails",
"from",
"folder",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/dataset.py#L114-L136 |
227,001 | mailgun/talon | talon/signature/learning/dataset.py | build_extraction_dataset | def build_extraction_dataset(folder, dataset_filename,
sender_known=True):
"""Builds signature extraction dataset using emails in the `folder`.
The emails in the `folder` should be annotated i.e. signature lines
should be marked with `#sig#`.
"""
if os.path.exists(dataset_filename):
os.remove(dataset_filename)
with open(dataset_filename, 'a') as dataset:
for filename in os.listdir(folder):
filename = os.path.join(folder, filename)
sender, msg = parse_msg_sender(filename, sender_known)
if not sender or not msg:
continue
lines = msg.splitlines()
for i in range(1, min(SIGNATURE_MAX_LINES,
len(lines)) + 1):
line = lines[-i]
label = -1
if line[:len(SIGNATURE_ANNOTATION)] == \
SIGNATURE_ANNOTATION:
label = 1
line = line[len(SIGNATURE_ANNOTATION):]
elif line[:len(REPLY_ANNOTATION)] == REPLY_ANNOTATION:
line = line[len(REPLY_ANNOTATION):]
X = build_pattern(line, features(sender))
X.append(label)
labeled_pattern = ','.join([str(e) for e in X])
dataset.write(labeled_pattern + '\n') | python | def build_extraction_dataset(folder, dataset_filename,
sender_known=True):
if os.path.exists(dataset_filename):
os.remove(dataset_filename)
with open(dataset_filename, 'a') as dataset:
for filename in os.listdir(folder):
filename = os.path.join(folder, filename)
sender, msg = parse_msg_sender(filename, sender_known)
if not sender or not msg:
continue
lines = msg.splitlines()
for i in range(1, min(SIGNATURE_MAX_LINES,
len(lines)) + 1):
line = lines[-i]
label = -1
if line[:len(SIGNATURE_ANNOTATION)] == \
SIGNATURE_ANNOTATION:
label = 1
line = line[len(SIGNATURE_ANNOTATION):]
elif line[:len(REPLY_ANNOTATION)] == REPLY_ANNOTATION:
line = line[len(REPLY_ANNOTATION):]
X = build_pattern(line, features(sender))
X.append(label)
labeled_pattern = ','.join([str(e) for e in X])
dataset.write(labeled_pattern + '\n') | [
"def",
"build_extraction_dataset",
"(",
"folder",
",",
"dataset_filename",
",",
"sender_known",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dataset_filename",
")",
":",
"os",
".",
"remove",
"(",
"dataset_filename",
")",
"with",
"open... | Builds signature extraction dataset using emails in the `folder`.
The emails in the `folder` should be annotated i.e. signature lines
should be marked with `#sig#`. | [
"Builds",
"signature",
"extraction",
"dataset",
"using",
"emails",
"in",
"the",
"folder",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/dataset.py#L139-L169 |
227,002 | mailgun/talon | talon/html_quotations.py | add_checkpoint | def add_checkpoint(html_note, counter):
"""Recursively adds checkpoints to html tree.
"""
if html_note.text:
html_note.text = (html_note.text + CHECKPOINT_PREFIX +
str(counter) + CHECKPOINT_SUFFIX)
else:
html_note.text = (CHECKPOINT_PREFIX + str(counter) +
CHECKPOINT_SUFFIX)
counter += 1
for child in html_note.iterchildren():
counter = add_checkpoint(child, counter)
if html_note.tail:
html_note.tail = (html_note.tail + CHECKPOINT_PREFIX +
str(counter) + CHECKPOINT_SUFFIX)
else:
html_note.tail = (CHECKPOINT_PREFIX + str(counter) +
CHECKPOINT_SUFFIX)
counter += 1
return counter | python | def add_checkpoint(html_note, counter):
if html_note.text:
html_note.text = (html_note.text + CHECKPOINT_PREFIX +
str(counter) + CHECKPOINT_SUFFIX)
else:
html_note.text = (CHECKPOINT_PREFIX + str(counter) +
CHECKPOINT_SUFFIX)
counter += 1
for child in html_note.iterchildren():
counter = add_checkpoint(child, counter)
if html_note.tail:
html_note.tail = (html_note.tail + CHECKPOINT_PREFIX +
str(counter) + CHECKPOINT_SUFFIX)
else:
html_note.tail = (CHECKPOINT_PREFIX + str(counter) +
CHECKPOINT_SUFFIX)
counter += 1
return counter | [
"def",
"add_checkpoint",
"(",
"html_note",
",",
"counter",
")",
":",
"if",
"html_note",
".",
"text",
":",
"html_note",
".",
"text",
"=",
"(",
"html_note",
".",
"text",
"+",
"CHECKPOINT_PREFIX",
"+",
"str",
"(",
"counter",
")",
"+",
"CHECKPOINT_SUFFIX",
")"... | Recursively adds checkpoints to html tree. | [
"Recursively",
"adds",
"checkpoints",
"to",
"html",
"tree",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/html_quotations.py#L20-L42 |
227,003 | mailgun/talon | talon/html_quotations.py | delete_quotation_tags | def delete_quotation_tags(html_note, counter, quotation_checkpoints):
"""Deletes tags with quotation checkpoints from html tree.
"""
tag_in_quotation = True
if quotation_checkpoints[counter]:
html_note.text = ''
else:
tag_in_quotation = False
counter += 1
quotation_children = [] # Children tags which are in quotation.
for child in html_note.iterchildren():
counter, child_tag_in_quotation = delete_quotation_tags(
child, counter,
quotation_checkpoints
)
if child_tag_in_quotation:
quotation_children.append(child)
if quotation_checkpoints[counter]:
html_note.tail = ''
else:
tag_in_quotation = False
counter += 1
if tag_in_quotation:
return counter, tag_in_quotation
else:
# Remove quotation children.
for child in quotation_children:
html_note.remove(child)
return counter, tag_in_quotation | python | def delete_quotation_tags(html_note, counter, quotation_checkpoints):
tag_in_quotation = True
if quotation_checkpoints[counter]:
html_note.text = ''
else:
tag_in_quotation = False
counter += 1
quotation_children = [] # Children tags which are in quotation.
for child in html_note.iterchildren():
counter, child_tag_in_quotation = delete_quotation_tags(
child, counter,
quotation_checkpoints
)
if child_tag_in_quotation:
quotation_children.append(child)
if quotation_checkpoints[counter]:
html_note.tail = ''
else:
tag_in_quotation = False
counter += 1
if tag_in_quotation:
return counter, tag_in_quotation
else:
# Remove quotation children.
for child in quotation_children:
html_note.remove(child)
return counter, tag_in_quotation | [
"def",
"delete_quotation_tags",
"(",
"html_note",
",",
"counter",
",",
"quotation_checkpoints",
")",
":",
"tag_in_quotation",
"=",
"True",
"if",
"quotation_checkpoints",
"[",
"counter",
"]",
":",
"html_note",
".",
"text",
"=",
"''",
"else",
":",
"tag_in_quotation"... | Deletes tags with quotation checkpoints from html tree. | [
"Deletes",
"tags",
"with",
"quotation",
"checkpoints",
"from",
"html",
"tree",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/html_quotations.py#L45-L77 |
227,004 | mailgun/talon | talon/html_quotations.py | cut_gmail_quote | def cut_gmail_quote(html_message):
''' Cuts the outermost block element with class gmail_quote. '''
gmail_quote = cssselect('div.gmail_quote', html_message)
if gmail_quote and (gmail_quote[0].text is None or not RE_FWD.match(gmail_quote[0].text)):
gmail_quote[0].getparent().remove(gmail_quote[0])
return True | python | def cut_gmail_quote(html_message):
''' Cuts the outermost block element with class gmail_quote. '''
gmail_quote = cssselect('div.gmail_quote', html_message)
if gmail_quote and (gmail_quote[0].text is None or not RE_FWD.match(gmail_quote[0].text)):
gmail_quote[0].getparent().remove(gmail_quote[0])
return True | [
"def",
"cut_gmail_quote",
"(",
"html_message",
")",
":",
"gmail_quote",
"=",
"cssselect",
"(",
"'div.gmail_quote'",
",",
"html_message",
")",
"if",
"gmail_quote",
"and",
"(",
"gmail_quote",
"[",
"0",
"]",
".",
"text",
"is",
"None",
"or",
"not",
"RE_FWD",
"."... | Cuts the outermost block element with class gmail_quote. | [
"Cuts",
"the",
"outermost",
"block",
"element",
"with",
"class",
"gmail_quote",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/html_quotations.py#L80-L85 |
227,005 | mailgun/talon | talon/html_quotations.py | cut_microsoft_quote | def cut_microsoft_quote(html_message):
''' Cuts splitter block and all following blocks. '''
#use EXSLT extensions to have a regex match() function with lxml
ns = {"re": "http://exslt.org/regular-expressions"}
#general pattern: @style='border:none;border-top:solid <color> 1.0pt;padding:3.0pt 0<unit> 0<unit> 0<unit>'
#outlook 2007, 2010 (international) <color=#B5C4DF> <unit=cm>
#outlook 2007, 2010 (american) <color=#B5C4DF> <unit=pt>
#outlook 2013 (international) <color=#E1E1E1> <unit=cm>
#outlook 2013 (american) <color=#E1E1E1> <unit=pt>
#also handles a variant with a space after the semicolon
splitter = html_message.xpath(
#outlook 2007, 2010, 2013 (international, american)
"//div[@style[re:match(., 'border:none; ?border-top:solid #(E1E1E1|B5C4DF) 1.0pt; ?"
"padding:3.0pt 0(in|cm) 0(in|cm) 0(in|cm)')]]|"
#windows mail
"//div[@style='padding-top: 5px; "
"border-top-color: rgb(229, 229, 229); "
"border-top-width: 1px; border-top-style: solid;']"
, namespaces=ns
)
if splitter:
splitter = splitter[0]
#outlook 2010
if splitter == splitter.getparent().getchildren()[0]:
splitter = splitter.getparent()
else:
#outlook 2003
splitter = html_message.xpath(
"//div"
"/div[@class='MsoNormal' and @align='center' "
"and @style='text-align:center']"
"/font"
"/span"
"/hr[@size='3' and @width='100%' and @align='center' "
"and @tabindex='-1']"
)
if len(splitter):
splitter = splitter[0]
splitter = splitter.getparent().getparent()
splitter = splitter.getparent().getparent()
if len(splitter):
parent = splitter.getparent()
after_splitter = splitter.getnext()
while after_splitter is not None:
parent.remove(after_splitter)
after_splitter = splitter.getnext()
parent.remove(splitter)
return True
return False | python | def cut_microsoft_quote(html_message):
''' Cuts splitter block and all following blocks. '''
#use EXSLT extensions to have a regex match() function with lxml
ns = {"re": "http://exslt.org/regular-expressions"}
#general pattern: @style='border:none;border-top:solid <color> 1.0pt;padding:3.0pt 0<unit> 0<unit> 0<unit>'
#outlook 2007, 2010 (international) <color=#B5C4DF> <unit=cm>
#outlook 2007, 2010 (american) <color=#B5C4DF> <unit=pt>
#outlook 2013 (international) <color=#E1E1E1> <unit=cm>
#outlook 2013 (american) <color=#E1E1E1> <unit=pt>
#also handles a variant with a space after the semicolon
splitter = html_message.xpath(
#outlook 2007, 2010, 2013 (international, american)
"//div[@style[re:match(., 'border:none; ?border-top:solid #(E1E1E1|B5C4DF) 1.0pt; ?"
"padding:3.0pt 0(in|cm) 0(in|cm) 0(in|cm)')]]|"
#windows mail
"//div[@style='padding-top: 5px; "
"border-top-color: rgb(229, 229, 229); "
"border-top-width: 1px; border-top-style: solid;']"
, namespaces=ns
)
if splitter:
splitter = splitter[0]
#outlook 2010
if splitter == splitter.getparent().getchildren()[0]:
splitter = splitter.getparent()
else:
#outlook 2003
splitter = html_message.xpath(
"//div"
"/div[@class='MsoNormal' and @align='center' "
"and @style='text-align:center']"
"/font"
"/span"
"/hr[@size='3' and @width='100%' and @align='center' "
"and @tabindex='-1']"
)
if len(splitter):
splitter = splitter[0]
splitter = splitter.getparent().getparent()
splitter = splitter.getparent().getparent()
if len(splitter):
parent = splitter.getparent()
after_splitter = splitter.getnext()
while after_splitter is not None:
parent.remove(after_splitter)
after_splitter = splitter.getnext()
parent.remove(splitter)
return True
return False | [
"def",
"cut_microsoft_quote",
"(",
"html_message",
")",
":",
"#use EXSLT extensions to have a regex match() function with lxml",
"ns",
"=",
"{",
"\"re\"",
":",
"\"http://exslt.org/regular-expressions\"",
"}",
"#general pattern: @style='border:none;border-top:solid <color> 1.0pt;padding:3... | Cuts splitter block and all following blocks. | [
"Cuts",
"splitter",
"block",
"and",
"all",
"following",
"blocks",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/html_quotations.py#L88-L140 |
227,006 | mailgun/talon | talon/html_quotations.py | cut_blockquote | def cut_blockquote(html_message):
''' Cuts the last non-nested blockquote with wrapping elements.'''
quote = html_message.xpath(
'(.//blockquote)'
'[not(@class="gmail_quote") and not(ancestor::blockquote)]'
'[last()]')
if quote:
quote = quote[0]
quote.getparent().remove(quote)
return True | python | def cut_blockquote(html_message):
''' Cuts the last non-nested blockquote with wrapping elements.'''
quote = html_message.xpath(
'(.//blockquote)'
'[not(@class="gmail_quote") and not(ancestor::blockquote)]'
'[last()]')
if quote:
quote = quote[0]
quote.getparent().remove(quote)
return True | [
"def",
"cut_blockquote",
"(",
"html_message",
")",
":",
"quote",
"=",
"html_message",
".",
"xpath",
"(",
"'(.//blockquote)'",
"'[not(@class=\"gmail_quote\") and not(ancestor::blockquote)]'",
"'[last()]'",
")",
"if",
"quote",
":",
"quote",
"=",
"quote",
"[",
"0",
"]",
... | Cuts the last non-nested blockquote with wrapping elements. | [
"Cuts",
"the",
"last",
"non",
"-",
"nested",
"blockquote",
"with",
"wrapping",
"elements",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/html_quotations.py#L153-L163 |
227,007 | fananimi/pyzk | zk/base.py | make_commkey | def make_commkey(key, session_id, ticks=50):
"""
take a password and session_id and scramble them to send to the machine.
copied from commpro.c - MakeKey
"""
key = int(key)
session_id = int(session_id)
k = 0
for i in range(32):
if (key & (1 << i)):
k = (k << 1 | 1)
else:
k = k << 1
k += session_id
k = pack(b'I', k)
k = unpack(b'BBBB', k)
k = pack(
b'BBBB',
k[0] ^ ord('Z'),
k[1] ^ ord('K'),
k[2] ^ ord('S'),
k[3] ^ ord('O'))
k = unpack(b'HH', k)
k = pack(b'HH', k[1], k[0])
B = 0xff & ticks
k = unpack(b'BBBB', k)
k = pack(
b'BBBB',
k[0] ^ B,
k[1] ^ B,
B,
k[3] ^ B)
return k | python | def make_commkey(key, session_id, ticks=50):
key = int(key)
session_id = int(session_id)
k = 0
for i in range(32):
if (key & (1 << i)):
k = (k << 1 | 1)
else:
k = k << 1
k += session_id
k = pack(b'I', k)
k = unpack(b'BBBB', k)
k = pack(
b'BBBB',
k[0] ^ ord('Z'),
k[1] ^ ord('K'),
k[2] ^ ord('S'),
k[3] ^ ord('O'))
k = unpack(b'HH', k)
k = pack(b'HH', k[1], k[0])
B = 0xff & ticks
k = unpack(b'BBBB', k)
k = pack(
b'BBBB',
k[0] ^ B,
k[1] ^ B,
B,
k[3] ^ B)
return k | [
"def",
"make_commkey",
"(",
"key",
",",
"session_id",
",",
"ticks",
"=",
"50",
")",
":",
"key",
"=",
"int",
"(",
"key",
")",
"session_id",
"=",
"int",
"(",
"session_id",
")",
"k",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"32",
")",
":",
"if",
... | take a password and session_id and scramble them to send to the machine.
copied from commpro.c - MakeKey | [
"take",
"a",
"password",
"and",
"session_id",
"and",
"scramble",
"them",
"to",
"send",
"to",
"the",
"machine",
".",
"copied",
"from",
"commpro",
".",
"c",
"-",
"MakeKey"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L23-L57 |
227,008 | fananimi/pyzk | zk/base.py | ZK.__create_tcp_top | def __create_tcp_top(self, packet):
"""
witch the complete packet set top header
"""
length = len(packet)
top = pack('<HHI', const.MACHINE_PREPARE_DATA_1, const.MACHINE_PREPARE_DATA_2, length)
return top + packet | python | def __create_tcp_top(self, packet):
length = len(packet)
top = pack('<HHI', const.MACHINE_PREPARE_DATA_1, const.MACHINE_PREPARE_DATA_2, length)
return top + packet | [
"def",
"__create_tcp_top",
"(",
"self",
",",
"packet",
")",
":",
"length",
"=",
"len",
"(",
"packet",
")",
"top",
"=",
"pack",
"(",
"'<HHI'",
",",
"const",
".",
"MACHINE_PREPARE_DATA_1",
",",
"const",
".",
"MACHINE_PREPARE_DATA_2",
",",
"length",
")",
"ret... | witch the complete packet set top header | [
"witch",
"the",
"complete",
"packet",
"set",
"top",
"header"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L178-L184 |
227,009 | fananimi/pyzk | zk/base.py | ZK.__create_header | def __create_header(self, command, command_string, session_id, reply_id):
"""
Puts a the parts that make up a packet together and packs them into a byte string
"""
buf = pack('<4H', command, 0, session_id, reply_id) + command_string
buf = unpack('8B' + '%sB' % len(command_string), buf)
checksum = unpack('H', self.__create_checksum(buf))[0]
reply_id += 1
if reply_id >= const.USHRT_MAX:
reply_id -= const.USHRT_MAX
buf = pack('<4H', command, checksum, session_id, reply_id)
return buf + command_string | python | def __create_header(self, command, command_string, session_id, reply_id):
buf = pack('<4H', command, 0, session_id, reply_id) + command_string
buf = unpack('8B' + '%sB' % len(command_string), buf)
checksum = unpack('H', self.__create_checksum(buf))[0]
reply_id += 1
if reply_id >= const.USHRT_MAX:
reply_id -= const.USHRT_MAX
buf = pack('<4H', command, checksum, session_id, reply_id)
return buf + command_string | [
"def",
"__create_header",
"(",
"self",
",",
"command",
",",
"command_string",
",",
"session_id",
",",
"reply_id",
")",
":",
"buf",
"=",
"pack",
"(",
"'<4H'",
",",
"command",
",",
"0",
",",
"session_id",
",",
"reply_id",
")",
"+",
"command_string",
"buf",
... | Puts a the parts that make up a packet together and packs them into a byte string | [
"Puts",
"a",
"the",
"parts",
"that",
"make",
"up",
"a",
"packet",
"together",
"and",
"packs",
"them",
"into",
"a",
"byte",
"string"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L186-L198 |
227,010 | fananimi/pyzk | zk/base.py | ZK.__create_checksum | def __create_checksum(self, p):
"""
Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c
"""
l = len(p)
checksum = 0
while l > 1:
checksum += unpack('H', pack('BB', p[0], p[1]))[0]
p = p[2:]
if checksum > const.USHRT_MAX:
checksum -= const.USHRT_MAX
l -= 2
if l:
checksum = checksum + p[-1]
while checksum > const.USHRT_MAX:
checksum -= const.USHRT_MAX
checksum = ~checksum
while checksum < 0:
checksum += const.USHRT_MAX
return pack('H', checksum) | python | def __create_checksum(self, p):
l = len(p)
checksum = 0
while l > 1:
checksum += unpack('H', pack('BB', p[0], p[1]))[0]
p = p[2:]
if checksum > const.USHRT_MAX:
checksum -= const.USHRT_MAX
l -= 2
if l:
checksum = checksum + p[-1]
while checksum > const.USHRT_MAX:
checksum -= const.USHRT_MAX
checksum = ~checksum
while checksum < 0:
checksum += const.USHRT_MAX
return pack('H', checksum) | [
"def",
"__create_checksum",
"(",
"self",
",",
"p",
")",
":",
"l",
"=",
"len",
"(",
"p",
")",
"checksum",
"=",
"0",
"while",
"l",
">",
"1",
":",
"checksum",
"+=",
"unpack",
"(",
"'H'",
",",
"pack",
"(",
"'BB'",
",",
"p",
"[",
"0",
"]",
",",
"p... | Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c | [
"Calculates",
"the",
"checksum",
"of",
"the",
"packet",
"to",
"be",
"sent",
"to",
"the",
"time",
"clock",
"Copied",
"from",
"zkemsdk",
".",
"c"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L200-L224 |
227,011 | fananimi/pyzk | zk/base.py | ZK.__send_command | def __send_command(self, command, command_string=b'', response_size=8):
"""
send command to the terminal
"""
if command not in [const.CMD_CONNECT, const.CMD_AUTH] and not self.is_connect:
raise ZKErrorConnection("instance are not connected.")
buf = self.__create_header(command, command_string, self.__session_id, self.__reply_id)
try:
if self.tcp:
top = self.__create_tcp_top(buf)
self.__sock.send(top)
self.__tcp_data_recv = self.__sock.recv(response_size + 8)
self.__tcp_length = self.__test_tcp_top(self.__tcp_data_recv)
if self.__tcp_length == 0:
raise ZKNetworkError("TCP packet invalid")
self.__header = unpack('<4H', self.__tcp_data_recv[8:16])
self.__data_recv = self.__tcp_data_recv[8:]
else:
self.__sock.sendto(buf, self.__address)
self.__data_recv = self.__sock.recv(response_size)
self.__header = unpack('<4H', self.__data_recv[:8])
except Exception as e:
raise ZKNetworkError(str(e))
self.__response = self.__header[0]
self.__reply_id = self.__header[3]
self.__data = self.__data_recv[8:]
if self.__response in [const.CMD_ACK_OK, const.CMD_PREPARE_DATA, const.CMD_DATA]:
return {
'status': True,
'code': self.__response
}
return {
'status': False,
'code': self.__response
} | python | def __send_command(self, command, command_string=b'', response_size=8):
if command not in [const.CMD_CONNECT, const.CMD_AUTH] and not self.is_connect:
raise ZKErrorConnection("instance are not connected.")
buf = self.__create_header(command, command_string, self.__session_id, self.__reply_id)
try:
if self.tcp:
top = self.__create_tcp_top(buf)
self.__sock.send(top)
self.__tcp_data_recv = self.__sock.recv(response_size + 8)
self.__tcp_length = self.__test_tcp_top(self.__tcp_data_recv)
if self.__tcp_length == 0:
raise ZKNetworkError("TCP packet invalid")
self.__header = unpack('<4H', self.__tcp_data_recv[8:16])
self.__data_recv = self.__tcp_data_recv[8:]
else:
self.__sock.sendto(buf, self.__address)
self.__data_recv = self.__sock.recv(response_size)
self.__header = unpack('<4H', self.__data_recv[:8])
except Exception as e:
raise ZKNetworkError(str(e))
self.__response = self.__header[0]
self.__reply_id = self.__header[3]
self.__data = self.__data_recv[8:]
if self.__response in [const.CMD_ACK_OK, const.CMD_PREPARE_DATA, const.CMD_DATA]:
return {
'status': True,
'code': self.__response
}
return {
'status': False,
'code': self.__response
} | [
"def",
"__send_command",
"(",
"self",
",",
"command",
",",
"command_string",
"=",
"b''",
",",
"response_size",
"=",
"8",
")",
":",
"if",
"command",
"not",
"in",
"[",
"const",
".",
"CMD_CONNECT",
",",
"const",
".",
"CMD_AUTH",
"]",
"and",
"not",
"self",
... | send command to the terminal | [
"send",
"command",
"to",
"the",
"terminal"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L237-L273 |
227,012 | fananimi/pyzk | zk/base.py | ZK.__ack_ok | def __ack_ok(self):
"""
event ack ok
"""
buf = self.__create_header(const.CMD_ACK_OK, b'', self.__session_id, const.USHRT_MAX - 1)
try:
if self.tcp:
top = self.__create_tcp_top(buf)
self.__sock.send(top)
else:
self.__sock.sendto(buf, self.__address)
except Exception as e:
raise ZKNetworkError(str(e)) | python | def __ack_ok(self):
buf = self.__create_header(const.CMD_ACK_OK, b'', self.__session_id, const.USHRT_MAX - 1)
try:
if self.tcp:
top = self.__create_tcp_top(buf)
self.__sock.send(top)
else:
self.__sock.sendto(buf, self.__address)
except Exception as e:
raise ZKNetworkError(str(e)) | [
"def",
"__ack_ok",
"(",
"self",
")",
":",
"buf",
"=",
"self",
".",
"__create_header",
"(",
"const",
".",
"CMD_ACK_OK",
",",
"b''",
",",
"self",
".",
"__session_id",
",",
"const",
".",
"USHRT_MAX",
"-",
"1",
")",
"try",
":",
"if",
"self",
".",
"tcp",
... | event ack ok | [
"event",
"ack",
"ok"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L275-L287 |
227,013 | fananimi/pyzk | zk/base.py | ZK.__get_data_size | def __get_data_size(self):
"""
Checks a returned packet to see if it returned CMD_PREPARE_DATA,
indicating that data packets are to be sent
Returns the amount of bytes that are going to be sent
"""
response = self.__response
if response == const.CMD_PREPARE_DATA:
size = unpack('I', self.__data[:4])[0]
return size
else:
return 0 | python | def __get_data_size(self):
response = self.__response
if response == const.CMD_PREPARE_DATA:
size = unpack('I', self.__data[:4])[0]
return size
else:
return 0 | [
"def",
"__get_data_size",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"__response",
"if",
"response",
"==",
"const",
".",
"CMD_PREPARE_DATA",
":",
"size",
"=",
"unpack",
"(",
"'I'",
",",
"self",
".",
"__data",
"[",
":",
"4",
"]",
")",
"[",
"... | Checks a returned packet to see if it returned CMD_PREPARE_DATA,
indicating that data packets are to be sent
Returns the amount of bytes that are going to be sent | [
"Checks",
"a",
"returned",
"packet",
"to",
"see",
"if",
"it",
"returned",
"CMD_PREPARE_DATA",
"indicating",
"that",
"data",
"packets",
"are",
"to",
"be",
"sent"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L289-L301 |
227,014 | fananimi/pyzk | zk/base.py | ZK.__decode_time | def __decode_time(self, t):
"""
Decode a timestamp retrieved from the timeclock
copied from zkemsdk.c - DecodeTime
"""
t = unpack("<I", t)[0]
second = t % 60
t = t // 60
minute = t % 60
t = t // 60
hour = t % 24
t = t // 24
day = t % 31 + 1
t = t // 31
month = t % 12 + 1
t = t // 12
year = t + 2000
d = datetime(year, month, day, hour, minute, second)
return d | python | def __decode_time(self, t):
t = unpack("<I", t)[0]
second = t % 60
t = t // 60
minute = t % 60
t = t // 60
hour = t % 24
t = t // 24
day = t % 31 + 1
t = t // 31
month = t % 12 + 1
t = t // 12
year = t + 2000
d = datetime(year, month, day, hour, minute, second)
return d | [
"def",
"__decode_time",
"(",
"self",
",",
"t",
")",
":",
"t",
"=",
"unpack",
"(",
"\"<I\"",
",",
"t",
")",
"[",
"0",
"]",
"second",
"=",
"t",
"%",
"60",
"t",
"=",
"t",
"//",
"60",
"minute",
"=",
"t",
"%",
"60",
"t",
"=",
"t",
"//",
"60",
... | Decode a timestamp retrieved from the timeclock
copied from zkemsdk.c - DecodeTime | [
"Decode",
"a",
"timestamp",
"retrieved",
"from",
"the",
"timeclock"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L309-L336 |
227,015 | fananimi/pyzk | zk/base.py | ZK.__decode_timehex | def __decode_timehex(self, timehex):
"""
timehex string of six bytes
"""
year, month, day, hour, minute, second = unpack("6B", timehex)
year += 2000
d = datetime(year, month, day, hour, minute, second)
return d | python | def __decode_timehex(self, timehex):
year, month, day, hour, minute, second = unpack("6B", timehex)
year += 2000
d = datetime(year, month, day, hour, minute, second)
return d | [
"def",
"__decode_timehex",
"(",
"self",
",",
"timehex",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
"=",
"unpack",
"(",
"\"6B\"",
",",
"timehex",
")",
"year",
"+=",
"2000",
"d",
"=",
"datetime",
"(",
"year",... | timehex string of six bytes | [
"timehex",
"string",
"of",
"six",
"bytes"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L338-L345 |
227,016 | fananimi/pyzk | zk/base.py | ZK.__encode_time | def __encode_time(self, t):
"""
Encode a timestamp so that it can be read on the timeclock
"""
# formula taken from zkemsdk.c - EncodeTime
# can also be found in the technical manual
d = (
((t.year % 100) * 12 * 31 + ((t.month - 1) * 31) + t.day - 1) *
(24 * 60 * 60) + (t.hour * 60 + t.minute) * 60 + t.second
)
return d | python | def __encode_time(self, t):
# formula taken from zkemsdk.c - EncodeTime
# can also be found in the technical manual
d = (
((t.year % 100) * 12 * 31 + ((t.month - 1) * 31) + t.day - 1) *
(24 * 60 * 60) + (t.hour * 60 + t.minute) * 60 + t.second
)
return d | [
"def",
"__encode_time",
"(",
"self",
",",
"t",
")",
":",
"# formula taken from zkemsdk.c - EncodeTime",
"# can also be found in the technical manual",
"d",
"=",
"(",
"(",
"(",
"t",
".",
"year",
"%",
"100",
")",
"*",
"12",
"*",
"31",
"+",
"(",
"(",
"t",
".",
... | Encode a timestamp so that it can be read on the timeclock | [
"Encode",
"a",
"timestamp",
"so",
"that",
"it",
"can",
"be",
"read",
"on",
"the",
"timeclock"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L347-L357 |
227,017 | fananimi/pyzk | zk/base.py | ZK.connect | def connect(self):
"""
connect to the device
:return: bool
"""
self.end_live_capture = False
if not self.ommit_ping and not self.helper.test_ping():
raise ZKNetworkError("can't reach device (ping %s)" % self.__address[0])
if not self.force_udp and self.helper.test_tcp() == 0:
self.user_packet_size = 72 # default zk8
self.__create_socket()
self.__session_id = 0
self.__reply_id = const.USHRT_MAX - 1
cmd_response = self.__send_command(const.CMD_CONNECT)
self.__session_id = self.__header[2]
if cmd_response.get('code') == const.CMD_ACK_UNAUTH:
if self.verbose: print ("try auth")
command_string = make_commkey(self.__password, self.__session_id)
cmd_response = self.__send_command(const.CMD_AUTH, command_string)
if cmd_response.get('status'):
self.is_connect = True
return self
else:
if cmd_response["code"] == const.CMD_ACK_UNAUTH:
raise ZKErrorResponse("Unauthenticated")
if self.verbose: print ("connect err response {} ".format(cmd_response["code"]))
raise ZKErrorResponse("Invalid response: Can't connect") | python | def connect(self):
self.end_live_capture = False
if not self.ommit_ping and not self.helper.test_ping():
raise ZKNetworkError("can't reach device (ping %s)" % self.__address[0])
if not self.force_udp and self.helper.test_tcp() == 0:
self.user_packet_size = 72 # default zk8
self.__create_socket()
self.__session_id = 0
self.__reply_id = const.USHRT_MAX - 1
cmd_response = self.__send_command(const.CMD_CONNECT)
self.__session_id = self.__header[2]
if cmd_response.get('code') == const.CMD_ACK_UNAUTH:
if self.verbose: print ("try auth")
command_string = make_commkey(self.__password, self.__session_id)
cmd_response = self.__send_command(const.CMD_AUTH, command_string)
if cmd_response.get('status'):
self.is_connect = True
return self
else:
if cmd_response["code"] == const.CMD_ACK_UNAUTH:
raise ZKErrorResponse("Unauthenticated")
if self.verbose: print ("connect err response {} ".format(cmd_response["code"]))
raise ZKErrorResponse("Invalid response: Can't connect") | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"end_live_capture",
"=",
"False",
"if",
"not",
"self",
".",
"ommit_ping",
"and",
"not",
"self",
".",
"helper",
".",
"test_ping",
"(",
")",
":",
"raise",
"ZKNetworkError",
"(",
"\"can't reach device (ping ... | connect to the device
:return: bool | [
"connect",
"to",
"the",
"device"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L359-L386 |
227,018 | fananimi/pyzk | zk/base.py | ZK.disconnect | def disconnect(self):
"""
diconnect from the connected device
:return: bool
"""
cmd_response = self.__send_command(const.CMD_EXIT)
if cmd_response.get('status'):
self.is_connect = False
if self.__sock:
self.__sock.close()
return True
else:
raise ZKErrorResponse("can't disconnect") | python | def disconnect(self):
cmd_response = self.__send_command(const.CMD_EXIT)
if cmd_response.get('status'):
self.is_connect = False
if self.__sock:
self.__sock.close()
return True
else:
raise ZKErrorResponse("can't disconnect") | [
"def",
"disconnect",
"(",
"self",
")",
":",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"const",
".",
"CMD_EXIT",
")",
"if",
"cmd_response",
".",
"get",
"(",
"'status'",
")",
":",
"self",
".",
"is_connect",
"=",
"False",
"if",
"self",
".",
... | diconnect from the connected device
:return: bool | [
"diconnect",
"from",
"the",
"connected",
"device"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L388-L401 |
227,019 | fananimi/pyzk | zk/base.py | ZK.enable_device | def enable_device(self):
"""
re-enable the connected device and allow user activity in device again
:return: bool
"""
cmd_response = self.__send_command(const.CMD_ENABLEDEVICE)
if cmd_response.get('status'):
self.is_enabled = True
return True
else:
raise ZKErrorResponse("Can't enable device") | python | def enable_device(self):
cmd_response = self.__send_command(const.CMD_ENABLEDEVICE)
if cmd_response.get('status'):
self.is_enabled = True
return True
else:
raise ZKErrorResponse("Can't enable device") | [
"def",
"enable_device",
"(",
"self",
")",
":",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"const",
".",
"CMD_ENABLEDEVICE",
")",
"if",
"cmd_response",
".",
"get",
"(",
"'status'",
")",
":",
"self",
".",
"is_enabled",
"=",
"True",
"return",
"T... | re-enable the connected device and allow user activity in device again
:return: bool | [
"re",
"-",
"enable",
"the",
"connected",
"device",
"and",
"allow",
"user",
"activity",
"in",
"device",
"again"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L403-L414 |
227,020 | fananimi/pyzk | zk/base.py | ZK.get_device_name | def get_device_name(self):
"""
return the device name
:return: str
"""
command = const.CMD_OPTIONS_RRQ
command_string = b'~DeviceName\x00'
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get('status'):
device = self.__data.split(b'=', 1)[-1].split(b'\x00')[0]
return device.decode()
else:
return "" | python | def get_device_name(self):
command = const.CMD_OPTIONS_RRQ
command_string = b'~DeviceName\x00'
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get('status'):
device = self.__data.split(b'=', 1)[-1].split(b'\x00')[0]
return device.decode()
else:
return "" | [
"def",
"get_device_name",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_OPTIONS_RRQ",
"command_string",
"=",
"b'~DeviceName\\x00'",
"response_size",
"=",
"1024",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",
... | return the device name
:return: str | [
"return",
"the",
"device",
"name"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L486-L501 |
227,021 | fananimi/pyzk | zk/base.py | ZK.get_network_params | def get_network_params(self):
"""
get network params
"""
ip = self.__address[0]
mask = b''
gate = b''
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024)
if cmd_response.get('status'):
ip = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'NetMask\x00', 1024)
if cmd_response.get('status'):
mask = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'GATEIPAddress\x00', 1024)
if cmd_response.get('status'):
gate = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
return {'ip': ip.decode(), 'mask': mask.decode(), 'gateway': gate.decode()} | python | def get_network_params(self):
ip = self.__address[0]
mask = b''
gate = b''
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024)
if cmd_response.get('status'):
ip = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'NetMask\x00', 1024)
if cmd_response.get('status'):
mask = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'GATEIPAddress\x00', 1024)
if cmd_response.get('status'):
gate = (self.__data.split(b'=', 1)[-1].split(b'\x00')[0])
return {'ip': ip.decode(), 'mask': mask.decode(), 'gateway': gate.decode()} | [
"def",
"get_network_params",
"(",
"self",
")",
":",
"ip",
"=",
"self",
".",
"__address",
"[",
"0",
"]",
"mask",
"=",
"b''",
"gate",
"=",
"b''",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"const",
".",
"CMD_OPTIONS_RRQ",
",",
"b'IPAddress\\x00... | get network params | [
"get",
"network",
"params"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L607-L623 |
227,022 | fananimi/pyzk | zk/base.py | ZK.read_sizes | def read_sizes(self):
"""
read the memory ussage
"""
command = const.CMD_GET_FREE_SIZES
response_size = 1024
cmd_response = self.__send_command(command,b'', response_size)
if cmd_response.get('status'):
if self.verbose: print(codecs.encode(self.__data,'hex'))
size = len(self.__data)
if len(self.__data) >= 80:
fields = unpack('20i', self.__data[:80])
self.users = fields[4]
self.fingers = fields[6]
self.records = fields[8]
self.dummy = fields[10] #???
self.cards = fields[12]
self.fingers_cap = fields[14]
self.users_cap = fields[15]
self.rec_cap = fields[16]
self.fingers_av = fields[17]
self.users_av = fields[18]
self.rec_av = fields[19]
self.__data = self.__data[80:]
if len(self.__data) >= 12: #face info
fields = unpack('3i', self.__data[:12]) #dirty hack! we need more information
self.faces = fields[0]
self.faces_cap = fields[2]
return True
else:
raise ZKErrorResponse("can't read sizes") | python | def read_sizes(self):
command = const.CMD_GET_FREE_SIZES
response_size = 1024
cmd_response = self.__send_command(command,b'', response_size)
if cmd_response.get('status'):
if self.verbose: print(codecs.encode(self.__data,'hex'))
size = len(self.__data)
if len(self.__data) >= 80:
fields = unpack('20i', self.__data[:80])
self.users = fields[4]
self.fingers = fields[6]
self.records = fields[8]
self.dummy = fields[10] #???
self.cards = fields[12]
self.fingers_cap = fields[14]
self.users_cap = fields[15]
self.rec_cap = fields[16]
self.fingers_av = fields[17]
self.users_av = fields[18]
self.rec_av = fields[19]
self.__data = self.__data[80:]
if len(self.__data) >= 12: #face info
fields = unpack('3i', self.__data[:12]) #dirty hack! we need more information
self.faces = fields[0]
self.faces_cap = fields[2]
return True
else:
raise ZKErrorResponse("can't read sizes") | [
"def",
"read_sizes",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_GET_FREE_SIZES",
"response_size",
"=",
"1024",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"b''",
",",
"response_size",
")",
"if",
"cmd_response",
".",
... | read the memory ussage | [
"read",
"the",
"memory",
"ussage"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L652-L682 |
227,023 | fananimi/pyzk | zk/base.py | ZK.restart | def restart(self):
"""
restart the device
:return: bool
"""
command = const.CMD_RESTART
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
self.is_connect = False
self.next_uid = 1
return True
else:
raise ZKErrorResponse("can't restart device") | python | def restart(self):
command = const.CMD_RESTART
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
self.is_connect = False
self.next_uid = 1
return True
else:
raise ZKErrorResponse("can't restart device") | [
"def",
"restart",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_RESTART",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
")",
"if",
"cmd_response",
".",
"get",
"(",
"'status'",
")",
":",
"self",
".",
"is_connect",
"=",
"F... | restart the device
:return: bool | [
"restart",
"the",
"device"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L712-L725 |
227,024 | fananimi/pyzk | zk/base.py | ZK.poweroff | def poweroff(self):
"""
shutdown the machine
"""
command = const.CMD_POWEROFF
command_string = b''
response_size = 1032
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get('status'):
self.is_connect = False
self.next_uid = 1
return True
else:
raise ZKErrorResponse("can't poweroff") | python | def poweroff(self):
command = const.CMD_POWEROFF
command_string = b''
response_size = 1032
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get('status'):
self.is_connect = False
self.next_uid = 1
return True
else:
raise ZKErrorResponse("can't poweroff") | [
"def",
"poweroff",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_POWEROFF",
"command_string",
"=",
"b''",
"response_size",
"=",
"1032",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",
",",
"response_size",
... | shutdown the machine | [
"shutdown",
"the",
"machine"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L753-L766 |
227,025 | fananimi/pyzk | zk/base.py | ZK.set_user | def set_user(self, uid=None, name='', privilege=0, password='', group_id='', user_id='', card=0):
"""
create or update user by uid
:param name: name ot the user
:param privilege: check the const.py for reference
:param password: int password
:param group_id: group ID
:param user_id: your own user ID
:param card: card
:return: bool
"""
command = const.CMD_USER_WRQ
if uid is None:
uid = self.next_uid
if not user_id:
user_id = self.next_user_id
if not user_id:
user_id = str(uid) #ZK6 needs uid2 == uid
#TODO: check what happens if name is missing...
if privilege not in [const.USER_DEFAULT, const.USER_ADMIN]:
privilege = const.USER_DEFAULT
privilege = int(privilege)
if self.user_packet_size == 28: #self.firmware == 6:
if not group_id:
group_id = 0
try:
command_string = pack('HB5s8sIxBHI', uid, privilege, password.encode(self.encoding, errors='ignore'), name.encode(self.encoding, errors='ignore'), card, int(group_id), 0, int(user_id))
except Exception as e:
if self.verbose: print("s_h Error pack: %s" % e)
if self.verbose: print("Error pack: %s" % sys.exc_info()[0])
raise ZKErrorResponse("Can't pack user")
else:
name_pad = name.encode(self.encoding, errors='ignore').ljust(24, b'\x00')[:24]
card_str = pack('<I', int(card))[:4]
command_string = pack('HB8s24s4sx7sx24s', uid, privilege, password.encode(self.encoding, errors='ignore'), name_pad, card_str, group_id.encode(), user_id.encode())
response_size = 1024 #TODO check response?
cmd_response = self.__send_command(command, command_string, response_size)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't set user")
self.refresh_data()
if self.next_uid == uid:
self.next_uid += 1 # better recalculate again
if self.next_user_id == user_id:
self.next_user_id = str(self.next_uid) | python | def set_user(self, uid=None, name='', privilege=0, password='', group_id='', user_id='', card=0):
command = const.CMD_USER_WRQ
if uid is None:
uid = self.next_uid
if not user_id:
user_id = self.next_user_id
if not user_id:
user_id = str(uid) #ZK6 needs uid2 == uid
#TODO: check what happens if name is missing...
if privilege not in [const.USER_DEFAULT, const.USER_ADMIN]:
privilege = const.USER_DEFAULT
privilege = int(privilege)
if self.user_packet_size == 28: #self.firmware == 6:
if not group_id:
group_id = 0
try:
command_string = pack('HB5s8sIxBHI', uid, privilege, password.encode(self.encoding, errors='ignore'), name.encode(self.encoding, errors='ignore'), card, int(group_id), 0, int(user_id))
except Exception as e:
if self.verbose: print("s_h Error pack: %s" % e)
if self.verbose: print("Error pack: %s" % sys.exc_info()[0])
raise ZKErrorResponse("Can't pack user")
else:
name_pad = name.encode(self.encoding, errors='ignore').ljust(24, b'\x00')[:24]
card_str = pack('<I', int(card))[:4]
command_string = pack('HB8s24s4sx7sx24s', uid, privilege, password.encode(self.encoding, errors='ignore'), name_pad, card_str, group_id.encode(), user_id.encode())
response_size = 1024 #TODO check response?
cmd_response = self.__send_command(command, command_string, response_size)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't set user")
self.refresh_data()
if self.next_uid == uid:
self.next_uid += 1 # better recalculate again
if self.next_user_id == user_id:
self.next_user_id = str(self.next_uid) | [
"def",
"set_user",
"(",
"self",
",",
"uid",
"=",
"None",
",",
"name",
"=",
"''",
",",
"privilege",
"=",
"0",
",",
"password",
"=",
"''",
",",
"group_id",
"=",
"''",
",",
"user_id",
"=",
"''",
",",
"card",
"=",
"0",
")",
":",
"command",
"=",
"co... | create or update user by uid
:param name: name ot the user
:param privilege: check the const.py for reference
:param password: int password
:param group_id: group ID
:param user_id: your own user ID
:param card: card
:return: bool | [
"create",
"or",
"update",
"user",
"by",
"uid"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L847-L891 |
227,026 | fananimi/pyzk | zk/base.py | ZK.save_user_template | def save_user_template(self, user, fingers=[]):
"""
save user and template
:param user: user
:param fingers: list of finger. (The maximum index 0-9)
"""
if not isinstance(user, User):
users = self.get_users()
tusers = list(filter(lambda x: x.uid==user, users))
if len(tusers) == 1:
user = tusers[0]
else:
tusers = list(filter(lambda x: x.user_id==str(user), users))
if len(tusers) == 1:
user = tusers[0]
else:
raise ZKErrorResponse("Can't find user")
if isinstance(fingers, Finger):
fingers = [fingers]
fpack = b""
table = b""
fnum = 0x10
tstart = 0
for finger in fingers:
tfp = finger.repack_only()
table += pack("<bHbI", 2, user.uid, fnum + finger.fid, tstart)
tstart += len(tfp)
fpack += tfp
if self.user_packet_size == 28:
upack = user.repack29()
else:
upack = user.repack73()
head = pack("III", len(upack), len(table), len(fpack))
packet = head + upack + table + fpack
self._send_with_buffer(packet)
command = 110
command_string = pack('<IHH', 12,0,8)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't save utemp")
self.refresh_data() | python | def save_user_template(self, user, fingers=[]):
if not isinstance(user, User):
users = self.get_users()
tusers = list(filter(lambda x: x.uid==user, users))
if len(tusers) == 1:
user = tusers[0]
else:
tusers = list(filter(lambda x: x.user_id==str(user), users))
if len(tusers) == 1:
user = tusers[0]
else:
raise ZKErrorResponse("Can't find user")
if isinstance(fingers, Finger):
fingers = [fingers]
fpack = b""
table = b""
fnum = 0x10
tstart = 0
for finger in fingers:
tfp = finger.repack_only()
table += pack("<bHbI", 2, user.uid, fnum + finger.fid, tstart)
tstart += len(tfp)
fpack += tfp
if self.user_packet_size == 28:
upack = user.repack29()
else:
upack = user.repack73()
head = pack("III", len(upack), len(table), len(fpack))
packet = head + upack + table + fpack
self._send_with_buffer(packet)
command = 110
command_string = pack('<IHH', 12,0,8)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't save utemp")
self.refresh_data() | [
"def",
"save_user_template",
"(",
"self",
",",
"user",
",",
"fingers",
"=",
"[",
"]",
")",
":",
"if",
"not",
"isinstance",
"(",
"user",
",",
"User",
")",
":",
"users",
"=",
"self",
".",
"get_users",
"(",
")",
"tusers",
"=",
"list",
"(",
"filter",
"... | save user and template
:param user: user
:param fingers: list of finger. (The maximum index 0-9) | [
"save",
"user",
"and",
"template"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L893-L934 |
227,027 | fananimi/pyzk | zk/base.py | ZK.delete_user_template | def delete_user_template(self, uid=0, temp_id=0, user_id=''):
"""
Delete specific template
:param uid: user ID that are generated from device
:param user_id: your own user ID
:return: bool
"""
if self.tcp and user_id:
command = 134
command_string = pack('<24sB', str(user_id), temp_id)
cmd_response = self.__send_command(command, command_string)
if cmd_response.get('status'):
return True
else:
return False # probably empty!
if not uid:
users = self.get_users()
users = list(filter(lambda x: x.user_id==str(user_id), users))
if not users:
return False
uid = users[0].uid
command = const.CMD_DELETE_USERTEMP
command_string = pack('hb', uid, temp_id)
cmd_response = self.__send_command(command, command_string)
if cmd_response.get('status'):
return True #refres_data (1013)?
else:
return False | python | def delete_user_template(self, uid=0, temp_id=0, user_id=''):
if self.tcp and user_id:
command = 134
command_string = pack('<24sB', str(user_id), temp_id)
cmd_response = self.__send_command(command, command_string)
if cmd_response.get('status'):
return True
else:
return False # probably empty!
if not uid:
users = self.get_users()
users = list(filter(lambda x: x.user_id==str(user_id), users))
if not users:
return False
uid = users[0].uid
command = const.CMD_DELETE_USERTEMP
command_string = pack('hb', uid, temp_id)
cmd_response = self.__send_command(command, command_string)
if cmd_response.get('status'):
return True #refres_data (1013)?
else:
return False | [
"def",
"delete_user_template",
"(",
"self",
",",
"uid",
"=",
"0",
",",
"temp_id",
"=",
"0",
",",
"user_id",
"=",
"''",
")",
":",
"if",
"self",
".",
"tcp",
"and",
"user_id",
":",
"command",
"=",
"134",
"command_string",
"=",
"pack",
"(",
"'<24sB'",
",... | Delete specific template
:param uid: user ID that are generated from device
:param user_id: your own user ID
:return: bool | [
"Delete",
"specific",
"template"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L962-L990 |
227,028 | fananimi/pyzk | zk/base.py | ZK.delete_user | def delete_user(self, uid=0, user_id=''):
"""
delete specific user by uid or user_id
:param uid: user ID that are generated from device
:param user_id: your own user ID
:return: bool
"""
if not uid:
users = self.get_users()
users = list(filter(lambda x: x.user_id==str(user_id), users))
if not users:
return False
uid = users[0].uid
command = const.CMD_DELETE_USER
command_string = pack('h', uid)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't delete user")
self.refresh_data()
if uid == (self.next_uid - 1):
self.next_uid = uid | python | def delete_user(self, uid=0, user_id=''):
if not uid:
users = self.get_users()
users = list(filter(lambda x: x.user_id==str(user_id), users))
if not users:
return False
uid = users[0].uid
command = const.CMD_DELETE_USER
command_string = pack('h', uid)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("Can't delete user")
self.refresh_data()
if uid == (self.next_uid - 1):
self.next_uid = uid | [
"def",
"delete_user",
"(",
"self",
",",
"uid",
"=",
"0",
",",
"user_id",
"=",
"''",
")",
":",
"if",
"not",
"uid",
":",
"users",
"=",
"self",
".",
"get_users",
"(",
")",
"users",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"us... | delete specific user by uid or user_id
:param uid: user ID that are generated from device
:param user_id: your own user ID
:return: bool | [
"delete",
"specific",
"user",
"by",
"uid",
"or",
"user_id"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L992-L1013 |
227,029 | fananimi/pyzk | zk/base.py | ZK.cancel_capture | def cancel_capture(self):
"""
cancel capturing finger
:return: bool
"""
command = const.CMD_CANCELCAPTURE
cmd_response = self.__send_command(command)
return bool(cmd_response.get('status')) | python | def cancel_capture(self):
command = const.CMD_CANCELCAPTURE
cmd_response = self.__send_command(command)
return bool(cmd_response.get('status')) | [
"def",
"cancel_capture",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_CANCELCAPTURE",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
")",
"return",
"bool",
"(",
"cmd_response",
".",
"get",
"(",
"'status'",
")",
")"
] | cancel capturing finger
:return: bool | [
"cancel",
"capturing",
"finger"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1128-L1136 |
227,030 | fananimi/pyzk | zk/base.py | ZK.__recieve_tcp_data | def __recieve_tcp_data(self, data_recv, size):
""" data_recv, raw tcp packet
must analyze tcp_length
must return data, broken
"""
data = []
tcp_length = self.__test_tcp_top(data_recv)
if self.verbose: print ("tcp_length {}, size {}".format(tcp_length, size))
if tcp_length <= 0:
if self.verbose: print ("Incorrect tcp packet")
return None, b""
if (tcp_length - 8) < size:
if self.verbose: print ("tcp length too small... retrying")
resp, bh = self.__recieve_tcp_data(data_recv, tcp_length - 8)
data.append(resp)
size -= len(resp)
if self.verbose: print ("new tcp DATA packet to fill misssing {}".format(size))
data_recv = bh + self.__sock.recv(size + 16 )
if self.verbose: print ("new tcp DATA starting with {} bytes".format(len(data_recv)))
resp, bh = self.__recieve_tcp_data(data_recv, size)
data.append(resp)
if self.verbose: print ("for misssing {} recieved {} with extra {}".format(size, len(resp), len(bh)))
return b''.join(data), bh
recieved = len(data_recv)
if self.verbose: print ("recieved {}, size {}".format(recieved, size))
response = unpack('HHHH', data_recv[8:16])[0]
if recieved >= (size + 32):
if response == const.CMD_DATA:
resp = data_recv[16 : size + 16]
if self.verbose: print ("resp complete len {}".format(len(resp)))
return resp, data_recv[size + 16:]
else:
if self.verbose: print("incorrect response!!! {}".format(response))
return None, b""
else:
if self.verbose: print ("try DATA incomplete (actual valid {})".format(recieved-16))
data.append(data_recv[16 : size + 16 ])
size -= recieved - 16
broken_header = b""
if size < 0:
broken_header = data_recv[size:]
if self.verbose: print ("broken", (broken_header).encode('hex'))
if size > 0:
data_recv = self.__recieve_raw_data(size)
data.append(data_recv)
return b''.join(data), broken_header | python | def __recieve_tcp_data(self, data_recv, size):
data = []
tcp_length = self.__test_tcp_top(data_recv)
if self.verbose: print ("tcp_length {}, size {}".format(tcp_length, size))
if tcp_length <= 0:
if self.verbose: print ("Incorrect tcp packet")
return None, b""
if (tcp_length - 8) < size:
if self.verbose: print ("tcp length too small... retrying")
resp, bh = self.__recieve_tcp_data(data_recv, tcp_length - 8)
data.append(resp)
size -= len(resp)
if self.verbose: print ("new tcp DATA packet to fill misssing {}".format(size))
data_recv = bh + self.__sock.recv(size + 16 )
if self.verbose: print ("new tcp DATA starting with {} bytes".format(len(data_recv)))
resp, bh = self.__recieve_tcp_data(data_recv, size)
data.append(resp)
if self.verbose: print ("for misssing {} recieved {} with extra {}".format(size, len(resp), len(bh)))
return b''.join(data), bh
recieved = len(data_recv)
if self.verbose: print ("recieved {}, size {}".format(recieved, size))
response = unpack('HHHH', data_recv[8:16])[0]
if recieved >= (size + 32):
if response == const.CMD_DATA:
resp = data_recv[16 : size + 16]
if self.verbose: print ("resp complete len {}".format(len(resp)))
return resp, data_recv[size + 16:]
else:
if self.verbose: print("incorrect response!!! {}".format(response))
return None, b""
else:
if self.verbose: print ("try DATA incomplete (actual valid {})".format(recieved-16))
data.append(data_recv[16 : size + 16 ])
size -= recieved - 16
broken_header = b""
if size < 0:
broken_header = data_recv[size:]
if self.verbose: print ("broken", (broken_header).encode('hex'))
if size > 0:
data_recv = self.__recieve_raw_data(size)
data.append(data_recv)
return b''.join(data), broken_header | [
"def",
"__recieve_tcp_data",
"(",
"self",
",",
"data_recv",
",",
"size",
")",
":",
"data",
"=",
"[",
"]",
"tcp_length",
"=",
"self",
".",
"__test_tcp_top",
"(",
"data_recv",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"tcp_length {}, size {}\"",
... | data_recv, raw tcp packet
must analyze tcp_length
must return data, broken | [
"data_recv",
"raw",
"tcp",
"packet",
"must",
"analyze",
"tcp_length"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1349-L1395 |
227,031 | fananimi/pyzk | zk/base.py | ZK.__recieve_raw_data | def __recieve_raw_data(self, size):
""" partial data ? """
data = []
if self.verbose: print ("expecting {} bytes raw data".format(size))
while size > 0:
data_recv = self.__sock.recv(size)
recieved = len(data_recv)
if self.verbose: print ("partial recv {}".format(recieved))
if recieved < 100 and self.verbose: print (" recv {}".format(codecs.encode(data_recv, 'hex')))
data.append(data_recv)
size -= recieved
if self.verbose: print ("still need {}".format(size))
return b''.join(data) | python | def __recieve_raw_data(self, size):
data = []
if self.verbose: print ("expecting {} bytes raw data".format(size))
while size > 0:
data_recv = self.__sock.recv(size)
recieved = len(data_recv)
if self.verbose: print ("partial recv {}".format(recieved))
if recieved < 100 and self.verbose: print (" recv {}".format(codecs.encode(data_recv, 'hex')))
data.append(data_recv)
size -= recieved
if self.verbose: print ("still need {}".format(size))
return b''.join(data) | [
"def",
"__recieve_raw_data",
"(",
"self",
",",
"size",
")",
":",
"data",
"=",
"[",
"]",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"expecting {} bytes raw data\"",
".",
"format",
"(",
"size",
")",
")",
"while",
"size",
">",
"0",
":",
"data_recv",... | partial data ? | [
"partial",
"data",
"?"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1397-L1409 |
227,032 | fananimi/pyzk | zk/base.py | ZK.__read_chunk | def __read_chunk(self, start, size):
"""
read a chunk from buffer
"""
for _retries in range(3):
command = 1504
command_string = pack('<ii', start, size)
if self.tcp:
response_size = size + 32
else:
response_size = 1024 + 8
cmd_response = self.__send_command(command, command_string, response_size)
data = self.__recieve_chunk()
if data is not None:
return data
else:
raise ZKErrorResponse("can't read chunk %i:[%i]" % (start, size)) | python | def __read_chunk(self, start, size):
for _retries in range(3):
command = 1504
command_string = pack('<ii', start, size)
if self.tcp:
response_size = size + 32
else:
response_size = 1024 + 8
cmd_response = self.__send_command(command, command_string, response_size)
data = self.__recieve_chunk()
if data is not None:
return data
else:
raise ZKErrorResponse("can't read chunk %i:[%i]" % (start, size)) | [
"def",
"__read_chunk",
"(",
"self",
",",
"start",
",",
"size",
")",
":",
"for",
"_retries",
"in",
"range",
"(",
"3",
")",
":",
"command",
"=",
"1504",
"command_string",
"=",
"pack",
"(",
"'<ii'",
",",
"start",
",",
"size",
")",
"if",
"self",
".",
"... | read a chunk from buffer | [
"read",
"a",
"chunk",
"from",
"buffer"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1477-L1493 |
227,033 | fananimi/pyzk | zk/base.py | ZK.clear_attendance | def clear_attendance(self):
"""
clear all attendance record
:return: bool
"""
command = const.CMD_CLEAR_ATTLOG
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
return True
else:
raise ZKErrorResponse("Can't clear response") | python | def clear_attendance(self):
command = const.CMD_CLEAR_ATTLOG
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
return True
else:
raise ZKErrorResponse("Can't clear response") | [
"def",
"clear_attendance",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_CLEAR_ATTLOG",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
")",
"if",
"cmd_response",
".",
"get",
"(",
"'status'",
")",
":",
"return",
"True",
"else"... | clear all attendance record
:return: bool | [
"clear",
"all",
"attendance",
"record"
] | 1a765d616526efdcb4c9adfcc9b1d10f6ed8b938 | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1607-L1618 |
227,034 | python-security/pyt | pyt/cfg/stmt_visitor_helper.py | _connect_control_flow_node | def _connect_control_flow_node(control_flow_node, next_node):
"""Connect a ControlFlowNode properly to the next_node."""
for last in control_flow_node.last_nodes:
if isinstance(next_node, ControlFlowNode):
last.connect(next_node.test) # connect to next if test case
elif isinstance(next_node, AssignmentCallNode):
call_node = next_node.call_node
inner_most_call_node = _get_inner_most_function_call(call_node)
last.connect(inner_most_call_node)
else:
last.connect(next_node) | python | def _connect_control_flow_node(control_flow_node, next_node):
for last in control_flow_node.last_nodes:
if isinstance(next_node, ControlFlowNode):
last.connect(next_node.test) # connect to next if test case
elif isinstance(next_node, AssignmentCallNode):
call_node = next_node.call_node
inner_most_call_node = _get_inner_most_function_call(call_node)
last.connect(inner_most_call_node)
else:
last.connect(next_node) | [
"def",
"_connect_control_flow_node",
"(",
"control_flow_node",
",",
"next_node",
")",
":",
"for",
"last",
"in",
"control_flow_node",
".",
"last_nodes",
":",
"if",
"isinstance",
"(",
"next_node",
",",
"ControlFlowNode",
")",
":",
"last",
".",
"connect",
"(",
"nex... | Connect a ControlFlowNode properly to the next_node. | [
"Connect",
"a",
"ControlFlowNode",
"properly",
"to",
"the",
"next_node",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L48-L58 |
227,035 | python-security/pyt | pyt/cfg/stmt_visitor_helper.py | connect_nodes | def connect_nodes(nodes):
"""Connect the nodes in a list linearly."""
for n, next_node in zip(nodes, nodes[1:]):
if isinstance(n, ControlFlowNode):
_connect_control_flow_node(n, next_node)
elif isinstance(next_node, ControlFlowNode):
n.connect(next_node.test)
elif isinstance(next_node, RestoreNode):
continue
elif CALL_IDENTIFIER in next_node.label:
continue
else:
n.connect(next_node) | python | def connect_nodes(nodes):
for n, next_node in zip(nodes, nodes[1:]):
if isinstance(n, ControlFlowNode):
_connect_control_flow_node(n, next_node)
elif isinstance(next_node, ControlFlowNode):
n.connect(next_node.test)
elif isinstance(next_node, RestoreNode):
continue
elif CALL_IDENTIFIER in next_node.label:
continue
else:
n.connect(next_node) | [
"def",
"connect_nodes",
"(",
"nodes",
")",
":",
"for",
"n",
",",
"next_node",
"in",
"zip",
"(",
"nodes",
",",
"nodes",
"[",
"1",
":",
"]",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"ControlFlowNode",
")",
":",
"_connect_control_flow_node",
"(",
"n",... | Connect the nodes in a list linearly. | [
"Connect",
"the",
"nodes",
"in",
"a",
"list",
"linearly",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L61-L73 |
227,036 | python-security/pyt | pyt/cfg/stmt_visitor_helper.py | _get_names | def _get_names(node, result):
"""Recursively finds all names."""
if isinstance(node, ast.Name):
return node.id + result
elif isinstance(node, ast.Subscript):
return result
elif isinstance(node, ast.Starred):
return _get_names(node.value, result)
else:
return _get_names(node.value, result + '.' + node.attr) | python | def _get_names(node, result):
if isinstance(node, ast.Name):
return node.id + result
elif isinstance(node, ast.Subscript):
return result
elif isinstance(node, ast.Starred):
return _get_names(node.value, result)
else:
return _get_names(node.value, result + '.' + node.attr) | [
"def",
"_get_names",
"(",
"node",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Name",
")",
":",
"return",
"node",
".",
"id",
"+",
"result",
"elif",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Subscript",
")",
":",
"r... | Recursively finds all names. | [
"Recursively",
"finds",
"all",
"names",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L76-L85 |
227,037 | python-security/pyt | pyt/cfg/stmt_visitor_helper.py | extract_left_hand_side | def extract_left_hand_side(target):
"""Extract the left hand side variable from a target.
Removes list indexes, stars and other left hand side elements.
"""
left_hand_side = _get_names(target, '')
left_hand_side.replace('*', '')
if '[' in left_hand_side:
index = left_hand_side.index('[')
left_hand_side = target[:index]
return left_hand_side | python | def extract_left_hand_side(target):
left_hand_side = _get_names(target, '')
left_hand_side.replace('*', '')
if '[' in left_hand_side:
index = left_hand_side.index('[')
left_hand_side = target[:index]
return left_hand_side | [
"def",
"extract_left_hand_side",
"(",
"target",
")",
":",
"left_hand_side",
"=",
"_get_names",
"(",
"target",
",",
"''",
")",
"left_hand_side",
".",
"replace",
"(",
"'*'",
",",
"''",
")",
"if",
"'['",
"in",
"left_hand_side",
":",
"index",
"=",
"left_hand_sid... | Extract the left hand side variable from a target.
Removes list indexes, stars and other left hand side elements. | [
"Extract",
"the",
"left",
"hand",
"side",
"variable",
"from",
"a",
"target",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L88-L100 |
227,038 | python-security/pyt | pyt/cfg/stmt_visitor_helper.py | get_first_node | def get_first_node(
node,
node_not_to_step_past
):
"""
This is a super hacky way of getting the first node after a statement.
We do this because we visit a statement and keep on visiting and get something in return that is rarely the first node.
So we loop and loop backwards until we hit the statement or there is nothing to step back to.
"""
ingoing = None
i = 0
current_node = node
while current_node.ingoing:
# This is used because there may be multiple ingoing and loop will cause an infinite loop if we did [0]
i = random.randrange(len(current_node.ingoing))
# e.g. We don't want to step past the Except of an Except basic block
if current_node.ingoing[i] == node_not_to_step_past:
break
ingoing = current_node.ingoing
current_node = current_node.ingoing[i]
if ingoing:
return ingoing[i]
return current_node | python | def get_first_node(
node,
node_not_to_step_past
):
ingoing = None
i = 0
current_node = node
while current_node.ingoing:
# This is used because there may be multiple ingoing and loop will cause an infinite loop if we did [0]
i = random.randrange(len(current_node.ingoing))
# e.g. We don't want to step past the Except of an Except basic block
if current_node.ingoing[i] == node_not_to_step_past:
break
ingoing = current_node.ingoing
current_node = current_node.ingoing[i]
if ingoing:
return ingoing[i]
return current_node | [
"def",
"get_first_node",
"(",
"node",
",",
"node_not_to_step_past",
")",
":",
"ingoing",
"=",
"None",
"i",
"=",
"0",
"current_node",
"=",
"node",
"while",
"current_node",
".",
"ingoing",
":",
"# This is used because there may be multiple ingoing and loop will cause an inf... | This is a super hacky way of getting the first node after a statement.
We do this because we visit a statement and keep on visiting and get something in return that is rarely the first node.
So we loop and loop backwards until we hit the statement or there is nothing to step back to. | [
"This",
"is",
"a",
"super",
"hacky",
"way",
"of",
"getting",
"the",
"first",
"node",
"after",
"a",
"statement",
".",
"We",
"do",
"this",
"because",
"we",
"visit",
"a",
"statement",
"and",
"keep",
"on",
"visiting",
"and",
"get",
"something",
"in",
"return... | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L103-L125 |
227,039 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.handle_or_else | def handle_or_else(self, orelse, test):
"""Handle the orelse part of an if or try node.
Args:
orelse(list[Node])
test(Node)
Returns:
The last nodes of the orelse branch.
"""
if isinstance(orelse[0], ast.If):
control_flow_node = self.visit(orelse[0])
# Prefix the if label with 'el'
control_flow_node.test.label = 'el' + control_flow_node.test.label
test.connect(control_flow_node.test)
return control_flow_node.last_nodes
else:
else_connect_statements = self.stmt_star_handler(
orelse,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(else_connect_statements.first_statement)
return else_connect_statements.last_statements | python | def handle_or_else(self, orelse, test):
if isinstance(orelse[0], ast.If):
control_flow_node = self.visit(orelse[0])
# Prefix the if label with 'el'
control_flow_node.test.label = 'el' + control_flow_node.test.label
test.connect(control_flow_node.test)
return control_flow_node.last_nodes
else:
else_connect_statements = self.stmt_star_handler(
orelse,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(else_connect_statements.first_statement)
return else_connect_statements.last_statements | [
"def",
"handle_or_else",
"(",
"self",
",",
"orelse",
",",
"test",
")",
":",
"if",
"isinstance",
"(",
"orelse",
"[",
"0",
"]",
",",
"ast",
".",
"If",
")",
":",
"control_flow_node",
"=",
"self",
".",
"visit",
"(",
"orelse",
"[",
"0",
"]",
")",
"# Pre... | Handle the orelse part of an if or try node.
Args:
orelse(list[Node])
test(Node)
Returns:
The last nodes of the orelse branch. | [
"Handle",
"the",
"orelse",
"part",
"of",
"an",
"if",
"or",
"try",
"node",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L193-L216 |
227,040 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.assignment_call_node | def assignment_call_node(self, left_hand_label, ast_node):
"""Handle assignments that contain a function call on its right side."""
self.undecided = True # Used for handling functions in assignments
call = self.visit(ast_node.value)
call_label = call.left_hand_side
call_assignment = AssignmentCallNode(
left_hand_label + ' = ' + call_label,
left_hand_label,
ast_node,
[call.left_hand_side],
line_number=ast_node.lineno,
path=self.filenames[-1],
call_node=call
)
call.connect(call_assignment)
self.nodes.append(call_assignment)
self.undecided = False
return call_assignment | python | def assignment_call_node(self, left_hand_label, ast_node):
self.undecided = True # Used for handling functions in assignments
call = self.visit(ast_node.value)
call_label = call.left_hand_side
call_assignment = AssignmentCallNode(
left_hand_label + ' = ' + call_label,
left_hand_label,
ast_node,
[call.left_hand_side],
line_number=ast_node.lineno,
path=self.filenames[-1],
call_node=call
)
call.connect(call_assignment)
self.nodes.append(call_assignment)
self.undecided = False
return call_assignment | [
"def",
"assignment_call_node",
"(",
"self",
",",
"left_hand_label",
",",
"ast_node",
")",
":",
"self",
".",
"undecided",
"=",
"True",
"# Used for handling functions in assignments",
"call",
"=",
"self",
".",
"visit",
"(",
"ast_node",
".",
"value",
")",
"call_label... | Handle assignments that contain a function call on its right side. | [
"Handle",
"assignments",
"that",
"contain",
"a",
"function",
"call",
"on",
"its",
"right",
"side",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L478-L499 |
227,041 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.loop_node_skeleton | def loop_node_skeleton(self, test, node):
"""Common handling of looped structures, while and for."""
body_connect_stmts = self.stmt_star_handler(
node.body,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(body_connect_stmts.first_statement)
test.connect_predecessors(body_connect_stmts.last_statements)
# last_nodes is used for making connections to the next node in the parent node
# this is handled in stmt_star_handler
last_nodes = list()
last_nodes.extend(body_connect_stmts.break_statements)
if node.orelse:
orelse_connect_stmts = self.stmt_star_handler(
node.orelse,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(orelse_connect_stmts.first_statement)
last_nodes.extend(orelse_connect_stmts.last_statements)
else:
last_nodes.append(test) # if there is no orelse, test needs an edge to the next_node
return ControlFlowNode(test, last_nodes, list()) | python | def loop_node_skeleton(self, test, node):
body_connect_stmts = self.stmt_star_handler(
node.body,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(body_connect_stmts.first_statement)
test.connect_predecessors(body_connect_stmts.last_statements)
# last_nodes is used for making connections to the next node in the parent node
# this is handled in stmt_star_handler
last_nodes = list()
last_nodes.extend(body_connect_stmts.break_statements)
if node.orelse:
orelse_connect_stmts = self.stmt_star_handler(
node.orelse,
prev_node_to_avoid=self.nodes[-1]
)
test.connect(orelse_connect_stmts.first_statement)
last_nodes.extend(orelse_connect_stmts.last_statements)
else:
last_nodes.append(test) # if there is no orelse, test needs an edge to the next_node
return ControlFlowNode(test, last_nodes, list()) | [
"def",
"loop_node_skeleton",
"(",
"self",
",",
"test",
",",
"node",
")",
":",
"body_connect_stmts",
"=",
"self",
".",
"stmt_star_handler",
"(",
"node",
".",
"body",
",",
"prev_node_to_avoid",
"=",
"self",
".",
"nodes",
"[",
"-",
"1",
"]",
")",
"test",
".... | Common handling of looped structures, while and for. | [
"Common",
"handling",
"of",
"looped",
"structures",
"while",
"and",
"for",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L517-L543 |
227,042 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.process_loop_funcs | def process_loop_funcs(self, comp_n, loop_node):
"""
If the loop test node contains function calls, it connects the loop node to the nodes of
those function calls.
:param comp_n: The test node of a loop that may contain functions.
:param loop_node: The loop node itself to connect to the new function nodes if any
:return: None
"""
if isinstance(comp_n, ast.Call) and get_call_names_as_string(comp_n.func) in self.function_names:
last_node = self.visit(comp_n)
last_node.connect(loop_node) | python | def process_loop_funcs(self, comp_n, loop_node):
if isinstance(comp_n, ast.Call) and get_call_names_as_string(comp_n.func) in self.function_names:
last_node = self.visit(comp_n)
last_node.connect(loop_node) | [
"def",
"process_loop_funcs",
"(",
"self",
",",
"comp_n",
",",
"loop_node",
")",
":",
"if",
"isinstance",
"(",
"comp_n",
",",
"ast",
".",
"Call",
")",
"and",
"get_call_names_as_string",
"(",
"comp_n",
".",
"func",
")",
"in",
"self",
".",
"function_names",
"... | If the loop test node contains function calls, it connects the loop node to the nodes of
those function calls.
:param comp_n: The test node of a loop that may contain functions.
:param loop_node: The loop node itself to connect to the new function nodes if any
:return: None | [
"If",
"the",
"loop",
"test",
"node",
"contains",
"function",
"calls",
"it",
"connects",
"the",
"loop",
"node",
"to",
"the",
"nodes",
"of",
"those",
"function",
"calls",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L563-L574 |
227,043 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.from_directory_import | def from_directory_import(
self,
module,
real_names,
local_names,
import_alias_mapping,
skip_init=False
):
"""
Directories don't need to be packages.
"""
module_path = module[1]
init_file_location = os.path.join(module_path, '__init__.py')
init_exists = os.path.isfile(init_file_location)
if init_exists and not skip_init:
package_name = os.path.split(module_path)[1]
return self.add_module(
module=(module[0], init_file_location),
module_or_package_name=package_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
is_init=True,
from_from=True
)
for real_name in real_names:
full_name = os.path.join(module_path, real_name)
if os.path.isdir(full_name):
new_init_file_location = os.path.join(full_name, '__init__.py')
if os.path.isfile(new_init_file_location):
self.add_module(
module=(real_name, new_init_file_location),
module_or_package_name=real_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
is_init=True,
from_from=True,
from_fdid=True
)
else:
raise Exception('from anything import directory needs an __init__.py file in directory')
else:
file_module = (real_name, full_name + '.py')
self.add_module(
module=file_module,
module_or_package_name=real_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
from_from=True
)
return IgnoredNode() | python | def from_directory_import(
self,
module,
real_names,
local_names,
import_alias_mapping,
skip_init=False
):
module_path = module[1]
init_file_location = os.path.join(module_path, '__init__.py')
init_exists = os.path.isfile(init_file_location)
if init_exists and not skip_init:
package_name = os.path.split(module_path)[1]
return self.add_module(
module=(module[0], init_file_location),
module_or_package_name=package_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
is_init=True,
from_from=True
)
for real_name in real_names:
full_name = os.path.join(module_path, real_name)
if os.path.isdir(full_name):
new_init_file_location = os.path.join(full_name, '__init__.py')
if os.path.isfile(new_init_file_location):
self.add_module(
module=(real_name, new_init_file_location),
module_or_package_name=real_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
is_init=True,
from_from=True,
from_fdid=True
)
else:
raise Exception('from anything import directory needs an __init__.py file in directory')
else:
file_module = (real_name, full_name + '.py')
self.add_module(
module=file_module,
module_or_package_name=real_name,
local_names=local_names,
import_alias_mapping=import_alias_mapping,
from_from=True
)
return IgnoredNode() | [
"def",
"from_directory_import",
"(",
"self",
",",
"module",
",",
"real_names",
",",
"local_names",
",",
"import_alias_mapping",
",",
"skip_init",
"=",
"False",
")",
":",
"module_path",
"=",
"module",
"[",
"1",
"]",
"init_file_location",
"=",
"os",
".",
"path",... | Directories don't need to be packages. | [
"Directories",
"don",
"t",
"need",
"to",
"be",
"packages",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L909-L960 |
227,044 | python-security/pyt | pyt/cfg/stmt_visitor.py | StmtVisitor.handle_relative_import | def handle_relative_import(self, node):
"""
from A means node.level == 0
from . import B means node.level == 1
from .A means node.level == 1
"""
no_file = os.path.abspath(os.path.join(self.filenames[-1], os.pardir))
skip_init = False
if node.level == 1:
# Same directory as current file
if node.module:
name_with_dir = os.path.join(no_file, node.module.replace('.', '/'))
if not os.path.isdir(name_with_dir):
name_with_dir = name_with_dir + '.py'
# e.g. from . import X
else:
name_with_dir = no_file
# We do not want to analyse the init file of the current directory
skip_init = True
else:
parent = os.path.abspath(os.path.join(no_file, os.pardir))
if node.level > 2:
# Perform extra `cd ..` however many times
for _ in range(0, node.level - 2):
parent = os.path.abspath(os.path.join(parent, os.pardir))
if node.module:
name_with_dir = os.path.join(parent, node.module.replace('.', '/'))
if not os.path.isdir(name_with_dir):
name_with_dir = name_with_dir + '.py'
# e.g. from .. import X
else:
name_with_dir = parent
# Is it a file?
if name_with_dir.endswith('.py'):
return self.add_module(
module=(node.module, name_with_dir),
module_or_package_name=None,
local_names=as_alias_handler(node.names),
import_alias_mapping=retrieve_import_alias_mapping(node.names),
from_from=True
)
return self.from_directory_import(
(node.module, name_with_dir),
not_as_alias_handler(node.names),
as_alias_handler(node.names),
retrieve_import_alias_mapping(node.names),
skip_init=skip_init
) | python | def handle_relative_import(self, node):
no_file = os.path.abspath(os.path.join(self.filenames[-1], os.pardir))
skip_init = False
if node.level == 1:
# Same directory as current file
if node.module:
name_with_dir = os.path.join(no_file, node.module.replace('.', '/'))
if not os.path.isdir(name_with_dir):
name_with_dir = name_with_dir + '.py'
# e.g. from . import X
else:
name_with_dir = no_file
# We do not want to analyse the init file of the current directory
skip_init = True
else:
parent = os.path.abspath(os.path.join(no_file, os.pardir))
if node.level > 2:
# Perform extra `cd ..` however many times
for _ in range(0, node.level - 2):
parent = os.path.abspath(os.path.join(parent, os.pardir))
if node.module:
name_with_dir = os.path.join(parent, node.module.replace('.', '/'))
if not os.path.isdir(name_with_dir):
name_with_dir = name_with_dir + '.py'
# e.g. from .. import X
else:
name_with_dir = parent
# Is it a file?
if name_with_dir.endswith('.py'):
return self.add_module(
module=(node.module, name_with_dir),
module_or_package_name=None,
local_names=as_alias_handler(node.names),
import_alias_mapping=retrieve_import_alias_mapping(node.names),
from_from=True
)
return self.from_directory_import(
(node.module, name_with_dir),
not_as_alias_handler(node.names),
as_alias_handler(node.names),
retrieve_import_alias_mapping(node.names),
skip_init=skip_init
) | [
"def",
"handle_relative_import",
"(",
"self",
",",
"node",
")",
":",
"no_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"filenames",
"[",
"-",
"1",
"]",
",",
"os",
".",
"pardir",
")",
")",
"s... | from A means node.level == 0
from . import B means node.level == 1
from .A means node.level == 1 | [
"from",
"A",
"means",
"node",
".",
"level",
"==",
"0",
"from",
".",
"import",
"B",
"means",
"node",
".",
"level",
"==",
"1",
"from",
".",
"A",
"means",
"node",
".",
"level",
"==",
"1"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L977-L1026 |
227,045 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.save_local_scope | def save_local_scope(
self,
line_number,
saved_function_call_index
):
"""Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Returns:
saved_variables(list[SavedVariable])
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
"""
saved_variables = list()
saved_variables_so_far = set()
first_node = None
# Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode
for assignment in [node for node in self.nodes
if (type(node) == AssignmentNode or
type(node) == AssignmentCallNode or
type(Node) == BBorBInode)]: # type() is used on purpose here
if assignment.left_hand_side in saved_variables_so_far:
continue
saved_variables_so_far.add(assignment.left_hand_side)
save_name = 'save_{}_{}'.format(saved_function_call_index, assignment.left_hand_side)
previous_node = self.nodes[-1]
saved_scope_node = RestoreNode(
save_name + ' = ' + assignment.left_hand_side,
save_name,
[assignment.left_hand_side],
line_number=line_number,
path=self.filenames[-1]
)
if not first_node:
first_node = saved_scope_node
self.nodes.append(saved_scope_node)
# Save LHS
saved_variables.append(SavedVariable(LHS=save_name,
RHS=assignment.left_hand_side))
self.connect_if_allowed(previous_node, saved_scope_node)
return (saved_variables, first_node) | python | def save_local_scope(
self,
line_number,
saved_function_call_index
):
saved_variables = list()
saved_variables_so_far = set()
first_node = None
# Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode
for assignment in [node for node in self.nodes
if (type(node) == AssignmentNode or
type(node) == AssignmentCallNode or
type(Node) == BBorBInode)]: # type() is used on purpose here
if assignment.left_hand_side in saved_variables_so_far:
continue
saved_variables_so_far.add(assignment.left_hand_side)
save_name = 'save_{}_{}'.format(saved_function_call_index, assignment.left_hand_side)
previous_node = self.nodes[-1]
saved_scope_node = RestoreNode(
save_name + ' = ' + assignment.left_hand_side,
save_name,
[assignment.left_hand_side],
line_number=line_number,
path=self.filenames[-1]
)
if not first_node:
first_node = saved_scope_node
self.nodes.append(saved_scope_node)
# Save LHS
saved_variables.append(SavedVariable(LHS=save_name,
RHS=assignment.left_hand_side))
self.connect_if_allowed(previous_node, saved_scope_node)
return (saved_variables, first_node) | [
"def",
"save_local_scope",
"(",
"self",
",",
"line_number",
",",
"saved_function_call_index",
")",
":",
"saved_variables",
"=",
"list",
"(",
")",
"saved_variables_so_far",
"=",
"set",
"(",
")",
"first_node",
"=",
"None",
"# Make e.g. save_N_LHS = assignment.LHS for each... | Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Returns:
saved_variables(list[SavedVariable])
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function. | [
"Save",
"the",
"local",
"scope",
"before",
"entering",
"a",
"function",
"call",
"by",
"saving",
"all",
"the",
"LHS",
"s",
"of",
"assignments",
"so",
"far",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L198-L245 |
227,046 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.save_def_args_in_temp | def save_def_args_in_temp(
self,
call_args,
def_args,
line_number,
saved_function_call_index,
first_node
):
"""Save the arguments of the definition being called. Visit the arguments if they're calls.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the call being made.
saved_function_call_index(int): Unique number for each call.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
args_mapping(dict): A mapping of call argument to definition argument.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
"""
args_mapping = dict()
last_return_value_of_nested_call = None
# Create e.g. temp_N_def_arg1 = call_arg1_label_visitor.result for each argument
for i, call_arg in enumerate(call_args):
# If this results in an IndexError it is invalid Python
def_arg_temp_name = 'temp_' + str(saved_function_call_index) + '_' + def_args[i]
return_value_of_nested_call = None
if isinstance(call_arg, ast.Call):
return_value_of_nested_call = self.visit(call_arg)
restore_node = RestoreNode(
def_arg_temp_name + ' = ' + return_value_of_nested_call.left_hand_side,
def_arg_temp_name,
[return_value_of_nested_call.left_hand_side],
line_number=line_number,
path=self.filenames[-1]
)
if return_value_of_nested_call in self.blackbox_assignments:
self.blackbox_assignments.add(restore_node)
else:
call_arg_label_visitor = LabelVisitor()
call_arg_label_visitor.visit(call_arg)
call_arg_rhs_visitor = RHSVisitor()
call_arg_rhs_visitor.visit(call_arg)
restore_node = RestoreNode(
def_arg_temp_name + ' = ' + call_arg_label_visitor.result,
def_arg_temp_name,
call_arg_rhs_visitor.result,
line_number=line_number,
path=self.filenames[-1]
)
# If there are no saved variables, then this is the first node
if not first_node:
first_node = restore_node
if isinstance(call_arg, ast.Call):
if last_return_value_of_nested_call:
# connect inner to other_inner in e.g. `outer(inner(image_name), other_inner(image_name))`
if isinstance(return_value_of_nested_call, BBorBInode):
last_return_value_of_nested_call.connect(return_value_of_nested_call)
else:
last_return_value_of_nested_call.connect(return_value_of_nested_call.first_node)
else:
# I should only set this once per loop, inner in e.g. `outer(inner(image_name), other_inner(image_name))`
# (inner_most_call is used when predecessor is a ControlFlowNode in connect_control_flow_node)
if isinstance(return_value_of_nested_call, BBorBInode):
first_node.inner_most_call = return_value_of_nested_call
else:
first_node.inner_most_call = return_value_of_nested_call.first_node
# We purposefully should not set this as the first_node of return_value_of_nested_call, last makes sense
last_return_value_of_nested_call = return_value_of_nested_call
self.connect_if_allowed(self.nodes[-1], restore_node)
self.nodes.append(restore_node)
if isinstance(call_arg, ast.Call):
args_mapping[return_value_of_nested_call.left_hand_side] = def_args[i]
else:
args_mapping[def_args[i]] = call_arg_label_visitor.result
return (args_mapping, first_node) | python | def save_def_args_in_temp(
self,
call_args,
def_args,
line_number,
saved_function_call_index,
first_node
):
args_mapping = dict()
last_return_value_of_nested_call = None
# Create e.g. temp_N_def_arg1 = call_arg1_label_visitor.result for each argument
for i, call_arg in enumerate(call_args):
# If this results in an IndexError it is invalid Python
def_arg_temp_name = 'temp_' + str(saved_function_call_index) + '_' + def_args[i]
return_value_of_nested_call = None
if isinstance(call_arg, ast.Call):
return_value_of_nested_call = self.visit(call_arg)
restore_node = RestoreNode(
def_arg_temp_name + ' = ' + return_value_of_nested_call.left_hand_side,
def_arg_temp_name,
[return_value_of_nested_call.left_hand_side],
line_number=line_number,
path=self.filenames[-1]
)
if return_value_of_nested_call in self.blackbox_assignments:
self.blackbox_assignments.add(restore_node)
else:
call_arg_label_visitor = LabelVisitor()
call_arg_label_visitor.visit(call_arg)
call_arg_rhs_visitor = RHSVisitor()
call_arg_rhs_visitor.visit(call_arg)
restore_node = RestoreNode(
def_arg_temp_name + ' = ' + call_arg_label_visitor.result,
def_arg_temp_name,
call_arg_rhs_visitor.result,
line_number=line_number,
path=self.filenames[-1]
)
# If there are no saved variables, then this is the first node
if not first_node:
first_node = restore_node
if isinstance(call_arg, ast.Call):
if last_return_value_of_nested_call:
# connect inner to other_inner in e.g. `outer(inner(image_name), other_inner(image_name))`
if isinstance(return_value_of_nested_call, BBorBInode):
last_return_value_of_nested_call.connect(return_value_of_nested_call)
else:
last_return_value_of_nested_call.connect(return_value_of_nested_call.first_node)
else:
# I should only set this once per loop, inner in e.g. `outer(inner(image_name), other_inner(image_name))`
# (inner_most_call is used when predecessor is a ControlFlowNode in connect_control_flow_node)
if isinstance(return_value_of_nested_call, BBorBInode):
first_node.inner_most_call = return_value_of_nested_call
else:
first_node.inner_most_call = return_value_of_nested_call.first_node
# We purposefully should not set this as the first_node of return_value_of_nested_call, last makes sense
last_return_value_of_nested_call = return_value_of_nested_call
self.connect_if_allowed(self.nodes[-1], restore_node)
self.nodes.append(restore_node)
if isinstance(call_arg, ast.Call):
args_mapping[return_value_of_nested_call.left_hand_side] = def_args[i]
else:
args_mapping[def_args[i]] = call_arg_label_visitor.result
return (args_mapping, first_node) | [
"def",
"save_def_args_in_temp",
"(",
"self",
",",
"call_args",
",",
"def_args",
",",
"line_number",
",",
"saved_function_call_index",
",",
"first_node",
")",
":",
"args_mapping",
"=",
"dict",
"(",
")",
"last_return_value_of_nested_call",
"=",
"None",
"# Create e.g. te... | Save the arguments of the definition being called. Visit the arguments if they're calls.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the call being made.
saved_function_call_index(int): Unique number for each call.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
args_mapping(dict): A mapping of call argument to definition argument.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function. | [
"Save",
"the",
"arguments",
"of",
"the",
"definition",
"being",
"called",
".",
"Visit",
"the",
"arguments",
"if",
"they",
"re",
"calls",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L247-L329 |
227,047 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.create_local_scope_from_def_args | def create_local_scope_from_def_args(
self,
call_args,
def_args,
line_number,
saved_function_call_index
):
"""Create the local scope before entering the body of a function call.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Note: We do not need a connect_if_allowed because of the
preceding call to save_def_args_in_temp.
"""
# Create e.g. def_arg1 = temp_N_def_arg1 for each argument
for i in range(len(call_args)):
def_arg_local_name = def_args[i]
def_arg_temp_name = 'temp_' + str(saved_function_call_index) + '_' + def_args[i]
local_scope_node = RestoreNode(
def_arg_local_name + ' = ' + def_arg_temp_name,
def_arg_local_name,
[def_arg_temp_name],
line_number=line_number,
path=self.filenames[-1]
)
# Chain the local scope nodes together
self.nodes[-1].connect(local_scope_node)
self.nodes.append(local_scope_node) | python | def create_local_scope_from_def_args(
self,
call_args,
def_args,
line_number,
saved_function_call_index
):
# Create e.g. def_arg1 = temp_N_def_arg1 for each argument
for i in range(len(call_args)):
def_arg_local_name = def_args[i]
def_arg_temp_name = 'temp_' + str(saved_function_call_index) + '_' + def_args[i]
local_scope_node = RestoreNode(
def_arg_local_name + ' = ' + def_arg_temp_name,
def_arg_local_name,
[def_arg_temp_name],
line_number=line_number,
path=self.filenames[-1]
)
# Chain the local scope nodes together
self.nodes[-1].connect(local_scope_node)
self.nodes.append(local_scope_node) | [
"def",
"create_local_scope_from_def_args",
"(",
"self",
",",
"call_args",
",",
"def_args",
",",
"line_number",
",",
"saved_function_call_index",
")",
":",
"# Create e.g. def_arg1 = temp_N_def_arg1 for each argument",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"call_args"... | Create the local scope before entering the body of a function call.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Note: We do not need a connect_if_allowed because of the
preceding call to save_def_args_in_temp. | [
"Create",
"the",
"local",
"scope",
"before",
"entering",
"the",
"body",
"of",
"a",
"function",
"call",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L331-L362 |
227,048 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.visit_and_get_function_nodes | def visit_and_get_function_nodes(
self,
definition,
first_node
):
"""Visits the nodes of a user defined function.
Args:
definition(LocalModuleDefinition): Definition of the function being added.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
the_new_nodes(list[Node]): The nodes added while visiting the function.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
"""
len_before_visiting_func = len(self.nodes)
previous_node = self.nodes[-1]
entry_node = self.append_node(EntryOrExitNode('Function Entry ' +
definition.name))
if not first_node:
first_node = entry_node
self.connect_if_allowed(previous_node, entry_node)
function_body_connect_statements = self.stmt_star_handler(definition.node.body)
entry_node.connect(function_body_connect_statements.first_statement)
exit_node = self.append_node(EntryOrExitNode('Exit ' + definition.name))
exit_node.connect_predecessors(function_body_connect_statements.last_statements)
the_new_nodes = self.nodes[len_before_visiting_func:]
return_connection_handler(the_new_nodes, exit_node)
return (the_new_nodes, first_node) | python | def visit_and_get_function_nodes(
self,
definition,
first_node
):
len_before_visiting_func = len(self.nodes)
previous_node = self.nodes[-1]
entry_node = self.append_node(EntryOrExitNode('Function Entry ' +
definition.name))
if not first_node:
first_node = entry_node
self.connect_if_allowed(previous_node, entry_node)
function_body_connect_statements = self.stmt_star_handler(definition.node.body)
entry_node.connect(function_body_connect_statements.first_statement)
exit_node = self.append_node(EntryOrExitNode('Exit ' + definition.name))
exit_node.connect_predecessors(function_body_connect_statements.last_statements)
the_new_nodes = self.nodes[len_before_visiting_func:]
return_connection_handler(the_new_nodes, exit_node)
return (the_new_nodes, first_node) | [
"def",
"visit_and_get_function_nodes",
"(",
"self",
",",
"definition",
",",
"first_node",
")",
":",
"len_before_visiting_func",
"=",
"len",
"(",
"self",
".",
"nodes",
")",
"previous_node",
"=",
"self",
".",
"nodes",
"[",
"-",
"1",
"]",
"entry_node",
"=",
"se... | Visits the nodes of a user defined function.
Args:
definition(LocalModuleDefinition): Definition of the function being added.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
the_new_nodes(list[Node]): The nodes added while visiting the function.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function. | [
"Visits",
"the",
"nodes",
"of",
"a",
"user",
"defined",
"function",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L364-L396 |
227,049 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.restore_saved_local_scope | def restore_saved_local_scope(
self,
saved_variables,
args_mapping,
line_number
):
"""Restore the previously saved variables to their original values.
Args:
saved_variables(list[SavedVariable])
args_mapping(dict): A mapping of call argument to definition argument.
line_number(int): Of the def of the function call about to be entered into.
Note: We do not need connect_if_allowed because of the
preceding call to save_local_scope.
"""
restore_nodes = list()
for var in saved_variables:
# Is var.RHS a call argument?
if var.RHS in args_mapping:
# If so, use the corresponding definition argument for the RHS of the label.
restore_nodes.append(RestoreNode(
var.RHS + ' = ' + args_mapping[var.RHS],
var.RHS,
[var.LHS],
line_number=line_number,
path=self.filenames[-1]
))
else:
# Create a node for e.g. foo = save_1_foo
restore_nodes.append(RestoreNode(
var.RHS + ' = ' + var.LHS,
var.RHS,
[var.LHS],
line_number=line_number,
path=self.filenames[-1]
))
# Chain the restore nodes
for node, successor in zip(restore_nodes, restore_nodes[1:]):
node.connect(successor)
if restore_nodes:
# Connect the last node to the first restore node
self.nodes[-1].connect(restore_nodes[0])
self.nodes.extend(restore_nodes)
return restore_nodes | python | def restore_saved_local_scope(
self,
saved_variables,
args_mapping,
line_number
):
restore_nodes = list()
for var in saved_variables:
# Is var.RHS a call argument?
if var.RHS in args_mapping:
# If so, use the corresponding definition argument for the RHS of the label.
restore_nodes.append(RestoreNode(
var.RHS + ' = ' + args_mapping[var.RHS],
var.RHS,
[var.LHS],
line_number=line_number,
path=self.filenames[-1]
))
else:
# Create a node for e.g. foo = save_1_foo
restore_nodes.append(RestoreNode(
var.RHS + ' = ' + var.LHS,
var.RHS,
[var.LHS],
line_number=line_number,
path=self.filenames[-1]
))
# Chain the restore nodes
for node, successor in zip(restore_nodes, restore_nodes[1:]):
node.connect(successor)
if restore_nodes:
# Connect the last node to the first restore node
self.nodes[-1].connect(restore_nodes[0])
self.nodes.extend(restore_nodes)
return restore_nodes | [
"def",
"restore_saved_local_scope",
"(",
"self",
",",
"saved_variables",
",",
"args_mapping",
",",
"line_number",
")",
":",
"restore_nodes",
"=",
"list",
"(",
")",
"for",
"var",
"in",
"saved_variables",
":",
"# Is var.RHS a call argument?",
"if",
"var",
".",
"RHS"... | Restore the previously saved variables to their original values.
Args:
saved_variables(list[SavedVariable])
args_mapping(dict): A mapping of call argument to definition argument.
line_number(int): Of the def of the function call about to be entered into.
Note: We do not need connect_if_allowed because of the
preceding call to save_local_scope. | [
"Restore",
"the",
"previously",
"saved",
"variables",
"to",
"their",
"original",
"values",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L398-L445 |
227,050 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.return_handler | def return_handler(
self,
call_node,
function_nodes,
saved_function_call_index,
first_node
):
"""Handle the return from a function during a function call.
Args:
call_node(ast.Call) : The node that calls the definition.
function_nodes(list[Node]): List of nodes of the function being called.
saved_function_call_index(int): Unique number for each call.
first_node(EntryOrExitNode or RestoreNode): Used to connect previous statements to this function.
"""
if any(isinstance(node, YieldNode) for node in function_nodes):
# Presence of a `YieldNode` means that the function is a generator
rhs_prefix = 'yld_'
elif any(isinstance(node, ConnectToExitNode) for node in function_nodes):
# Only `Return`s and `Raise`s can be of type ConnectToExitNode
rhs_prefix = 'ret_'
else:
return # No return value
# Create e.g. ~call_1 = ret_func_foo RestoreNode
LHS = CALL_IDENTIFIER + 'call_' + str(saved_function_call_index)
RHS = rhs_prefix + get_call_names_as_string(call_node.func)
return_node = RestoreNode(
LHS + ' = ' + RHS,
LHS,
[RHS],
line_number=call_node.lineno,
path=self.filenames[-1]
)
return_node.first_node = first_node
self.nodes[-1].connect(return_node)
self.nodes.append(return_node) | python | def return_handler(
self,
call_node,
function_nodes,
saved_function_call_index,
first_node
):
if any(isinstance(node, YieldNode) for node in function_nodes):
# Presence of a `YieldNode` means that the function is a generator
rhs_prefix = 'yld_'
elif any(isinstance(node, ConnectToExitNode) for node in function_nodes):
# Only `Return`s and `Raise`s can be of type ConnectToExitNode
rhs_prefix = 'ret_'
else:
return # No return value
# Create e.g. ~call_1 = ret_func_foo RestoreNode
LHS = CALL_IDENTIFIER + 'call_' + str(saved_function_call_index)
RHS = rhs_prefix + get_call_names_as_string(call_node.func)
return_node = RestoreNode(
LHS + ' = ' + RHS,
LHS,
[RHS],
line_number=call_node.lineno,
path=self.filenames[-1]
)
return_node.first_node = first_node
self.nodes[-1].connect(return_node)
self.nodes.append(return_node) | [
"def",
"return_handler",
"(",
"self",
",",
"call_node",
",",
"function_nodes",
",",
"saved_function_call_index",
",",
"first_node",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"node",
",",
"YieldNode",
")",
"for",
"node",
"in",
"function_nodes",
")",
":",
... | Handle the return from a function during a function call.
Args:
call_node(ast.Call) : The node that calls the definition.
function_nodes(list[Node]): List of nodes of the function being called.
saved_function_call_index(int): Unique number for each call.
first_node(EntryOrExitNode or RestoreNode): Used to connect previous statements to this function. | [
"Handle",
"the",
"return",
"from",
"a",
"function",
"during",
"a",
"function",
"call",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L447-L483 |
227,051 | python-security/pyt | pyt/cfg/expr_visitor.py | ExprVisitor.process_function | def process_function(self, call_node, definition):
"""Processes a user defined function when it is called.
Increments self.function_call_index each time it is called, we can refer to it as N in the comments.
Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode. (save_local_scope)
Create e.g. temp_N_def_arg1 = call_arg1_label_visitor.result for each argument.
Visit the arguments if they're calls. (save_def_args_in_temp)
Create e.g. def_arg1 = temp_N_def_arg1 for each argument. (create_local_scope_from_def_args)
Visit and get function nodes. (visit_and_get_function_nodes)
Loop through each save_N_LHS node and create an e.g.
foo = save_1_foo or, if foo was a call arg, foo = arg_mapping[foo]. (restore_saved_local_scope)
Create e.g. ~call_1 = ret_func_foo RestoreNode. (return_handler)
Notes:
Page 31 in the original thesis, but changed a little.
We don't have to return the ~call_1 = ret_func_foo RestoreNode made in return_handler,
because it's the last node anyway, that we return in this function.
e.g. ret_func_foo gets assigned to visit_Return.
Args:
call_node(ast.Call) : The node that calls the definition.
definition(LocalModuleDefinition): Definition of the function being called.
Returns:
Last node in self.nodes, probably the return of the function appended to self.nodes in return_handler.
"""
self.function_call_index += 1
saved_function_call_index = self.function_call_index
def_node = definition.node
saved_variables, first_node = self.save_local_scope(
def_node.lineno,
saved_function_call_index
)
args_mapping, first_node = self.save_def_args_in_temp(
call_node.args,
Arguments(def_node.args),
call_node.lineno,
saved_function_call_index,
first_node
)
self.filenames.append(definition.path)
self.create_local_scope_from_def_args(
call_node.args,
Arguments(def_node.args),
def_node.lineno,
saved_function_call_index
)
function_nodes, first_node = self.visit_and_get_function_nodes(
definition,
first_node
)
self.filenames.pop() # Should really probably move after restore_saved_local_scope!!!
self.restore_saved_local_scope(
saved_variables,
args_mapping,
def_node.lineno
)
self.return_handler(
call_node,
function_nodes,
saved_function_call_index,
first_node
)
self.function_return_stack.pop()
self.function_definition_stack.pop()
return self.nodes[-1] | python | def process_function(self, call_node, definition):
self.function_call_index += 1
saved_function_call_index = self.function_call_index
def_node = definition.node
saved_variables, first_node = self.save_local_scope(
def_node.lineno,
saved_function_call_index
)
args_mapping, first_node = self.save_def_args_in_temp(
call_node.args,
Arguments(def_node.args),
call_node.lineno,
saved_function_call_index,
first_node
)
self.filenames.append(definition.path)
self.create_local_scope_from_def_args(
call_node.args,
Arguments(def_node.args),
def_node.lineno,
saved_function_call_index
)
function_nodes, first_node = self.visit_and_get_function_nodes(
definition,
first_node
)
self.filenames.pop() # Should really probably move after restore_saved_local_scope!!!
self.restore_saved_local_scope(
saved_variables,
args_mapping,
def_node.lineno
)
self.return_handler(
call_node,
function_nodes,
saved_function_call_index,
first_node
)
self.function_return_stack.pop()
self.function_definition_stack.pop()
return self.nodes[-1] | [
"def",
"process_function",
"(",
"self",
",",
"call_node",
",",
"definition",
")",
":",
"self",
".",
"function_call_index",
"+=",
"1",
"saved_function_call_index",
"=",
"self",
".",
"function_call_index",
"def_node",
"=",
"definition",
".",
"node",
"saved_variables",... | Processes a user defined function when it is called.
Increments self.function_call_index each time it is called, we can refer to it as N in the comments.
Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode. (save_local_scope)
Create e.g. temp_N_def_arg1 = call_arg1_label_visitor.result for each argument.
Visit the arguments if they're calls. (save_def_args_in_temp)
Create e.g. def_arg1 = temp_N_def_arg1 for each argument. (create_local_scope_from_def_args)
Visit and get function nodes. (visit_and_get_function_nodes)
Loop through each save_N_LHS node and create an e.g.
foo = save_1_foo or, if foo was a call arg, foo = arg_mapping[foo]. (restore_saved_local_scope)
Create e.g. ~call_1 = ret_func_foo RestoreNode. (return_handler)
Notes:
Page 31 in the original thesis, but changed a little.
We don't have to return the ~call_1 = ret_func_foo RestoreNode made in return_handler,
because it's the last node anyway, that we return in this function.
e.g. ret_func_foo gets assigned to visit_Return.
Args:
call_node(ast.Call) : The node that calls the definition.
definition(LocalModuleDefinition): Definition of the function being called.
Returns:
Last node in self.nodes, probably the return of the function appended to self.nodes in return_handler. | [
"Processes",
"a",
"user",
"defined",
"function",
"when",
"it",
"is",
"called",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L485-L554 |
227,052 | python-security/pyt | pyt/formatters/screen.py | report | def report(
vulnerabilities,
fileobj,
print_sanitised,
):
"""
Prints issues in color-coded text format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout
"""
n_vulnerabilities = len(vulnerabilities)
unsanitised_vulnerabilities = [v for v in vulnerabilities if not isinstance(v, SanitisedVulnerability)]
n_unsanitised = len(unsanitised_vulnerabilities)
n_sanitised = n_vulnerabilities - n_unsanitised
heading = "{} vulnerabilit{} found{}.\n".format(
'No' if n_unsanitised == 0 else n_unsanitised,
'y' if n_unsanitised == 1 else 'ies',
" (plus {} sanitised)".format(n_sanitised) if n_sanitised else "",
)
vulnerabilities_to_print = vulnerabilities if print_sanitised else unsanitised_vulnerabilities
with fileobj:
for i, vulnerability in enumerate(vulnerabilities_to_print, start=1):
fileobj.write(vulnerability_to_str(i, vulnerability))
if n_unsanitised == 0:
fileobj.write(color(heading, GOOD))
else:
fileobj.write(color(heading, DANGER)) | python | def report(
vulnerabilities,
fileobj,
print_sanitised,
):
n_vulnerabilities = len(vulnerabilities)
unsanitised_vulnerabilities = [v for v in vulnerabilities if not isinstance(v, SanitisedVulnerability)]
n_unsanitised = len(unsanitised_vulnerabilities)
n_sanitised = n_vulnerabilities - n_unsanitised
heading = "{} vulnerabilit{} found{}.\n".format(
'No' if n_unsanitised == 0 else n_unsanitised,
'y' if n_unsanitised == 1 else 'ies',
" (plus {} sanitised)".format(n_sanitised) if n_sanitised else "",
)
vulnerabilities_to_print = vulnerabilities if print_sanitised else unsanitised_vulnerabilities
with fileobj:
for i, vulnerability in enumerate(vulnerabilities_to_print, start=1):
fileobj.write(vulnerability_to_str(i, vulnerability))
if n_unsanitised == 0:
fileobj.write(color(heading, GOOD))
else:
fileobj.write(color(heading, DANGER)) | [
"def",
"report",
"(",
"vulnerabilities",
",",
"fileobj",
",",
"print_sanitised",
",",
")",
":",
"n_vulnerabilities",
"=",
"len",
"(",
"vulnerabilities",
")",
"unsanitised_vulnerabilities",
"=",
"[",
"v",
"for",
"v",
"in",
"vulnerabilities",
"if",
"not",
"isinsta... | Prints issues in color-coded text format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout | [
"Prints",
"issues",
"in",
"color",
"-",
"coded",
"text",
"format",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/formatters/screen.py#L17-L46 |
227,053 | python-security/pyt | pyt/analysis/fixed_point.py | FixedPointAnalysis.fixpoint_runner | def fixpoint_runner(self):
"""Work list algorithm that runs the fixpoint algorithm."""
q = self.cfg.nodes
while q != []:
x_i = constraint_table[q[0]] # x_i = q[0].old_constraint
self.analysis.fixpointmethod(q[0]) # y = F_i(x_1, ..., x_n);
y = constraint_table[q[0]] # y = q[0].new_constraint
if y != x_i:
for node in self.analysis.dep(q[0]): # for (v in dep(v_i))
q.append(node) # q.append(v):
constraint_table[q[0]] = y # q[0].old_constraint = q[0].new_constraint # x_i = y
q = q[1:] | python | def fixpoint_runner(self):
q = self.cfg.nodes
while q != []:
x_i = constraint_table[q[0]] # x_i = q[0].old_constraint
self.analysis.fixpointmethod(q[0]) # y = F_i(x_1, ..., x_n);
y = constraint_table[q[0]] # y = q[0].new_constraint
if y != x_i:
for node in self.analysis.dep(q[0]): # for (v in dep(v_i))
q.append(node) # q.append(v):
constraint_table[q[0]] = y # q[0].old_constraint = q[0].new_constraint # x_i = y
q = q[1:] | [
"def",
"fixpoint_runner",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"cfg",
".",
"nodes",
"while",
"q",
"!=",
"[",
"]",
":",
"x_i",
"=",
"constraint_table",
"[",
"q",
"[",
"0",
"]",
"]",
"# x_i = q[0].old_constraint",
"self",
".",
"analysis",
".",
... | Work list algorithm that runs the fixpoint algorithm. | [
"Work",
"list",
"algorithm",
"that",
"runs",
"the",
"fixpoint",
"algorithm",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/analysis/fixed_point.py#L17-L30 |
227,054 | python-security/pyt | pyt/vulnerabilities/trigger_definitions_parser.py | parse | def parse(trigger_word_file):
"""Parse the file for source and sink definitions.
Returns:
A definitions tuple with sources and sinks.
"""
with open(trigger_word_file) as fd:
triggers_dict = json.load(fd)
sources = [Source(s) for s in triggers_dict['sources']]
sinks = [
Sink.from_json(trigger, data)
for trigger, data in triggers_dict['sinks'].items()
]
return Definitions(sources, sinks) | python | def parse(trigger_word_file):
with open(trigger_word_file) as fd:
triggers_dict = json.load(fd)
sources = [Source(s) for s in triggers_dict['sources']]
sinks = [
Sink.from_json(trigger, data)
for trigger, data in triggers_dict['sinks'].items()
]
return Definitions(sources, sinks) | [
"def",
"parse",
"(",
"trigger_word_file",
")",
":",
"with",
"open",
"(",
"trigger_word_file",
")",
"as",
"fd",
":",
"triggers_dict",
"=",
"json",
".",
"load",
"(",
"fd",
")",
"sources",
"=",
"[",
"Source",
"(",
"s",
")",
"for",
"s",
"in",
"triggers_dic... | Parse the file for source and sink definitions.
Returns:
A definitions tuple with sources and sinks. | [
"Parse",
"the",
"file",
"for",
"source",
"and",
"sink",
"definitions",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/trigger_definitions_parser.py#L69-L82 |
227,055 | python-security/pyt | pyt/core/node_types.py | Node.connect | def connect(self, successor):
"""Connect this node to its successor node by
setting its outgoing and the successors ingoing."""
if isinstance(self, ConnectToExitNode) and not isinstance(successor, EntryOrExitNode):
return
self.outgoing.append(successor)
successor.ingoing.append(self) | python | def connect(self, successor):
if isinstance(self, ConnectToExitNode) and not isinstance(successor, EntryOrExitNode):
return
self.outgoing.append(successor)
successor.ingoing.append(self) | [
"def",
"connect",
"(",
"self",
",",
"successor",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"ConnectToExitNode",
")",
"and",
"not",
"isinstance",
"(",
"successor",
",",
"EntryOrExitNode",
")",
":",
"return",
"self",
".",
"outgoing",
".",
"append",
"("... | Connect this node to its successor node by
setting its outgoing and the successors ingoing. | [
"Connect",
"this",
"node",
"to",
"its",
"successor",
"node",
"by",
"setting",
"its",
"outgoing",
"and",
"the",
"successors",
"ingoing",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/node_types.py#L57-L64 |
227,056 | python-security/pyt | pyt/core/node_types.py | Node.connect_predecessors | def connect_predecessors(self, predecessors):
"""Connect all nodes in predecessors to this node."""
for n in predecessors:
self.ingoing.append(n)
n.outgoing.append(self) | python | def connect_predecessors(self, predecessors):
for n in predecessors:
self.ingoing.append(n)
n.outgoing.append(self) | [
"def",
"connect_predecessors",
"(",
"self",
",",
"predecessors",
")",
":",
"for",
"n",
"in",
"predecessors",
":",
"self",
".",
"ingoing",
".",
"append",
"(",
"n",
")",
"n",
".",
"outgoing",
".",
"append",
"(",
"self",
")"
] | Connect all nodes in predecessors to this node. | [
"Connect",
"all",
"nodes",
"in",
"predecessors",
"to",
"this",
"node",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/node_types.py#L66-L70 |
227,057 | python-security/pyt | pyt/core/module_definitions.py | ModuleDefinitions.append_if_local_or_in_imports | def append_if_local_or_in_imports(self, definition):
"""Add definition to list.
Handles local definitions and adds to project_definitions.
"""
if isinstance(definition, LocalModuleDefinition):
self.definitions.append(definition)
elif self.import_names == ["*"]:
self.definitions.append(definition)
elif self.import_names and definition.name in self.import_names:
self.definitions.append(definition)
elif (self.import_alias_mapping and definition.name in
self.import_alias_mapping.values()):
self.definitions.append(definition)
if definition.parent_module_name:
self.definitions.append(definition)
if definition.node not in project_definitions:
project_definitions[definition.node] = definition | python | def append_if_local_or_in_imports(self, definition):
if isinstance(definition, LocalModuleDefinition):
self.definitions.append(definition)
elif self.import_names == ["*"]:
self.definitions.append(definition)
elif self.import_names and definition.name in self.import_names:
self.definitions.append(definition)
elif (self.import_alias_mapping and definition.name in
self.import_alias_mapping.values()):
self.definitions.append(definition)
if definition.parent_module_name:
self.definitions.append(definition)
if definition.node not in project_definitions:
project_definitions[definition.node] = definition | [
"def",
"append_if_local_or_in_imports",
"(",
"self",
",",
"definition",
")",
":",
"if",
"isinstance",
"(",
"definition",
",",
"LocalModuleDefinition",
")",
":",
"self",
".",
"definitions",
".",
"append",
"(",
"definition",
")",
"elif",
"self",
".",
"import_names... | Add definition to list.
Handles local definitions and adds to project_definitions. | [
"Add",
"definition",
"to",
"list",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/module_definitions.py#L79-L98 |
227,058 | python-security/pyt | pyt/core/module_definitions.py | ModuleDefinitions.get_definition | def get_definition(self, name):
"""Get definitions by name."""
for definition in self.definitions:
if definition.name == name:
return definition | python | def get_definition(self, name):
for definition in self.definitions:
if definition.name == name:
return definition | [
"def",
"get_definition",
"(",
"self",
",",
"name",
")",
":",
"for",
"definition",
"in",
"self",
".",
"definitions",
":",
"if",
"definition",
".",
"name",
"==",
"name",
":",
"return",
"definition"
] | Get definitions by name. | [
"Get",
"definitions",
"by",
"name",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/module_definitions.py#L100-L104 |
227,059 | python-security/pyt | pyt/core/module_definitions.py | ModuleDefinitions.set_definition_node | def set_definition_node(self, node, name):
"""Set definition by name."""
definition = self.get_definition(name)
if definition:
definition.node = node | python | def set_definition_node(self, node, name):
definition = self.get_definition(name)
if definition:
definition.node = node | [
"def",
"set_definition_node",
"(",
"self",
",",
"node",
",",
"name",
")",
":",
"definition",
"=",
"self",
".",
"get_definition",
"(",
"name",
")",
"if",
"definition",
":",
"definition",
".",
"node",
"=",
"node"
] | Set definition by name. | [
"Set",
"definition",
"by",
"name",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/module_definitions.py#L106-L110 |
227,060 | python-security/pyt | pyt/analysis/reaching_definitions_taint.py | ReachingDefinitionsTaintAnalysis.fixpointmethod | def fixpointmethod(self, cfg_node):
"""The most important part of PyT, where we perform
the variant of reaching definitions to find where sources reach.
"""
JOIN = self.join(cfg_node)
# Assignment check
if isinstance(cfg_node, AssignmentNode):
arrow_result = JOIN
# Reassignment check
if cfg_node.left_hand_side not in cfg_node.right_hand_side_variables:
# Get previous assignments of cfg_node.left_hand_side and remove them from JOIN
arrow_result = self.arrow(JOIN, cfg_node.left_hand_side)
arrow_result = arrow_result | self.lattice.el2bv[cfg_node]
constraint_table[cfg_node] = arrow_result
# Default case
else:
constraint_table[cfg_node] = JOIN | python | def fixpointmethod(self, cfg_node):
JOIN = self.join(cfg_node)
# Assignment check
if isinstance(cfg_node, AssignmentNode):
arrow_result = JOIN
# Reassignment check
if cfg_node.left_hand_side not in cfg_node.right_hand_side_variables:
# Get previous assignments of cfg_node.left_hand_side and remove them from JOIN
arrow_result = self.arrow(JOIN, cfg_node.left_hand_side)
arrow_result = arrow_result | self.lattice.el2bv[cfg_node]
constraint_table[cfg_node] = arrow_result
# Default case
else:
constraint_table[cfg_node] = JOIN | [
"def",
"fixpointmethod",
"(",
"self",
",",
"cfg_node",
")",
":",
"JOIN",
"=",
"self",
".",
"join",
"(",
"cfg_node",
")",
"# Assignment check",
"if",
"isinstance",
"(",
"cfg_node",
",",
"AssignmentNode",
")",
":",
"arrow_result",
"=",
"JOIN",
"# Reassignment ch... | The most important part of PyT, where we perform
the variant of reaching definitions to find where sources reach. | [
"The",
"most",
"important",
"part",
"of",
"PyT",
"where",
"we",
"perform",
"the",
"variant",
"of",
"reaching",
"definitions",
"to",
"find",
"where",
"sources",
"reach",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/analysis/reaching_definitions_taint.py#L14-L32 |
227,061 | python-security/pyt | pyt/analysis/reaching_definitions_taint.py | ReachingDefinitionsTaintAnalysis.arrow | def arrow(self, JOIN, _id):
"""Removes all previous assignments from JOIN that have the same left hand side.
This represents the arrow id definition from Schwartzbach."""
r = JOIN
for node in self.lattice.get_elements(JOIN):
if node.left_hand_side == _id:
r = r ^ self.lattice.el2bv[node]
return r | python | def arrow(self, JOIN, _id):
r = JOIN
for node in self.lattice.get_elements(JOIN):
if node.left_hand_side == _id:
r = r ^ self.lattice.el2bv[node]
return r | [
"def",
"arrow",
"(",
"self",
",",
"JOIN",
",",
"_id",
")",
":",
"r",
"=",
"JOIN",
"for",
"node",
"in",
"self",
".",
"lattice",
".",
"get_elements",
"(",
"JOIN",
")",
":",
"if",
"node",
".",
"left_hand_side",
"==",
"_id",
":",
"r",
"=",
"r",
"^",
... | Removes all previous assignments from JOIN that have the same left hand side.
This represents the arrow id definition from Schwartzbach. | [
"Removes",
"all",
"previous",
"assignments",
"from",
"JOIN",
"that",
"have",
"the",
"same",
"left",
"hand",
"side",
".",
"This",
"represents",
"the",
"arrow",
"id",
"definition",
"from",
"Schwartzbach",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/analysis/reaching_definitions_taint.py#L39-L46 |
227,062 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | identify_triggers | def identify_triggers(
cfg,
sources,
sinks,
lattice,
nosec_lines
):
"""Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple.
nosec_lines(set): lines with # nosec whitelisting
Returns:
Triggers tuple with sink and source nodes and a sanitiser node dict.
"""
assignment_nodes = filter_cfg_nodes(cfg, AssignmentNode)
tainted_nodes = filter_cfg_nodes(cfg, TaintedNode)
tainted_trigger_nodes = [
TriggerNode(
Source('Framework function URL parameter'),
cfg_node=node
) for node in tainted_nodes
]
sources_in_file = find_triggers(assignment_nodes, sources, nosec_lines)
sources_in_file.extend(tainted_trigger_nodes)
find_secondary_sources(assignment_nodes, sources_in_file, lattice)
sinks_in_file = find_triggers(cfg.nodes, sinks, nosec_lines)
sanitiser_node_dict = build_sanitiser_node_dict(cfg, sinks_in_file)
return Triggers(sources_in_file, sinks_in_file, sanitiser_node_dict) | python | def identify_triggers(
cfg,
sources,
sinks,
lattice,
nosec_lines
):
assignment_nodes = filter_cfg_nodes(cfg, AssignmentNode)
tainted_nodes = filter_cfg_nodes(cfg, TaintedNode)
tainted_trigger_nodes = [
TriggerNode(
Source('Framework function URL parameter'),
cfg_node=node
) for node in tainted_nodes
]
sources_in_file = find_triggers(assignment_nodes, sources, nosec_lines)
sources_in_file.extend(tainted_trigger_nodes)
find_secondary_sources(assignment_nodes, sources_in_file, lattice)
sinks_in_file = find_triggers(cfg.nodes, sinks, nosec_lines)
sanitiser_node_dict = build_sanitiser_node_dict(cfg, sinks_in_file)
return Triggers(sources_in_file, sinks_in_file, sanitiser_node_dict) | [
"def",
"identify_triggers",
"(",
"cfg",
",",
"sources",
",",
"sinks",
",",
"lattice",
",",
"nosec_lines",
")",
":",
"assignment_nodes",
"=",
"filter_cfg_nodes",
"(",
"cfg",
",",
"AssignmentNode",
")",
"tainted_nodes",
"=",
"filter_cfg_nodes",
"(",
"cfg",
",",
... | Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple.
nosec_lines(set): lines with # nosec whitelisting
Returns:
Triggers tuple with sink and source nodes and a sanitiser node dict. | [
"Identify",
"sources",
"sinks",
"and",
"sanitisers",
"in",
"a",
"CFG",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L30-L65 |
227,063 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | find_secondary_sources | def find_secondary_sources(
assignment_nodes,
sources,
lattice
):
"""
Sets the secondary_nodes attribute of each source in the sources list.
Args:
assignment_nodes([AssignmentNode])
sources([tuple])
lattice(Lattice): the lattice we're analysing.
"""
for source in sources:
source.secondary_nodes = find_assignments(assignment_nodes, source, lattice) | python | def find_secondary_sources(
assignment_nodes,
sources,
lattice
):
for source in sources:
source.secondary_nodes = find_assignments(assignment_nodes, source, lattice) | [
"def",
"find_secondary_sources",
"(",
"assignment_nodes",
",",
"sources",
",",
"lattice",
")",
":",
"for",
"source",
"in",
"sources",
":",
"source",
".",
"secondary_nodes",
"=",
"find_assignments",
"(",
"assignment_nodes",
",",
"source",
",",
"lattice",
")"
] | Sets the secondary_nodes attribute of each source in the sources list.
Args:
assignment_nodes([AssignmentNode])
sources([tuple])
lattice(Lattice): the lattice we're analysing. | [
"Sets",
"the",
"secondary_nodes",
"attribute",
"of",
"each",
"source",
"in",
"the",
"sources",
"list",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L75-L89 |
227,064 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | find_triggers | def find_triggers(
nodes,
trigger_words,
nosec_lines
):
"""Find triggers from the trigger_word_list in the nodes.
Args:
nodes(list[Node]): the nodes to find triggers in.
trigger_word_list(list[Union[Sink, Source]]): list of trigger words to look for.
nosec_lines(set): lines with # nosec whitelisting
Returns:
List of found TriggerNodes
"""
trigger_nodes = list()
for node in nodes:
if node.line_number not in nosec_lines:
trigger_nodes.extend(iter(label_contains(node, trigger_words)))
return trigger_nodes | python | def find_triggers(
nodes,
trigger_words,
nosec_lines
):
trigger_nodes = list()
for node in nodes:
if node.line_number not in nosec_lines:
trigger_nodes.extend(iter(label_contains(node, trigger_words)))
return trigger_nodes | [
"def",
"find_triggers",
"(",
"nodes",
",",
"trigger_words",
",",
"nosec_lines",
")",
":",
"trigger_nodes",
"=",
"list",
"(",
")",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
".",
"line_number",
"not",
"in",
"nosec_lines",
":",
"trigger_nodes",
".",
"e... | Find triggers from the trigger_word_list in the nodes.
Args:
nodes(list[Node]): the nodes to find triggers in.
trigger_word_list(list[Union[Sink, Source]]): list of trigger words to look for.
nosec_lines(set): lines with # nosec whitelisting
Returns:
List of found TriggerNodes | [
"Find",
"triggers",
"from",
"the",
"trigger_word_list",
"in",
"the",
"nodes",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L135-L154 |
227,065 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | label_contains | def label_contains(
node,
triggers
):
"""Determine if node contains any of the trigger_words provided.
Args:
node(Node): CFG node to check.
trigger_words(list[Union[Sink, Source]]): list of trigger words to look for.
Returns:
Iterable of TriggerNodes found. Can be multiple because multiple
trigger_words can be in one node.
"""
for trigger in triggers:
if trigger.trigger_word in node.label:
yield TriggerNode(trigger, node) | python | def label_contains(
node,
triggers
):
for trigger in triggers:
if trigger.trigger_word in node.label:
yield TriggerNode(trigger, node) | [
"def",
"label_contains",
"(",
"node",
",",
"triggers",
")",
":",
"for",
"trigger",
"in",
"triggers",
":",
"if",
"trigger",
".",
"trigger_word",
"in",
"node",
".",
"label",
":",
"yield",
"TriggerNode",
"(",
"trigger",
",",
"node",
")"
] | Determine if node contains any of the trigger_words provided.
Args:
node(Node): CFG node to check.
trigger_words(list[Union[Sink, Source]]): list of trigger words to look for.
Returns:
Iterable of TriggerNodes found. Can be multiple because multiple
trigger_words can be in one node. | [
"Determine",
"if",
"node",
"contains",
"any",
"of",
"the",
"trigger_words",
"provided",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L157-L173 |
227,066 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | build_sanitiser_node_dict | def build_sanitiser_node_dict(
cfg,
sinks_in_file
):
"""Build a dict of string -> TriggerNode pairs, where the string
is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.
Args:
cfg(CFG): cfg to traverse.
sinks_in_file(list[TriggerNode]): list of TriggerNodes containing
the sinks in the file.
Returns:
A string -> TriggerNode dict.
"""
sanitisers = list()
for sink in sinks_in_file:
sanitisers.extend(sink.sanitisers)
sanitisers_in_file = list()
for sanitiser in sanitisers:
for cfg_node in cfg.nodes:
if sanitiser in cfg_node.label:
sanitisers_in_file.append(Sanitiser(sanitiser, cfg_node))
sanitiser_node_dict = dict()
for sanitiser in sanitisers:
sanitiser_node_dict[sanitiser] = list(find_sanitiser_nodes(
sanitiser,
sanitisers_in_file
))
return sanitiser_node_dict | python | def build_sanitiser_node_dict(
cfg,
sinks_in_file
):
sanitisers = list()
for sink in sinks_in_file:
sanitisers.extend(sink.sanitisers)
sanitisers_in_file = list()
for sanitiser in sanitisers:
for cfg_node in cfg.nodes:
if sanitiser in cfg_node.label:
sanitisers_in_file.append(Sanitiser(sanitiser, cfg_node))
sanitiser_node_dict = dict()
for sanitiser in sanitisers:
sanitiser_node_dict[sanitiser] = list(find_sanitiser_nodes(
sanitiser,
sanitisers_in_file
))
return sanitiser_node_dict | [
"def",
"build_sanitiser_node_dict",
"(",
"cfg",
",",
"sinks_in_file",
")",
":",
"sanitisers",
"=",
"list",
"(",
")",
"for",
"sink",
"in",
"sinks_in_file",
":",
"sanitisers",
".",
"extend",
"(",
"sink",
".",
"sanitisers",
")",
"sanitisers_in_file",
"=",
"list",... | Build a dict of string -> TriggerNode pairs, where the string
is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.
Args:
cfg(CFG): cfg to traverse.
sinks_in_file(list[TriggerNode]): list of TriggerNodes containing
the sinks in the file.
Returns:
A string -> TriggerNode dict. | [
"Build",
"a",
"dict",
"of",
"string",
"-",
">",
"TriggerNode",
"pairs",
"where",
"the",
"string",
"is",
"the",
"sanitiser",
"and",
"the",
"TriggerNode",
"is",
"a",
"TriggerNode",
"of",
"the",
"sanitiser",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L176-L207 |
227,067 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | find_sanitiser_nodes | def find_sanitiser_nodes(
sanitiser,
sanitisers_in_file
):
"""Find nodes containing a particular sanitiser.
Args:
sanitiser(string): sanitiser to look for.
sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.
Returns:
Iterable of sanitiser nodes.
"""
for sanitiser_tuple in sanitisers_in_file:
if sanitiser == sanitiser_tuple.trigger_word:
yield sanitiser_tuple.cfg_node | python | def find_sanitiser_nodes(
sanitiser,
sanitisers_in_file
):
for sanitiser_tuple in sanitisers_in_file:
if sanitiser == sanitiser_tuple.trigger_word:
yield sanitiser_tuple.cfg_node | [
"def",
"find_sanitiser_nodes",
"(",
"sanitiser",
",",
"sanitisers_in_file",
")",
":",
"for",
"sanitiser_tuple",
"in",
"sanitisers_in_file",
":",
"if",
"sanitiser",
"==",
"sanitiser_tuple",
".",
"trigger_word",
":",
"yield",
"sanitiser_tuple",
".",
"cfg_node"
] | Find nodes containing a particular sanitiser.
Args:
sanitiser(string): sanitiser to look for.
sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.
Returns:
Iterable of sanitiser nodes. | [
"Find",
"nodes",
"containing",
"a",
"particular",
"sanitiser",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L210-L225 |
227,068 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | get_vulnerability_chains | def get_vulnerability_chains(
current_node,
sink,
def_use,
chain=[]
):
"""Traverses the def-use graph to find all paths from source to sink that cause a vulnerability.
Args:
current_node()
sink()
def_use(dict):
chain(list(Node)): A path of nodes between source and sink.
"""
for use in def_use[current_node]:
if use == sink:
yield chain
else:
vuln_chain = list(chain)
vuln_chain.append(use)
yield from get_vulnerability_chains(
use,
sink,
def_use,
vuln_chain
) | python | def get_vulnerability_chains(
current_node,
sink,
def_use,
chain=[]
):
for use in def_use[current_node]:
if use == sink:
yield chain
else:
vuln_chain = list(chain)
vuln_chain.append(use)
yield from get_vulnerability_chains(
use,
sink,
def_use,
vuln_chain
) | [
"def",
"get_vulnerability_chains",
"(",
"current_node",
",",
"sink",
",",
"def_use",
",",
"chain",
"=",
"[",
"]",
")",
":",
"for",
"use",
"in",
"def_use",
"[",
"current_node",
"]",
":",
"if",
"use",
"==",
"sink",
":",
"yield",
"chain",
"else",
":",
"vu... | Traverses the def-use graph to find all paths from source to sink that cause a vulnerability.
Args:
current_node()
sink()
def_use(dict):
chain(list(Node)): A path of nodes between source and sink. | [
"Traverses",
"the",
"def",
"-",
"use",
"graph",
"to",
"find",
"all",
"paths",
"from",
"source",
"to",
"sink",
"that",
"cause",
"a",
"vulnerability",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L272-L297 |
227,069 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | how_vulnerable | def how_vulnerable(
chain,
blackbox_mapping,
sanitiser_nodes,
potential_sanitiser,
blackbox_assignments,
interactive,
vuln_deets
):
"""Iterates through the chain of nodes and checks the blackbox nodes against the blackbox mapping and sanitiser dictionary.
Note: potential_sanitiser is the only hack here, it is because we do not take p-use's into account yet.
e.g. we can only say potentially instead of definitely sanitised in the path_traversal_sanitised_2.py test.
Args:
chain(list(Node)): A path of nodes between source and sink.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
sanitiser_nodes(set): A set of nodes that are sanitisers for the sink.
potential_sanitiser(Node): An if or elif node that can potentially cause sanitisation.
blackbox_assignments(set[AssignmentNode]): set of blackbox assignments, includes the ReturnNode's of BBorBInode's.
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
vuln_deets(dict): vulnerability details.
Returns:
A VulnerabilityType depending on how vulnerable the chain is.
"""
for i, current_node in enumerate(chain):
if current_node in sanitiser_nodes:
vuln_deets['sanitiser'] = current_node
vuln_deets['confident'] = True
return VulnerabilityType.SANITISED, interactive
if isinstance(current_node, BBorBInode):
if current_node.func_name in blackbox_mapping['propagates']:
continue
elif current_node.func_name in blackbox_mapping['does_not_propagate']:
return VulnerabilityType.FALSE, interactive
elif interactive:
user_says = input(
'Is the return value of {} with tainted argument "{}" vulnerable? ([Y]es/[N]o/[S]top asking)'.format(
current_node.label,
chain[i - 1].left_hand_side
)
).lower()
if user_says.startswith('s'):
interactive = False
vuln_deets['unknown_assignment'] = current_node
return VulnerabilityType.UNKNOWN, interactive
if user_says.startswith('n'):
blackbox_mapping['does_not_propagate'].append(current_node.func_name)
return VulnerabilityType.FALSE, interactive
blackbox_mapping['propagates'].append(current_node.func_name)
else:
vuln_deets['unknown_assignment'] = current_node
return VulnerabilityType.UNKNOWN, interactive
if potential_sanitiser:
vuln_deets['sanitiser'] = potential_sanitiser
vuln_deets['confident'] = False
return VulnerabilityType.SANITISED, interactive
return VulnerabilityType.TRUE, interactive | python | def how_vulnerable(
chain,
blackbox_mapping,
sanitiser_nodes,
potential_sanitiser,
blackbox_assignments,
interactive,
vuln_deets
):
for i, current_node in enumerate(chain):
if current_node in sanitiser_nodes:
vuln_deets['sanitiser'] = current_node
vuln_deets['confident'] = True
return VulnerabilityType.SANITISED, interactive
if isinstance(current_node, BBorBInode):
if current_node.func_name in blackbox_mapping['propagates']:
continue
elif current_node.func_name in blackbox_mapping['does_not_propagate']:
return VulnerabilityType.FALSE, interactive
elif interactive:
user_says = input(
'Is the return value of {} with tainted argument "{}" vulnerable? ([Y]es/[N]o/[S]top asking)'.format(
current_node.label,
chain[i - 1].left_hand_side
)
).lower()
if user_says.startswith('s'):
interactive = False
vuln_deets['unknown_assignment'] = current_node
return VulnerabilityType.UNKNOWN, interactive
if user_says.startswith('n'):
blackbox_mapping['does_not_propagate'].append(current_node.func_name)
return VulnerabilityType.FALSE, interactive
blackbox_mapping['propagates'].append(current_node.func_name)
else:
vuln_deets['unknown_assignment'] = current_node
return VulnerabilityType.UNKNOWN, interactive
if potential_sanitiser:
vuln_deets['sanitiser'] = potential_sanitiser
vuln_deets['confident'] = False
return VulnerabilityType.SANITISED, interactive
return VulnerabilityType.TRUE, interactive | [
"def",
"how_vulnerable",
"(",
"chain",
",",
"blackbox_mapping",
",",
"sanitiser_nodes",
",",
"potential_sanitiser",
",",
"blackbox_assignments",
",",
"interactive",
",",
"vuln_deets",
")",
":",
"for",
"i",
",",
"current_node",
"in",
"enumerate",
"(",
"chain",
")",... | Iterates through the chain of nodes and checks the blackbox nodes against the blackbox mapping and sanitiser dictionary.
Note: potential_sanitiser is the only hack here, it is because we do not take p-use's into account yet.
e.g. we can only say potentially instead of definitely sanitised in the path_traversal_sanitised_2.py test.
Args:
chain(list(Node)): A path of nodes between source and sink.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
sanitiser_nodes(set): A set of nodes that are sanitisers for the sink.
potential_sanitiser(Node): An if or elif node that can potentially cause sanitisation.
blackbox_assignments(set[AssignmentNode]): set of blackbox assignments, includes the ReturnNode's of BBorBInode's.
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
vuln_deets(dict): vulnerability details.
Returns:
A VulnerabilityType depending on how vulnerable the chain is. | [
"Iterates",
"through",
"the",
"chain",
"of",
"nodes",
"and",
"checks",
"the",
"blackbox",
"nodes",
"against",
"the",
"blackbox",
"mapping",
"and",
"sanitiser",
"dictionary",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L300-L361 |
227,070 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | get_vulnerability | def get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
):
"""Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the source, the secondary is a save_N_LHS
node made in process_function in expr_visitor.
Args:
source(TriggerNode): TriggerNode of the source.
sink(TriggerNode): TriggerNode of the sink.
triggers(Triggers): Triggers of the CFG.
lattice(Lattice): the lattice we're analysing.
cfg(CFG): .blackbox_assignments used in is_unknown, .nodes used in build_def_use_chain
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
Returns:
A Vulnerability if it exists, else None
"""
nodes_in_constraint = [
secondary
for secondary in reversed(source.secondary_nodes)
if lattice.in_constraint(
secondary,
sink.cfg_node
)
]
nodes_in_constraint.append(source.cfg_node)
if sink.trigger.all_arguments_propagate_taint:
sink_args = get_sink_args(sink.cfg_node)
else:
sink_args = get_sink_args_which_propagate(sink, sink.cfg_node.ast_node)
tainted_node_in_sink_arg = get_tainted_node_in_sink_args(
sink_args,
nodes_in_constraint,
)
if tainted_node_in_sink_arg:
vuln_deets = {
'source': source.cfg_node,
'source_trigger_word': source.trigger_word,
'sink': sink.cfg_node,
'sink_trigger_word': sink.trigger_word
}
sanitiser_nodes = set()
potential_sanitiser = None
if sink.sanitisers:
for sanitiser in sink.sanitisers:
for cfg_node in triggers.sanitiser_dict[sanitiser]:
if isinstance(cfg_node, AssignmentNode):
sanitiser_nodes.add(cfg_node)
elif isinstance(cfg_node, IfNode):
potential_sanitiser = cfg_node
def_use = build_def_use_chain(
cfg.nodes,
lattice
)
for chain in get_vulnerability_chains(
source.cfg_node,
sink.cfg_node,
def_use
):
vulnerability_type, interactive = how_vulnerable(
chain,
blackbox_mapping,
sanitiser_nodes,
potential_sanitiser,
cfg.blackbox_assignments,
interactive,
vuln_deets
)
if vulnerability_type == VulnerabilityType.FALSE:
continue
vuln_deets['reassignment_nodes'] = chain
return vuln_factory(vulnerability_type)(**vuln_deets), interactive
return None, interactive | python | def get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
):
nodes_in_constraint = [
secondary
for secondary in reversed(source.secondary_nodes)
if lattice.in_constraint(
secondary,
sink.cfg_node
)
]
nodes_in_constraint.append(source.cfg_node)
if sink.trigger.all_arguments_propagate_taint:
sink_args = get_sink_args(sink.cfg_node)
else:
sink_args = get_sink_args_which_propagate(sink, sink.cfg_node.ast_node)
tainted_node_in_sink_arg = get_tainted_node_in_sink_args(
sink_args,
nodes_in_constraint,
)
if tainted_node_in_sink_arg:
vuln_deets = {
'source': source.cfg_node,
'source_trigger_word': source.trigger_word,
'sink': sink.cfg_node,
'sink_trigger_word': sink.trigger_word
}
sanitiser_nodes = set()
potential_sanitiser = None
if sink.sanitisers:
for sanitiser in sink.sanitisers:
for cfg_node in triggers.sanitiser_dict[sanitiser]:
if isinstance(cfg_node, AssignmentNode):
sanitiser_nodes.add(cfg_node)
elif isinstance(cfg_node, IfNode):
potential_sanitiser = cfg_node
def_use = build_def_use_chain(
cfg.nodes,
lattice
)
for chain in get_vulnerability_chains(
source.cfg_node,
sink.cfg_node,
def_use
):
vulnerability_type, interactive = how_vulnerable(
chain,
blackbox_mapping,
sanitiser_nodes,
potential_sanitiser,
cfg.blackbox_assignments,
interactive,
vuln_deets
)
if vulnerability_type == VulnerabilityType.FALSE:
continue
vuln_deets['reassignment_nodes'] = chain
return vuln_factory(vulnerability_type)(**vuln_deets), interactive
return None, interactive | [
"def",
"get_vulnerability",
"(",
"source",
",",
"sink",
",",
"triggers",
",",
"lattice",
",",
"cfg",
",",
"interactive",
",",
"blackbox_mapping",
")",
":",
"nodes_in_constraint",
"=",
"[",
"secondary",
"for",
"secondary",
"in",
"reversed",
"(",
"source",
".",
... | Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the source, the secondary is a save_N_LHS
node made in process_function in expr_visitor.
Args:
source(TriggerNode): TriggerNode of the source.
sink(TriggerNode): TriggerNode of the sink.
triggers(Triggers): Triggers of the CFG.
lattice(Lattice): the lattice we're analysing.
cfg(CFG): .blackbox_assignments used in is_unknown, .nodes used in build_def_use_chain
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
Returns:
A Vulnerability if it exists, else None | [
"Get",
"vulnerability",
"between",
"source",
"and",
"sink",
"if",
"it",
"exists",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L376-L468 |
227,071 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | find_vulnerabilities_in_cfg | def find_vulnerabilities_in_cfg(
cfg,
definitions,
lattice,
blackbox_mapping,
vulnerabilities_list,
interactive,
nosec_lines
):
"""Find vulnerabilities in a cfg.
Args:
cfg(CFG): The CFG to find vulnerabilities in.
definitions(trigger_definitions_parser.Definitions): Source and sink definitions.
lattice(Lattice): the lattice we're analysing.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
vulnerabilities_list(list): That we append to when we find vulnerabilities.
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
"""
triggers = identify_triggers(
cfg,
definitions.sources,
definitions.sinks,
lattice,
nosec_lines[cfg.filename]
)
for sink in triggers.sinks:
for source in triggers.sources:
vulnerability, interactive = get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
)
if vulnerability:
vulnerabilities_list.append(vulnerability) | python | def find_vulnerabilities_in_cfg(
cfg,
definitions,
lattice,
blackbox_mapping,
vulnerabilities_list,
interactive,
nosec_lines
):
triggers = identify_triggers(
cfg,
definitions.sources,
definitions.sinks,
lattice,
nosec_lines[cfg.filename]
)
for sink in triggers.sinks:
for source in triggers.sources:
vulnerability, interactive = get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
)
if vulnerability:
vulnerabilities_list.append(vulnerability) | [
"def",
"find_vulnerabilities_in_cfg",
"(",
"cfg",
",",
"definitions",
",",
"lattice",
",",
"blackbox_mapping",
",",
"vulnerabilities_list",
",",
"interactive",
",",
"nosec_lines",
")",
":",
"triggers",
"=",
"identify_triggers",
"(",
"cfg",
",",
"definitions",
".",
... | Find vulnerabilities in a cfg.
Args:
cfg(CFG): The CFG to find vulnerabilities in.
definitions(trigger_definitions_parser.Definitions): Source and sink definitions.
lattice(Lattice): the lattice we're analysing.
blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.
vulnerabilities_list(list): That we append to when we find vulnerabilities.
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file. | [
"Find",
"vulnerabilities",
"in",
"a",
"cfg",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L471-L509 |
227,072 | python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | find_vulnerabilities | def find_vulnerabilities(
cfg_list,
blackbox_mapping_file,
sources_and_sinks_file,
interactive=False,
nosec_lines=defaultdict(set)
):
"""Find vulnerabilities in a list of CFGs from a trigger_word_file.
Args:
cfg_list(list[CFG]): the list of CFGs to scan.
blackbox_mapping_file(str)
sources_and_sinks_file(str)
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
Returns:
A list of vulnerabilities.
"""
vulnerabilities = list()
definitions = parse(sources_and_sinks_file)
with open(blackbox_mapping_file) as infile:
blackbox_mapping = json.load(infile)
for cfg in cfg_list:
find_vulnerabilities_in_cfg(
cfg,
definitions,
Lattice(cfg.nodes),
blackbox_mapping,
vulnerabilities,
interactive,
nosec_lines
)
if interactive:
with open(blackbox_mapping_file, 'w') as outfile:
json.dump(blackbox_mapping, outfile, indent=4)
return vulnerabilities | python | def find_vulnerabilities(
cfg_list,
blackbox_mapping_file,
sources_and_sinks_file,
interactive=False,
nosec_lines=defaultdict(set)
):
vulnerabilities = list()
definitions = parse(sources_and_sinks_file)
with open(blackbox_mapping_file) as infile:
blackbox_mapping = json.load(infile)
for cfg in cfg_list:
find_vulnerabilities_in_cfg(
cfg,
definitions,
Lattice(cfg.nodes),
blackbox_mapping,
vulnerabilities,
interactive,
nosec_lines
)
if interactive:
with open(blackbox_mapping_file, 'w') as outfile:
json.dump(blackbox_mapping, outfile, indent=4)
return vulnerabilities | [
"def",
"find_vulnerabilities",
"(",
"cfg_list",
",",
"blackbox_mapping_file",
",",
"sources_and_sinks_file",
",",
"interactive",
"=",
"False",
",",
"nosec_lines",
"=",
"defaultdict",
"(",
"set",
")",
")",
":",
"vulnerabilities",
"=",
"list",
"(",
")",
"definitions... | Find vulnerabilities in a list of CFGs from a trigger_word_file.
Args:
cfg_list(list[CFG]): the list of CFGs to scan.
blackbox_mapping_file(str)
sources_and_sinks_file(str)
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
Returns:
A list of vulnerabilities. | [
"Find",
"vulnerabilities",
"in",
"a",
"list",
"of",
"CFGs",
"from",
"a",
"trigger_word_file",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L512-L549 |
227,073 | python-security/pyt | pyt/web_frameworks/framework_adaptor.py | _get_func_nodes | def _get_func_nodes():
"""Get all function nodes."""
return [definition for definition in project_definitions.values()
if isinstance(definition.node, ast.FunctionDef)] | python | def _get_func_nodes():
return [definition for definition in project_definitions.values()
if isinstance(definition.node, ast.FunctionDef)] | [
"def",
"_get_func_nodes",
"(",
")",
":",
"return",
"[",
"definition",
"for",
"definition",
"in",
"project_definitions",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"definition",
".",
"node",
",",
"ast",
".",
"FunctionDef",
")",
"]"
] | Get all function nodes. | [
"Get",
"all",
"function",
"nodes",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/web_frameworks/framework_adaptor.py#L95-L98 |
227,074 | python-security/pyt | pyt/web_frameworks/framework_adaptor.py | FrameworkAdaptor.get_func_cfg_with_tainted_args | def get_func_cfg_with_tainted_args(self, definition):
"""Build a function cfg and return it, with all arguments tainted."""
log.debug("Getting CFG for %s", definition.name)
func_cfg = make_cfg(
definition.node,
self.project_modules,
self.local_modules,
definition.path,
definition.module_definitions
)
args = Arguments(definition.node.args)
if args:
function_entry_node = func_cfg.nodes[0]
function_entry_node.outgoing = list()
first_node_after_args = func_cfg.nodes[1]
first_node_after_args.ingoing = list()
# We are just going to give all the tainted args the lineno of the def
definition_lineno = definition.node.lineno
# Taint all the arguments
for i, arg in enumerate(args):
node_type = TaintedNode
if i == 0 and arg == 'self':
node_type = AssignmentNode
arg_node = node_type(
label=arg,
left_hand_side=arg,
ast_node=None,
right_hand_side_variables=[],
line_number=definition_lineno,
path=definition.path
)
function_entry_node.connect(arg_node)
# 1 and not 0 so that Entry Node remains first in the list
func_cfg.nodes.insert(1, arg_node)
arg_node.connect(first_node_after_args)
return func_cfg | python | def get_func_cfg_with_tainted_args(self, definition):
log.debug("Getting CFG for %s", definition.name)
func_cfg = make_cfg(
definition.node,
self.project_modules,
self.local_modules,
definition.path,
definition.module_definitions
)
args = Arguments(definition.node.args)
if args:
function_entry_node = func_cfg.nodes[0]
function_entry_node.outgoing = list()
first_node_after_args = func_cfg.nodes[1]
first_node_after_args.ingoing = list()
# We are just going to give all the tainted args the lineno of the def
definition_lineno = definition.node.lineno
# Taint all the arguments
for i, arg in enumerate(args):
node_type = TaintedNode
if i == 0 and arg == 'self':
node_type = AssignmentNode
arg_node = node_type(
label=arg,
left_hand_side=arg,
ast_node=None,
right_hand_side_variables=[],
line_number=definition_lineno,
path=definition.path
)
function_entry_node.connect(arg_node)
# 1 and not 0 so that Entry Node remains first in the list
func_cfg.nodes.insert(1, arg_node)
arg_node.connect(first_node_after_args)
return func_cfg | [
"def",
"get_func_cfg_with_tainted_args",
"(",
"self",
",",
"definition",
")",
":",
"log",
".",
"debug",
"(",
"\"Getting CFG for %s\"",
",",
"definition",
".",
"name",
")",
"func_cfg",
"=",
"make_cfg",
"(",
"definition",
".",
"node",
",",
"self",
".",
"project_... | Build a function cfg and return it, with all arguments tainted. | [
"Build",
"a",
"function",
"cfg",
"and",
"return",
"it",
"with",
"all",
"arguments",
"tainted",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/web_frameworks/framework_adaptor.py#L35-L75 |
227,075 | python-security/pyt | pyt/web_frameworks/framework_adaptor.py | FrameworkAdaptor.find_route_functions_taint_args | def find_route_functions_taint_args(self):
"""Find all route functions and taint all of their arguments.
Yields:
CFG of each route function, with args marked as tainted.
"""
for definition in _get_func_nodes():
if self.is_route_function(definition.node):
yield self.get_func_cfg_with_tainted_args(definition) | python | def find_route_functions_taint_args(self):
for definition in _get_func_nodes():
if self.is_route_function(definition.node):
yield self.get_func_cfg_with_tainted_args(definition) | [
"def",
"find_route_functions_taint_args",
"(",
"self",
")",
":",
"for",
"definition",
"in",
"_get_func_nodes",
"(",
")",
":",
"if",
"self",
".",
"is_route_function",
"(",
"definition",
".",
"node",
")",
":",
"yield",
"self",
".",
"get_func_cfg_with_tainted_args",
... | Find all route functions and taint all of their arguments.
Yields:
CFG of each route function, with args marked as tainted. | [
"Find",
"all",
"route",
"functions",
"and",
"taint",
"all",
"of",
"their",
"arguments",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/web_frameworks/framework_adaptor.py#L77-L85 |
227,076 | python-security/pyt | pyt/web_frameworks/framework_adaptor.py | FrameworkAdaptor.run | def run(self):
"""Run find_route_functions_taint_args on each CFG."""
function_cfgs = list()
for _ in self.cfg_list:
function_cfgs.extend(self.find_route_functions_taint_args())
self.cfg_list.extend(function_cfgs) | python | def run(self):
function_cfgs = list()
for _ in self.cfg_list:
function_cfgs.extend(self.find_route_functions_taint_args())
self.cfg_list.extend(function_cfgs) | [
"def",
"run",
"(",
"self",
")",
":",
"function_cfgs",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"self",
".",
"cfg_list",
":",
"function_cfgs",
".",
"extend",
"(",
"self",
".",
"find_route_functions_taint_args",
"(",
")",
")",
"self",
".",
"cfg_list",
".",... | Run find_route_functions_taint_args on each CFG. | [
"Run",
"find_route_functions_taint_args",
"on",
"each",
"CFG",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/web_frameworks/framework_adaptor.py#L87-L92 |
227,077 | python-security/pyt | pyt/analysis/constraint_table.py | initialize_constraint_table | def initialize_constraint_table(cfg_list):
"""Collects all given cfg nodes and initializes the table with value 0."""
for cfg in cfg_list:
constraint_table.update(dict.fromkeys(cfg.nodes, 0)) | python | def initialize_constraint_table(cfg_list):
for cfg in cfg_list:
constraint_table.update(dict.fromkeys(cfg.nodes, 0)) | [
"def",
"initialize_constraint_table",
"(",
"cfg_list",
")",
":",
"for",
"cfg",
"in",
"cfg_list",
":",
"constraint_table",
".",
"update",
"(",
"dict",
".",
"fromkeys",
"(",
"cfg",
".",
"nodes",
",",
"0",
")",
")"
] | Collects all given cfg nodes and initializes the table with value 0. | [
"Collects",
"all",
"given",
"cfg",
"nodes",
"and",
"initializes",
"the",
"table",
"with",
"value",
"0",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/analysis/constraint_table.py#L8-L11 |
227,078 | python-security/pyt | pyt/analysis/constraint_table.py | constraint_join | def constraint_join(cfg_nodes):
"""Looks up all cfg_nodes and joins the bitvectors by using logical or."""
r = 0
for e in cfg_nodes:
r = r | constraint_table[e]
return r | python | def constraint_join(cfg_nodes):
r = 0
for e in cfg_nodes:
r = r | constraint_table[e]
return r | [
"def",
"constraint_join",
"(",
"cfg_nodes",
")",
":",
"r",
"=",
"0",
"for",
"e",
"in",
"cfg_nodes",
":",
"r",
"=",
"r",
"|",
"constraint_table",
"[",
"e",
"]",
"return",
"r"
] | Looks up all cfg_nodes and joins the bitvectors by using logical or. | [
"Looks",
"up",
"all",
"cfg_nodes",
"and",
"joins",
"the",
"bitvectors",
"by",
"using",
"logical",
"or",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/analysis/constraint_table.py#L14-L19 |
227,079 | python-security/pyt | examples/django.nV/taskManager/misc.py | store_uploaded_file | def store_uploaded_file(title, uploaded_file):
""" Stores a temporary uploaded file on disk """
upload_dir_path = '%s/static/taskManager/uploads' % (
os.path.dirname(os.path.realpath(__file__)))
if not os.path.exists(upload_dir_path):
os.makedirs(upload_dir_path)
# A1: Injection (shell)
# Let's avoid the file corruption race condition!
os.system(
"mv " +
uploaded_file.temporary_file_path() +
" " +
"%s/%s" %
(upload_dir_path,
title))
return '/static/taskManager/uploads/%s' % (title) | python | def store_uploaded_file(title, uploaded_file):
upload_dir_path = '%s/static/taskManager/uploads' % (
os.path.dirname(os.path.realpath(__file__)))
if not os.path.exists(upload_dir_path):
os.makedirs(upload_dir_path)
# A1: Injection (shell)
# Let's avoid the file corruption race condition!
os.system(
"mv " +
uploaded_file.temporary_file_path() +
" " +
"%s/%s" %
(upload_dir_path,
title))
return '/static/taskManager/uploads/%s' % (title) | [
"def",
"store_uploaded_file",
"(",
"title",
",",
"uploaded_file",
")",
":",
"upload_dir_path",
"=",
"'%s/static/taskManager/uploads'",
"%",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
")",
"if",... | Stores a temporary uploaded file on disk | [
"Stores",
"a",
"temporary",
"uploaded",
"file",
"on",
"disk"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/examples/django.nV/taskManager/misc.py#L24-L41 |
227,080 | python-security/pyt | pyt/cfg/expr_visitor_helper.py | return_connection_handler | def return_connection_handler(nodes, exit_node):
"""Connect all return statements to the Exit node."""
for function_body_node in nodes:
if isinstance(function_body_node, ConnectToExitNode):
if exit_node not in function_body_node.outgoing:
function_body_node.connect(exit_node) | python | def return_connection_handler(nodes, exit_node):
for function_body_node in nodes:
if isinstance(function_body_node, ConnectToExitNode):
if exit_node not in function_body_node.outgoing:
function_body_node.connect(exit_node) | [
"def",
"return_connection_handler",
"(",
"nodes",
",",
"exit_node",
")",
":",
"for",
"function_body_node",
"in",
"nodes",
":",
"if",
"isinstance",
"(",
"function_body_node",
",",
"ConnectToExitNode",
")",
":",
"if",
"exit_node",
"not",
"in",
"function_body_node",
... | Connect all return statements to the Exit node. | [
"Connect",
"all",
"return",
"statements",
"to",
"the",
"Exit",
"node",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor_helper.py#L43-L48 |
227,081 | python-security/pyt | examples/django.nV/taskManager/forms.py | get_my_choices_users | def get_my_choices_users():
""" Retrieves a list of all users in the system
for the user management page
"""
user_list = User.objects.order_by('date_joined')
user_tuple = []
counter = 1
for user in user_list:
user_tuple.append((counter, user))
counter = counter + 1
return user_tuple | python | def get_my_choices_users():
user_list = User.objects.order_by('date_joined')
user_tuple = []
counter = 1
for user in user_list:
user_tuple.append((counter, user))
counter = counter + 1
return user_tuple | [
"def",
"get_my_choices_users",
"(",
")",
":",
"user_list",
"=",
"User",
".",
"objects",
".",
"order_by",
"(",
"'date_joined'",
")",
"user_tuple",
"=",
"[",
"]",
"counter",
"=",
"1",
"for",
"user",
"in",
"user_list",
":",
"user_tuple",
".",
"append",
"(",
... | Retrieves a list of all users in the system
for the user management page | [
"Retrieves",
"a",
"list",
"of",
"all",
"users",
"in",
"the",
"system",
"for",
"the",
"user",
"management",
"page"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/examples/django.nV/taskManager/forms.py#L22-L33 |
227,082 | python-security/pyt | examples/django.nV/taskManager/forms.py | get_my_choices_tasks | def get_my_choices_tasks(current_proj):
""" Retrieves all tasks in the system
for the task management page
"""
task_list = []
tasks = Task.objects.all()
for task in tasks:
if task.project == current_proj:
task_list.append(task)
task_tuple = []
counter = 1
for task in task_list:
task_tuple.append((counter, task))
counter = counter + 1
return task_tuple | python | def get_my_choices_tasks(current_proj):
task_list = []
tasks = Task.objects.all()
for task in tasks:
if task.project == current_proj:
task_list.append(task)
task_tuple = []
counter = 1
for task in task_list:
task_tuple.append((counter, task))
counter = counter + 1
return task_tuple | [
"def",
"get_my_choices_tasks",
"(",
"current_proj",
")",
":",
"task_list",
"=",
"[",
"]",
"tasks",
"=",
"Task",
".",
"objects",
".",
"all",
"(",
")",
"for",
"task",
"in",
"tasks",
":",
"if",
"task",
".",
"project",
"==",
"current_proj",
":",
"task_list",... | Retrieves all tasks in the system
for the task management page | [
"Retrieves",
"all",
"tasks",
"in",
"the",
"system",
"for",
"the",
"task",
"management",
"page"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/examples/django.nV/taskManager/forms.py#L36-L52 |
227,083 | python-security/pyt | examples/django.nV/taskManager/forms.py | get_my_choices_projects | def get_my_choices_projects():
""" Retrieves all projects in the system
for the project management page
"""
proj_list = Project.objects.all()
proj_tuple = []
counter = 1
for proj in proj_list:
proj_tuple.append((counter, proj))
counter = counter + 1
return proj_tuple | python | def get_my_choices_projects():
proj_list = Project.objects.all()
proj_tuple = []
counter = 1
for proj in proj_list:
proj_tuple.append((counter, proj))
counter = counter + 1
return proj_tuple | [
"def",
"get_my_choices_projects",
"(",
")",
":",
"proj_list",
"=",
"Project",
".",
"objects",
".",
"all",
"(",
")",
"proj_tuple",
"=",
"[",
"]",
"counter",
"=",
"1",
"for",
"proj",
"in",
"proj_list",
":",
"proj_tuple",
".",
"append",
"(",
"(",
"counter",... | Retrieves all projects in the system
for the project management page | [
"Retrieves",
"all",
"projects",
"in",
"the",
"system",
"for",
"the",
"project",
"management",
"page"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/examples/django.nV/taskManager/forms.py#L55-L66 |
227,084 | python-security/pyt | pyt/cfg/alias_helper.py | as_alias_handler | def as_alias_handler(alias_list):
"""Returns a list of all the names that will be called."""
list_ = list()
for alias in alias_list:
if alias.asname:
list_.append(alias.asname)
else:
list_.append(alias.name)
return list_ | python | def as_alias_handler(alias_list):
list_ = list()
for alias in alias_list:
if alias.asname:
list_.append(alias.asname)
else:
list_.append(alias.name)
return list_ | [
"def",
"as_alias_handler",
"(",
"alias_list",
")",
":",
"list_",
"=",
"list",
"(",
")",
"for",
"alias",
"in",
"alias_list",
":",
"if",
"alias",
".",
"asname",
":",
"list_",
".",
"append",
"(",
"alias",
".",
"asname",
")",
"else",
":",
"list_",
".",
"... | Returns a list of all the names that will be called. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"names",
"that",
"will",
"be",
"called",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L4-L12 |
227,085 | python-security/pyt | pyt/cfg/alias_helper.py | handle_fdid_aliases | def handle_fdid_aliases(module_or_package_name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
fdid means from directory import directory.
"""
for key, val in import_alias_mapping.items():
if module_or_package_name == val:
return key
return None | python | def handle_fdid_aliases(module_or_package_name, import_alias_mapping):
for key, val in import_alias_mapping.items():
if module_or_package_name == val:
return key
return None | [
"def",
"handle_fdid_aliases",
"(",
"module_or_package_name",
",",
"import_alias_mapping",
")",
":",
"for",
"key",
",",
"val",
"in",
"import_alias_mapping",
".",
"items",
"(",
")",
":",
"if",
"module_or_package_name",
"==",
"val",
":",
"return",
"key",
"return",
... | Returns either None or the handled alias.
Used in add_module.
fdid means from directory import directory. | [
"Returns",
"either",
"None",
"or",
"the",
"handled",
"alias",
".",
"Used",
"in",
"add_module",
".",
"fdid",
"means",
"from",
"directory",
"import",
"directory",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L49-L57 |
227,086 | python-security/pyt | pyt/cfg/alias_helper.py | not_as_alias_handler | def not_as_alias_handler(names_list):
"""Returns a list of names ignoring any aliases."""
list_ = list()
for alias in names_list:
list_.append(alias.name)
return list_ | python | def not_as_alias_handler(names_list):
list_ = list()
for alias in names_list:
list_.append(alias.name)
return list_ | [
"def",
"not_as_alias_handler",
"(",
"names_list",
")",
":",
"list_",
"=",
"list",
"(",
")",
"for",
"alias",
"in",
"names_list",
":",
"list_",
".",
"append",
"(",
"alias",
".",
"name",
")",
"return",
"list_"
] | Returns a list of names ignoring any aliases. | [
"Returns",
"a",
"list",
"of",
"names",
"ignoring",
"any",
"aliases",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L60-L65 |
227,087 | python-security/pyt | pyt/cfg/alias_helper.py | retrieve_import_alias_mapping | def retrieve_import_alias_mapping(names_list):
"""Creates a dictionary mapping aliases to their respective name.
import_alias_names is used in module_definitions.py and visit_Call"""
import_alias_names = dict()
for alias in names_list:
if alias.asname:
import_alias_names[alias.asname] = alias.name
return import_alias_names | python | def retrieve_import_alias_mapping(names_list):
import_alias_names = dict()
for alias in names_list:
if alias.asname:
import_alias_names[alias.asname] = alias.name
return import_alias_names | [
"def",
"retrieve_import_alias_mapping",
"(",
"names_list",
")",
":",
"import_alias_names",
"=",
"dict",
"(",
")",
"for",
"alias",
"in",
"names_list",
":",
"if",
"alias",
".",
"asname",
":",
"import_alias_names",
"[",
"alias",
".",
"asname",
"]",
"=",
"alias",
... | Creates a dictionary mapping aliases to their respective name.
import_alias_names is used in module_definitions.py and visit_Call | [
"Creates",
"a",
"dictionary",
"mapping",
"aliases",
"to",
"their",
"respective",
"name",
".",
"import_alias_names",
"is",
"used",
"in",
"module_definitions",
".",
"py",
"and",
"visit_Call"
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L68-L76 |
227,088 | python-security/pyt | pyt/cfg/alias_helper.py | fully_qualify_alias_labels | def fully_qualify_alias_labels(label, aliases):
"""Replace any aliases in label with the fully qualified name.
Args:
label -- A label : str representing a name (e.g. myos.system)
aliases -- A dict of {alias: real_name} (e.g. {'myos': 'os'})
>>> fully_qualify_alias_labels('myos.mycall', {'myos':'os'})
'os.mycall'
"""
for alias, full_name in aliases.items():
if label == alias:
return full_name
elif label.startswith(alias+'.'):
return full_name + label[len(alias):]
return label | python | def fully_qualify_alias_labels(label, aliases):
for alias, full_name in aliases.items():
if label == alias:
return full_name
elif label.startswith(alias+'.'):
return full_name + label[len(alias):]
return label | [
"def",
"fully_qualify_alias_labels",
"(",
"label",
",",
"aliases",
")",
":",
"for",
"alias",
",",
"full_name",
"in",
"aliases",
".",
"items",
"(",
")",
":",
"if",
"label",
"==",
"alias",
":",
"return",
"full_name",
"elif",
"label",
".",
"startswith",
"(",
... | Replace any aliases in label with the fully qualified name.
Args:
label -- A label : str representing a name (e.g. myos.system)
aliases -- A dict of {alias: real_name} (e.g. {'myos': 'os'})
>>> fully_qualify_alias_labels('myos.mycall', {'myos':'os'})
'os.mycall' | [
"Replace",
"any",
"aliases",
"in",
"label",
"with",
"the",
"fully",
"qualified",
"name",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L79-L94 |
227,089 | python-security/pyt | pyt/core/ast_helper.py | _convert_to_3 | def _convert_to_3(path): # pragma: no cover
"""Convert python 2 file to python 3."""
try:
log.warn('##### Trying to convert %s to Python 3. #####', path)
subprocess.call(['2to3', '-w', path])
except subprocess.SubprocessError:
log.exception('Check if 2to3 is installed. https://docs.python.org/2/library/2to3.html')
exit(1) | python | def _convert_to_3(path): # pragma: no cover
try:
log.warn('##### Trying to convert %s to Python 3. #####', path)
subprocess.call(['2to3', '-w', path])
except subprocess.SubprocessError:
log.exception('Check if 2to3 is installed. https://docs.python.org/2/library/2to3.html')
exit(1) | [
"def",
"_convert_to_3",
"(",
"path",
")",
":",
"# pragma: no cover",
"try",
":",
"log",
".",
"warn",
"(",
"'##### Trying to convert %s to Python 3. #####'",
",",
"path",
")",
"subprocess",
".",
"call",
"(",
"[",
"'2to3'",
",",
"'-w'",
",",
"path",
"]",
")",
... | Convert python 2 file to python 3. | [
"Convert",
"python",
"2",
"file",
"to",
"python",
"3",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/ast_helper.py#L17-L24 |
227,090 | python-security/pyt | pyt/core/ast_helper.py | generate_ast | def generate_ast(path):
"""Generate an Abstract Syntax Tree using the ast module.
Args:
path(str): The path to the file e.g. example/foo/bar.py
"""
if os.path.isfile(path):
with open(path, 'r') as f:
try:
tree = ast.parse(f.read())
return PytTransformer().visit(tree)
except SyntaxError: # pragma: no cover
global recursive
if not recursive:
_convert_to_3(path)
recursive = True
return generate_ast(path)
else:
raise SyntaxError('The ast module can not parse the file'
' and the python 2 to 3 conversion'
' also failed.')
raise IOError('Input needs to be a file. Path: ' + path) | python | def generate_ast(path):
if os.path.isfile(path):
with open(path, 'r') as f:
try:
tree = ast.parse(f.read())
return PytTransformer().visit(tree)
except SyntaxError: # pragma: no cover
global recursive
if not recursive:
_convert_to_3(path)
recursive = True
return generate_ast(path)
else:
raise SyntaxError('The ast module can not parse the file'
' and the python 2 to 3 conversion'
' also failed.')
raise IOError('Input needs to be a file. Path: ' + path) | [
"def",
"generate_ast",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"try",
":",
"tree",
"=",
"ast",
".",
"parse",
"(",
"f",
".",
"read",
"(... | Generate an Abstract Syntax Tree using the ast module.
Args:
path(str): The path to the file e.g. example/foo/bar.py | [
"Generate",
"an",
"Abstract",
"Syntax",
"Tree",
"using",
"the",
"ast",
"module",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/ast_helper.py#L28-L49 |
227,091 | python-security/pyt | pyt/core/ast_helper.py | _get_call_names_helper | def _get_call_names_helper(node):
"""Recursively finds all function names."""
if isinstance(node, ast.Name):
if node.id not in BLACK_LISTED_CALL_NAMES:
yield node.id
elif isinstance(node, ast.Subscript):
yield from _get_call_names_helper(node.value)
elif isinstance(node, ast.Str):
yield node.s
elif isinstance(node, ast.Attribute):
yield node.attr
yield from _get_call_names_helper(node.value) | python | def _get_call_names_helper(node):
if isinstance(node, ast.Name):
if node.id not in BLACK_LISTED_CALL_NAMES:
yield node.id
elif isinstance(node, ast.Subscript):
yield from _get_call_names_helper(node.value)
elif isinstance(node, ast.Str):
yield node.s
elif isinstance(node, ast.Attribute):
yield node.attr
yield from _get_call_names_helper(node.value) | [
"def",
"_get_call_names_helper",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Name",
")",
":",
"if",
"node",
".",
"id",
"not",
"in",
"BLACK_LISTED_CALL_NAMES",
":",
"yield",
"node",
".",
"id",
"elif",
"isinstance",
"(",
"node... | Recursively finds all function names. | [
"Recursively",
"finds",
"all",
"function",
"names",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/ast_helper.py#L52-L63 |
227,092 | python-security/pyt | pyt/web_frameworks/framework_helper.py | is_flask_route_function | def is_flask_route_function(ast_node):
"""Check whether function uses a route decorator."""
for decorator in ast_node.decorator_list:
if isinstance(decorator, ast.Call):
if _get_last_of_iterable(get_call_names(decorator.func)) == 'route':
return True
return False | python | def is_flask_route_function(ast_node):
for decorator in ast_node.decorator_list:
if isinstance(decorator, ast.Call):
if _get_last_of_iterable(get_call_names(decorator.func)) == 'route':
return True
return False | [
"def",
"is_flask_route_function",
"(",
"ast_node",
")",
":",
"for",
"decorator",
"in",
"ast_node",
".",
"decorator_list",
":",
"if",
"isinstance",
"(",
"decorator",
",",
"ast",
".",
"Call",
")",
":",
"if",
"_get_last_of_iterable",
"(",
"get_call_names",
"(",
"... | Check whether function uses a route decorator. | [
"Check",
"whether",
"function",
"uses",
"a",
"route",
"decorator",
"."
] | efc0cfb716e40e0c8df4098f1cc8cf43723cd31f | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/web_frameworks/framework_helper.py#L14-L20 |
227,093 | PyCQA/astroid | astroid/modutils.py | _cache_normalize_path | def _cache_normalize_path(path):
"""abspath with caching"""
# _module_file calls abspath on every path in sys.path every time it's
# called; on a larger codebase this easily adds up to half a second just
# assembling path components. This cache alleviates that.
try:
return _NORM_PATH_CACHE[path]
except KeyError:
if not path: # don't cache result for ''
return _normalize_path(path)
result = _NORM_PATH_CACHE[path] = _normalize_path(path)
return result | python | def _cache_normalize_path(path):
# _module_file calls abspath on every path in sys.path every time it's
# called; on a larger codebase this easily adds up to half a second just
# assembling path components. This cache alleviates that.
try:
return _NORM_PATH_CACHE[path]
except KeyError:
if not path: # don't cache result for ''
return _normalize_path(path)
result = _NORM_PATH_CACHE[path] = _normalize_path(path)
return result | [
"def",
"_cache_normalize_path",
"(",
"path",
")",
":",
"# _module_file calls abspath on every path in sys.path every time it's",
"# called; on a larger codebase this easily adds up to half a second just",
"# assembling path components. This cache alleviates that.",
"try",
":",
"return",
"_NO... | abspath with caching | [
"abspath",
"with",
"caching"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L166-L177 |
227,094 | PyCQA/astroid | astroid/modutils.py | load_module_from_name | def load_module_from_name(dotted_name, path=None, use_sys=True):
"""Load a Python module from its name.
:type dotted_name: str
:param dotted_name: python name of a module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be
used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module
"""
return load_module_from_modpath(dotted_name.split("."), path, use_sys) | python | def load_module_from_name(dotted_name, path=None, use_sys=True):
return load_module_from_modpath(dotted_name.split("."), path, use_sys) | [
"def",
"load_module_from_name",
"(",
"dotted_name",
",",
"path",
"=",
"None",
",",
"use_sys",
"=",
"True",
")",
":",
"return",
"load_module_from_modpath",
"(",
"dotted_name",
".",
"split",
"(",
"\".\"",
")",
",",
"path",
",",
"use_sys",
")"
] | Load a Python module from its name.
:type dotted_name: str
:param dotted_name: python name of a module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be
used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module | [
"Load",
"a",
"Python",
"module",
"from",
"its",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L180-L202 |
227,095 | PyCQA/astroid | astroid/modutils.py | load_module_from_modpath | def load_module_from_modpath(parts, path=None, use_sys=1):
"""Load a python module from its split name.
:type parts: list(str) or tuple(str)
:param parts:
python name of a module or package split on '.'
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module
"""
if use_sys:
try:
return sys.modules[".".join(parts)]
except KeyError:
pass
modpath = []
prevmodule = None
for part in parts:
modpath.append(part)
curname = ".".join(modpath)
module = None
if len(modpath) != len(parts):
# even with use_sys=False, should try to get outer packages from sys.modules
module = sys.modules.get(curname)
elif use_sys:
# because it may have been indirectly loaded through a parent
module = sys.modules.get(curname)
if module is None:
mp_file, mp_filename, mp_desc = imp.find_module(part, path)
module = imp.load_module(curname, mp_file, mp_filename, mp_desc)
# mp_file still needs to be closed.
if mp_file:
mp_file.close()
if prevmodule:
setattr(prevmodule, part, module)
_file = getattr(module, "__file__", "")
prevmodule = module
if not _file and util.is_namespace(curname):
continue
if not _file and len(modpath) != len(parts):
raise ImportError("no module in %s" % ".".join(parts[len(modpath) :]))
path = [os.path.dirname(_file)]
return module | python | def load_module_from_modpath(parts, path=None, use_sys=1):
if use_sys:
try:
return sys.modules[".".join(parts)]
except KeyError:
pass
modpath = []
prevmodule = None
for part in parts:
modpath.append(part)
curname = ".".join(modpath)
module = None
if len(modpath) != len(parts):
# even with use_sys=False, should try to get outer packages from sys.modules
module = sys.modules.get(curname)
elif use_sys:
# because it may have been indirectly loaded through a parent
module = sys.modules.get(curname)
if module is None:
mp_file, mp_filename, mp_desc = imp.find_module(part, path)
module = imp.load_module(curname, mp_file, mp_filename, mp_desc)
# mp_file still needs to be closed.
if mp_file:
mp_file.close()
if prevmodule:
setattr(prevmodule, part, module)
_file = getattr(module, "__file__", "")
prevmodule = module
if not _file and util.is_namespace(curname):
continue
if not _file and len(modpath) != len(parts):
raise ImportError("no module in %s" % ".".join(parts[len(modpath) :]))
path = [os.path.dirname(_file)]
return module | [
"def",
"load_module_from_modpath",
"(",
"parts",
",",
"path",
"=",
"None",
",",
"use_sys",
"=",
"1",
")",
":",
"if",
"use_sys",
":",
"try",
":",
"return",
"sys",
".",
"modules",
"[",
"\".\"",
".",
"join",
"(",
"parts",
")",
"]",
"except",
"KeyError",
... | Load a python module from its split name.
:type parts: list(str) or tuple(str)
:param parts:
python name of a module or package split on '.'
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module | [
"Load",
"a",
"python",
"module",
"from",
"its",
"split",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L205-L258 |
227,096 | PyCQA/astroid | astroid/modutils.py | load_module_from_file | def load_module_from_file(filepath, path=None, use_sys=True, extrapath=None):
"""Load a Python module from it's path.
:type filepath: str
:param filepath: path to the python module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be
used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module
"""
modpath = modpath_from_file(filepath, extrapath)
return load_module_from_modpath(modpath, path, use_sys) | python | def load_module_from_file(filepath, path=None, use_sys=True, extrapath=None):
modpath = modpath_from_file(filepath, extrapath)
return load_module_from_modpath(modpath, path, use_sys) | [
"def",
"load_module_from_file",
"(",
"filepath",
",",
"path",
"=",
"None",
",",
"use_sys",
"=",
"True",
",",
"extrapath",
"=",
"None",
")",
":",
"modpath",
"=",
"modpath_from_file",
"(",
"filepath",
",",
"extrapath",
")",
"return",
"load_module_from_modpath",
... | Load a Python module from it's path.
:type filepath: str
:param filepath: path to the python module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
:param use_sys:
boolean indicating whether the sys.modules dictionary should be
used or not
:raise ImportError: if the module or package is not found
:rtype: module
:return: the loaded module | [
"Load",
"a",
"Python",
"module",
"from",
"it",
"s",
"path",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L261-L284 |
227,097 | PyCQA/astroid | astroid/modutils.py | _get_relative_base_path | def _get_relative_base_path(filename, path_to_check):
"""Extracts the relative mod path of the file to import from
Check if a file is within the passed in path and if so, returns the
relative mod path from the one passed in.
If the filename is no in path_to_check, returns None
Note this function will look for both abs and realpath of the file,
this allows to find the relative base path even if the file is a
symlink of a file in the passed in path
Examples:
_get_relative_base_path("/a/b/c/d.py", "/a/b") -> ["c","d"]
_get_relative_base_path("/a/b/c/d.py", "/dev") -> None
"""
importable_path = None
path_to_check = os.path.normcase(path_to_check)
abs_filename = os.path.abspath(filename)
if os.path.normcase(abs_filename).startswith(path_to_check):
importable_path = abs_filename
real_filename = os.path.realpath(filename)
if os.path.normcase(real_filename).startswith(path_to_check):
importable_path = real_filename
if importable_path:
base_path = os.path.splitext(importable_path)[0]
relative_base_path = base_path[len(path_to_check) :]
return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
return None | python | def _get_relative_base_path(filename, path_to_check):
importable_path = None
path_to_check = os.path.normcase(path_to_check)
abs_filename = os.path.abspath(filename)
if os.path.normcase(abs_filename).startswith(path_to_check):
importable_path = abs_filename
real_filename = os.path.realpath(filename)
if os.path.normcase(real_filename).startswith(path_to_check):
importable_path = real_filename
if importable_path:
base_path = os.path.splitext(importable_path)[0]
relative_base_path = base_path[len(path_to_check) :]
return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
return None | [
"def",
"_get_relative_base_path",
"(",
"filename",
",",
"path_to_check",
")",
":",
"importable_path",
"=",
"None",
"path_to_check",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"path_to_check",
")",
"abs_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",... | Extracts the relative mod path of the file to import from
Check if a file is within the passed in path and if so, returns the
relative mod path from the one passed in.
If the filename is no in path_to_check, returns None
Note this function will look for both abs and realpath of the file,
this allows to find the relative base path even if the file is a
symlink of a file in the passed in path
Examples:
_get_relative_base_path("/a/b/c/d.py", "/a/b") -> ["c","d"]
_get_relative_base_path("/a/b/c/d.py", "/dev") -> None | [
"Extracts",
"the",
"relative",
"mod",
"path",
"of",
"the",
"file",
"to",
"import",
"from"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L300-L331 |
227,098 | PyCQA/astroid | astroid/modutils.py | get_module_files | def get_module_files(src_directory, blacklist, list_all=False):
"""given a package directory return a list of all available python
module's files in the package and its subpackages
:type src_directory: str
:param src_directory:
path of the directory corresponding to the package
:type blacklist: list or tuple
:param blacklist: iterable
list of files or directories to ignore.
:type list_all: bool
:param list_all:
get files from all paths, including ones without __init__.py
:rtype: list
:return:
the list of all available python module's files in the package and
its subpackages
"""
files = []
for directory, dirnames, filenames in os.walk(src_directory):
if directory in blacklist:
continue
_handle_blacklist(blacklist, dirnames, filenames)
# check for __init__.py
if not list_all and "__init__.py" not in filenames:
dirnames[:] = ()
continue
for filename in filenames:
if _is_python_file(filename):
src = os.path.join(directory, filename)
files.append(src)
return files | python | def get_module_files(src_directory, blacklist, list_all=False):
files = []
for directory, dirnames, filenames in os.walk(src_directory):
if directory in blacklist:
continue
_handle_blacklist(blacklist, dirnames, filenames)
# check for __init__.py
if not list_all and "__init__.py" not in filenames:
dirnames[:] = ()
continue
for filename in filenames:
if _is_python_file(filename):
src = os.path.join(directory, filename)
files.append(src)
return files | [
"def",
"get_module_files",
"(",
"src_directory",
",",
"blacklist",
",",
"list_all",
"=",
"False",
")",
":",
"files",
"=",
"[",
"]",
"for",
"directory",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"src_directory",
")",
":",
"if",
"dir... | given a package directory return a list of all available python
module's files in the package and its subpackages
:type src_directory: str
:param src_directory:
path of the directory corresponding to the package
:type blacklist: list or tuple
:param blacklist: iterable
list of files or directories to ignore.
:type list_all: bool
:param list_all:
get files from all paths, including ones without __init__.py
:rtype: list
:return:
the list of all available python module's files in the package and
its subpackages | [
"given",
"a",
"package",
"directory",
"return",
"a",
"list",
"of",
"all",
"available",
"python",
"module",
"s",
"files",
"in",
"the",
"package",
"and",
"its",
"subpackages"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L499-L533 |
227,099 | PyCQA/astroid | astroid/modutils.py | is_relative | def is_relative(modname, from_file):
"""return true if the given module name is relative to the given
file name
:type modname: str
:param modname: name of the module we are interested in
:type from_file: str
:param from_file:
path of the module from which modname has been imported
:rtype: bool
:return:
true if the module has been imported relatively to `from_file`
"""
if not os.path.isdir(from_file):
from_file = os.path.dirname(from_file)
if from_file in sys.path:
return False
try:
stream, _, _ = imp.find_module(modname.split(".")[0], [from_file])
# Close the stream to avoid ResourceWarnings.
if stream:
stream.close()
return True
except ImportError:
return False | python | def is_relative(modname, from_file):
if not os.path.isdir(from_file):
from_file = os.path.dirname(from_file)
if from_file in sys.path:
return False
try:
stream, _, _ = imp.find_module(modname.split(".")[0], [from_file])
# Close the stream to avoid ResourceWarnings.
if stream:
stream.close()
return True
except ImportError:
return False | [
"def",
"is_relative",
"(",
"modname",
",",
"from_file",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"from_file",
")",
":",
"from_file",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"from_file",
")",
"if",
"from_file",
"in",
"sys",
".... | return true if the given module name is relative to the given
file name
:type modname: str
:param modname: name of the module we are interested in
:type from_file: str
:param from_file:
path of the module from which modname has been imported
:rtype: bool
:return:
true if the module has been imported relatively to `from_file` | [
"return",
"true",
"if",
"the",
"given",
"module",
"name",
"is",
"relative",
"to",
"the",
"given",
"file",
"name"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/modutils.py#L610-L637 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.