lca_index
int64 0
223
| idx
stringlengths 7
11
| line_type
stringclasses 6
values | ground_truth
stringlengths 2
35
| completions
sequencelengths 3
1.16k
| prefix
stringlengths 298
32.8k
| postfix
stringlengths 0
28.6k
| repo
stringclasses 34
values |
---|---|---|---|---|---|---|---|
0 | 0-46-56 | inproject | MergedProjectProfile | [
"add_func_to_reached_and_clone",
"Any",
"copy",
"Dict",
"FunctionProfile",
"fuzz_cfg_load",
"fuzz_cov_load",
"fuzz_utils",
"FuzzerProfile",
"List",
"load_all_profiles",
"logger",
"logging",
"MergedProjectProfile",
"Optional",
"os",
"read_fuzzer_data_file_to_profile",
"Set",
"Tuple",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader. | ,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-47-54 | inproject | FuzzerProfile | [
"add_func_to_reached_and_clone",
"Any",
"copy",
"Dict",
"FunctionProfile",
"fuzz_cfg_load",
"fuzz_cov_load",
"fuzz_utils",
"FuzzerProfile",
"List",
"load_all_profiles",
"logger",
"logging",
"MergedProjectProfile",
"Optional",
"os",
"read_fuzzer_data_file_to_profile",
"Set",
"Tuple",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader. | ],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-62-30 | inproject | extract_all_callsites | [
"CalltreeCallsite",
"data_file_read_calltree",
"extract_all_callsites",
"extract_all_callsites_recursive",
"List",
"logger",
"logging",
"Optional",
"print_ctcs_tree",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load. | (profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-62-60 | inproject | function_call_depths | [
"accummulate_profile",
"all_class_functions",
"binary_executable",
"correlate_executable_name",
"coverage",
"file_targets",
"function_call_depths",
"functions_reached_by_fuzzer",
"functions_unreached_by_fuzzer",
"fuzzer_source_file",
"get_cov_metrics",
"get_cov_uncovered_reachable_funcs",
"get_file_targets",
"get_function_coverage",
"get_key",
"get_target_fuzzer_filename",
"get_total_basic_blocks",
"get_total_cyclomatic_complexity",
"introspector_data_file",
"load_coverage",
"reaches",
"refine_paths",
"set_all_reached_functions",
"set_all_unreached_functions",
"total_basic_blocks",
"total_cyclomatic_complexity",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile. | )
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-66-40 | inproject | demangle_cpp_func | [
"Any",
"cxxfilt",
"data_file_read_yaml",
"demangle_cpp_func",
"Dict",
"get_all_files_in_tree_with_regex",
"get_target_coverage_url",
"List",
"logger",
"logging",
"longest_common_prefix",
"normalise_str",
"Optional",
"os",
"re",
"safe_decode",
"scan_executables_for_fuzz_introspector_logs",
"yaml",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils. | (node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-66-63 | inproject | dst_function_name | [
"children",
"cov_callsite_link",
"cov_color",
"cov_ct_idx",
"cov_forward_reds",
"cov_hitcount",
"cov_largest_blocked_func",
"cov_link",
"cov_parent",
"depth",
"dst_function_name",
"dst_function_source_file",
"hitcount",
"parent_calltree_callsite",
"src_function_name",
"src_function_source_file",
"src_linenumber",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node. | )
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-77-33 | random | cov_callsite_link | [
"children",
"cov_callsite_link",
"cov_color",
"cov_ct_idx",
"cov_forward_reds",
"cov_hitcount",
"cov_largest_blocked_func",
"cov_link",
"cov_parent",
"depth",
"dst_function_name",
"dst_function_source_file",
"hitcount",
"parent_calltree_callsite",
"src_function_name",
"src_function_source_file",
"src_linenumber",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node. |
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-79-30 | infile | create_str_node_ctx_idx | [
"analysis_func",
"create_calltree",
"create_fuzz_blocker_table",
"create_str_node_ctx_idx",
"get_fuzz_blockers",
"html_create_dedicated_calltree_file",
"name",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self. | (str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-79-63 | infile | cov_ct_idx | [
"children",
"cov_callsite_link",
"cov_color",
"cov_ct_idx",
"cov_forward_reds",
"cov_hitcount",
"cov_largest_blocked_func",
"cov_link",
"cov_parent",
"depth",
"dst_function_name",
"dst_function_source_file",
"hitcount",
"parent_calltree_callsite",
"src_function_name",
"src_function_source_file",
"src_linenumber",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node. | ))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-133-13 | infile | html_create_dedicated_calltree_file | [
"analysis_func",
"create_calltree",
"create_fuzz_blocker_table",
"create_str_node_ctx_idx",
"get_fuzz_blockers",
"html_create_dedicated_calltree_file",
"name",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self. | (
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-144-38 | inproject | FuzzerProfile | [
"add_func_to_reached_and_clone",
"Any",
"copy",
"Dict",
"FunctionProfile",
"fuzz_cfg_load",
"fuzz_cov_load",
"fuzz_utils",
"FuzzerProfile",
"List",
"load_all_profiles",
"logger",
"logging",
"MergedProjectProfile",
"Optional",
"os",
"read_fuzzer_data_file_to_profile",
"Set",
"Tuple",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader. | ):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-153-40 | inproject | html_get_header | [
"Any",
"html_add_header_with_link",
"html_create_table_head",
"html_get_header",
"html_get_navbar",
"html_get_table_of_contents",
"html_table_add_row",
"List",
"Tuple",
"__doc__",
"__file__",
"__name__",
"__package__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers. | (
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-155-49 | inproject | get_key | [
"accummulate_profile",
"all_class_functions",
"binary_executable",
"correlate_executable_name",
"coverage",
"file_targets",
"function_call_depths",
"functions_reached_by_fuzzer",
"functions_unreached_by_fuzzer",
"fuzzer_source_file",
"get_cov_metrics",
"get_cov_uncovered_reachable_funcs",
"get_file_targets",
"get_function_coverage",
"get_key",
"get_target_fuzzer_filename",
"get_total_basic_blocks",
"get_total_cyclomatic_complexity",
"introspector_data_file",
"load_coverage",
"reaches",
"refine_paths",
"set_all_reached_functions",
"set_all_unreached_functions",
"total_basic_blocks",
"total_cyclomatic_complexity",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile. | () }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-166-34 | infile | create_fuzz_blocker_table | [
"analysis_func",
"create_calltree",
"create_fuzz_blocker_table",
"create_str_node_ctx_idx",
"get_fuzz_blockers",
"html_create_dedicated_calltree_file",
"name",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self. | (profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-181-25 | infile | append | [
"append",
"clear",
"copy",
"count",
"extend",
"index",
"insert",
"pop",
"remove",
"reverse",
"sort",
"__add__",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__delitem__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__gt__",
"__hash__",
"__iadd__",
"__imul__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs. | (self.create_str_node_ctx_idx(str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
0 | 0-181-37 | infile | create_str_node_ctx_idx | [
"analysis_func",
"create_calltree",
"create_fuzz_blocker_table",
"create_str_node_ctx_idx",
"get_fuzz_blockers",
"html_create_dedicated_calltree_file",
"name",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | # Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic related to calltree analysis"""
import os
import logging
import json
from typing import (
List,
Tuple,
Optional,
Set,
)
import fuzz_analysis
import fuzz_data_loader
import fuzz_utils
import fuzz_cfg_load
import fuzz_html_helpers
# For pretty printing the html code:
from bs4 import BeautifulSoup as bs
logger = logging.getLogger(name=__name__)
class FuzzCalltreeAnalysis(fuzz_analysis.AnalysisInterface):
def __init__(self):
self.name = "FuzzCalltreeAnalysis"
logger.info("Creating FuzzCalltreeAnalysis")
def analysis_func(self,
toc_list: List[Tuple[str, str, int]],
tables: List[str],
project_profile: fuzz_data_loader.MergedProjectProfile,
profiles: List[fuzz_data_loader.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions) -> str:
"""
Creates the HTML of the calltree. Returns the HTML as a string.
"""
logger.info("Not implemented")
return ""
def create_calltree(self, profile: fuzz_data_loader.FuzzerProfile) -> str:
logger.info("In calltree")
# Generate HTML for the calltree
calltree_html_string = "<div class='section-wrapper'>"
calltree_html_string += "<h1>Fuzzer calltree</h1>"
nodes = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
for i in range(len(nodes)):
node = nodes[i]
demangled_name = fuzz_utils.demangle_cpp_func(node.dst_function_name)
# We may not want to show certain functions at times, e.g. libc functions
# in case it bloats the calltree
# libc_funcs = { "free" }
libc_funcs: Set[str] = set()
avoid = len([fn for fn in libc_funcs if fn in demangled_name]) > 0
if avoid:
continue
# Prepare strings needed in the HTML
color_to_be = node.cov_color
callsite_link = node.cov_callsite_link
link = node.cov_link
ct_idx_str = self.create_str_node_ctx_idx(str(node.cov_ct_idx))
# Only display [function] link if we have, otherwhise show no [function] text.
if node.dst_function_source_file.replace(" ", "") != "/":
func_href = f"""<a href="{link}">[function]</a>"""
else:
func_href = ""
if i > 0:
previous_node = nodes[i - 1]
if previous_node.depth == node.depth:
calltree_html_string += "</div>"
depth_diff = previous_node.depth - node.depth
if depth_diff >= 1:
closing_divs = "</div>" # To close "calltree-line-wrapper"
closing_divs = "</div>" * (int(depth_diff) + 1)
calltree_html_string += closing_divs
calltree_html_string += f"""
<div class="{color_to_be}-background coverage-line">
<span class="coverage-line-inner" data-calltree-idx="{ct_idx_str}">
{node.depth}
<code class="language-clike">
{demangled_name}
</code>
<span class="coverage-line-filename">
{func_href}
<a href="{callsite_link}">
[call site2]
</a>
<span class="calltree-idx">[calltree idx: {ct_idx_str}]</span>
</span>
</span>
"""
if i != len(nodes) - 1:
next_node = nodes[i + 1]
if next_node.depth > node.depth:
calltree_html_string += f"""<div
class="calltree-line-wrapper open level-{int(node.depth)}"
style="padding-left: 16px">"""
elif next_node.depth < node.depth:
depth_diff = int(node.depth - next_node.depth)
calltree_html_string += "</div>" * depth_diff
calltree_html_string += "</div>"
logger.info("Calltree created")
# Write the HTML to a file called calltree_view_XX.html where XX is a counter.
calltree_file_idx = 0
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
while os.path.isfile(calltree_html_file):
calltree_file_idx += 1
calltree_html_file = f"calltree_view_{calltree_file_idx}.html"
self.html_create_dedicated_calltree_file(
calltree_html_string,
calltree_html_file,
profile,
)
return calltree_html_file
def html_create_dedicated_calltree_file(
self,
calltree_html_string,
filename,
profile: fuzz_data_loader.FuzzerProfile):
"""
Write a wrapped HTML file with the tags needed from fuzz-introspector
We use this only for wrapping calltrees at the moment, however, down
the line it makes sense to have an easy wrapper for other HTML pages too.
"""
complete_html_string = ""
# HTML start
html_header = fuzz_html_helpers.html_get_header(
calltree=True,
title=f"Fuzz introspector: { profile.get_key() }"
)
html_header += '<div class="content-section calltree-content-section">'
complete_html_string += html_header
# Display fuzz blocker at top of page
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
fuzz_blocker_table = self.create_fuzz_blocker_table(profile, [], "", fuzz_blockers)
if fuzz_blocker_table is not None:
complete_html_string += "<div class=\"report-box\">"
complete_html_string += "<h1>Fuzz blockers</h1>"
complete_html_string += fuzz_blocker_table
complete_html_string += "</div>"
# Display calltree
complete_html_string += calltree_html_string
complete_html_string += "</div></div></div></div>"
# HTML end
html_end = '</div>'
blocker_idxs = []
for node in fuzz_blockers:
blocker_idxs.append(self. | (str(node.cov_ct_idx)))
if len(blocker_idxs) > 0:
html_end = "<script>"
html_end += f"var fuzz_blocker_idxs = {json.dumps(blocker_idxs)};"
html_end += "</script>"
html_end += "<script src=\"prism.js\"></script>"
html_end += "<script src=\"clike.js\"></script>"
html_end += "<script src=\"calltree.js\"></script>"
complete_html_string += html_end
complete_html_string += "</body></html>"
# Beautify and write HTML
soup = bs(complete_html_string, 'lxml')
pretty_html = soup.prettify()
with open(filename, "w+") as cf:
cf.write(pretty_html)
def create_str_node_ctx_idx(self, cov_ct_idx):
prefixed_zeros = "0" * (len("00000") - len(cov_ct_idx))
return f"{prefixed_zeros}{cov_ct_idx}"
def get_fuzz_blockers(
self,
profile: fuzz_data_loader.FuzzerProfile,
max_blockers_to_extract=999):
"""Gets a list of fuzz blockers"""
blocker_list: List[fuzz_cfg_load.CalltreeCallsite] = list()
# Extract all callsites in calltree and exit early if none
all_callsites = fuzz_cfg_load.extract_all_callsites(profile.function_call_depths)
if len(all_callsites) == 0:
return blocker_list
# Filter nodes that has forward reds. Extract maximum max_blockers_to_extract nodes.
nodes_sorted_by_red_ahead = sorted(all_callsites,
key=lambda x: x.cov_forward_reds,
reverse=True)
for node in nodes_sorted_by_red_ahead:
if node.cov_forward_reds == 0 or len(blocker_list) >= max_blockers_to_extract:
break
blocker_list.append(node)
return blocker_list
def create_fuzz_blocker_table(
self,
profile: fuzz_data_loader.FuzzerProfile,
tables: List[str],
calltree_file_name: str,
fuzz_blockers=None) -> Optional[str]:
"""
Creates HTML string for table showing fuzz blockers.
"""
logger.info("Creating fuzz blocker table")
# Get the fuzz blockers
if fuzz_blockers is None:
fuzz_blockers = self.get_fuzz_blockers(
profile,
max_blockers_to_extract=12
)
if len(fuzz_blockers) == 0:
return None
html_table_string = "<p class='no-top-margin'>The followings nodes " \
"represent call sites where fuzz blockers occur</p>"
tables.append(f"myTable{len(tables)}")
html_table_string += fuzz_html_helpers.html_create_table_head(
tables[-1],
[
("Amount of callsites blocked",
"Total amount of callsites blocked"),
("Calltree index",
"Index in call tree where the fuzz blocker is."),
("Parent function",
"Function in which the call site that blocks resides."),
("Callsite",
""),
("Largest blocked function",
"This is the function with highest cyclomatiic complexity amongst"
"all of the functions that are blocked. As such, it's a way of "
"highlighting a potentially important function being blocked")
],
sort_by_column=0,
sort_order="desc"
)
for node in fuzz_blockers:
link_prefix = "0" * (5 - len(str(node.cov_ct_idx)))
node_link = "%s?scrollToNode=%s%s" % (
calltree_file_name,
link_prefix,
node.cov_ct_idx
)
html_table_string += fuzz_html_helpers.html_table_add_row([
str(node.cov_forward_reds),
str(node.cov_ct_idx),
node.cov_parent,
f"<a href={node_link}>call site</a>",
node.cov_largest_blocked_func
])
html_table_string += "</table>"
return html_table_string
| ossf__fuzz-introspector |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 101