Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def _absolutePaths(self, paths):
slashes = [p.replace('\\', '/') for p in paths]
stripped = [p.replace('../', '') if p.startswith('../') else p for p in slashes]
return list([p if (os.path.isabs(p) or '/' not in p) else os.path.join(self.engineRoot, self.engineSourceDir, p) for p in stripped]) | [
"\n\t\tConverts the supplied list of paths to absolute pathnames (except for pure filenames without leading relative directories)\n\t\t"
]
|
Please provide a description of the function:def _flatten(self, field, items, transform = None):
# Retrieve the value for each item in the iterable
values = [item[field] for item in items]
# Flatten any nested lists
flattened = []
for value in values:
flattened.extend([value] if isinstance(value, str) else value)
# Apply any supplied transformation function
return transform(flattened) if transform != None else flattened | [
"\n\t\tExtracts the entry `field` from each item in the supplied iterable, flattening any nested lists\n\t\t"
]
|
Please provide a description of the function:def _getThirdPartyLibs(self, platformIdentifier, configuration):
# If we have previously cached the library list for the current engine version, use the cached data
cachedList = CachedDataManager.getCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries')
if cachedList != None:
return cachedList
# Create a temp directory to hold the JSON file
tempDir = tempfile.mkdtemp()
jsonFile = os.path.join(tempDir, 'ubt_output.json')
# Installed Builds of the Engine only contain a small handful of third-party libraries, rather than the full set
# included in a source build of the Engine. However, if the ThirdParty directory from a source build is copied
# into an Installed Build and the `InstalledBuild.txt` sentinel file is temporarily renamed, we can get the best
# of both worlds and utilise the full set of third-party libraries. Enable this sentinel renaming behaviour only
# if you have copied the ThirdParty directory from a source build into your Installed Build, or else the UBT
# command will fail trying to rebuild UnrealHeaderTool.
sentinelFile = os.path.join(self.engineRoot, 'Engine', 'Build', 'InstalledBuild.txt')
sentinelBackup = sentinelFile + '.bak'
renameSentinel = os.path.exists(sentinelFile) and os.environ.get('UE4CLI_SENTINEL_RENAME', '0') == '1'
if renameSentinel == True:
shutil.move(sentinelFile, sentinelBackup)
# Invoke UnrealBuildTool in JSON export mode (make sure we specify gathering mode, since this is a prerequisite of JSON export)
# (Ensure we always perform sentinel file cleanup even when errors occur)
try:
args = ['-Mode=JsonExport', '-OutputFile=' +jsonFile ] if self.engineVersion['MinorVersion'] >= 22 else ['-gather', '-jsonexport=' + jsonFile, '-SkipBuild']
self.runUBTFunc('UE4Editor', platformIdentifier, configuration, args)
finally:
if renameSentinel == True:
shutil.move(sentinelBackup, sentinelFile)
# Parse the JSON output
result = json.loads(Utility.readFile(jsonFile))
# Extract the list of third-party library modules
# (Note that since UE4.21, modules no longer have a "Type" field, so we must
# rely on the "Directory" field filter below to identify third-party libraries)
modules = [result['Modules'][key] for key in result['Modules']]
# Filter out any modules from outside the Engine/Source/ThirdParty directory
thirdPartyRoot = os.path.join(self.engineRoot, 'Engine', 'Source', 'ThirdParty')
thirdparty = list([m for m in modules if thirdPartyRoot in m['Directory']])
# Remove the temp directory
try:
shutil.rmtree(tempDir)
except:
pass
# Cache the list of libraries for use by subsequent runs
CachedDataManager.setCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries', thirdparty)
return thirdparty | [
"\n\t\tRuns UnrealBuildTool in JSON export mode and extracts the list of third-party libraries\n\t\t"
]
|
Please provide a description of the function:def processLibraryDetails(details):
# If the header include directories list contains any directories we have flags for, add them
for includeDir in details.includeDirs:
# If the directory path matches any of the substrings in our list, generate the relevant flags
for pattern in CUSTOM_FLAGS_FOR_INCLUDE_DIRS:
if pattern in includeDir:
flag = '-D' + CUSTOM_FLAGS_FOR_INCLUDE_DIRS[pattern] + '=' + includeDir
details.cmakeFlags.append(flag)
# If the libraries list contains any libs we have flags for, add them
for lib in details.libs:
# Extract the name of the library from the filename
# (We remove any "lib" prefix or numerical suffix)
filename = os.path.basename(lib)
(name, ext) = os.path.splitext(filename)
libName = name.replace('lib', '') if name.startswith('lib') else name
libName = libName.rstrip('_-1234567890')
# If the library name matches one in our list, generate its flag
if libName in CUSTOM_FLAGS_FOR_LIBS:
flag = '-D' + CUSTOM_FLAGS_FOR_LIBS[libName] + '=' + lib
details.cmakeFlags.append(flag) | [
"\n\t\tProcesses the supplied ThirdPartyLibraryDetails instance and sets any custom CMake flags\n\t\t"
]
|
Please provide a description of the function:def getPlugins():
# Retrieve the list of detected entry points in the ue4cli.plugins group
plugins = {
entry_point.name: entry_point.load()
for entry_point
in pkg_resources.iter_entry_points('ue4cli.plugins')
}
# Filter out any invalid plugins
plugins = {
name: plugins[name]
for name in plugins
if
'action' in plugins[name] and
'description' in plugins[name] and
'args' in plugins[name] and
callable(plugins[name]['action']) == True and
len(signature(plugins[name]['action']).parameters) == 2
}
return plugins | [
"\n\t\tReturns the list of valid ue4cli plugins\n\t\t"
]
|
Please provide a description of the function:def getCompilerFlags(self, engineRoot, fmt):
return Utility.join(
fmt.delim,
self.prefixedStrings(self.definitionPrefix, self.definitions, engineRoot) +
self.prefixedStrings(self.includeDirPrefix, self.includeDirs, engineRoot) +
self.resolveRoot(self.cxxFlags, engineRoot),
fmt.quotes
) | [
"\n\t\tConstructs the compiler flags string for building against this library\n\t\t"
]
|
Please provide a description of the function:def getLinkerFlags(self, engineRoot, fmt, includeLibs=True):
components = self.resolveRoot(self.ldFlags, engineRoot)
if includeLibs == True:
components.extend(self.prefixedStrings(self.linkerDirPrefix, self.linkDirs, engineRoot))
components.extend(self.resolveRoot(self.libs, engineRoot))
return Utility.join(fmt.delim, components, fmt.quotes) | [
"\n\t\tConstructs the linker flags string for building against this library\n\t\t"
]
|
Please provide a description of the function:def getPrefixDirectories(self, engineRoot, delimiter=' '):
return delimiter.join(self.resolveRoot(self.prefixDirs, engineRoot)) | [
"\n\t\tReturns the list of prefix directories for this library, joined using the specified delimiter\n\t\t"
]
|
Please provide a description of the function:def getIncludeDirectories(self, engineRoot, delimiter=' '):
return delimiter.join(self.resolveRoot(self.includeDirs, engineRoot)) | [
"\n\t\tReturns the list of include directories for this library, joined using the specified delimiter\n\t\t"
]
|
Please provide a description of the function:def getLinkerDirectories(self, engineRoot, delimiter=' '):
return delimiter.join(self.resolveRoot(self.linkDirs, engineRoot)) | [
"\n\t\tReturns the list of linker directories for this library, joined using the specified delimiter\n\t\t"
]
|
Please provide a description of the function:def getLibraryFiles(self, engineRoot, delimiter=' '):
return delimiter.join(self.resolveRoot(self.libs, engineRoot)) | [
"\n\t\tReturns the list of library files for this library, joined using the specified delimiter\n\t\t"
]
|
Please provide a description of the function:def getPreprocessorDefinitions(self, engineRoot, delimiter=' '):
return delimiter.join(self.resolveRoot(self.definitions, engineRoot)) | [
"\n\t\tReturns the list of preprocessor definitions for this library, joined using the specified delimiter\n\t\t"
]
|
Please provide a description of the function:def getCMakeFlags(self, engineRoot, fmt):
return Utility.join(
fmt.delim,
[
'-DCMAKE_PREFIX_PATH=' + self.getPrefixDirectories(engineRoot, ';'),
'-DCMAKE_INCLUDE_PATH=' + self.getIncludeDirectories(engineRoot, ';'),
'-DCMAKE_LIBRARY_PATH=' + self.getLinkerDirectories(engineRoot, ';'),
] + self.resolveRoot(self.cmakeFlags, engineRoot),
fmt.quotes
) | [
"\n\t\tConstructs the CMake invocation flags string for building against this library\n\t\t"
]
|
Please provide a description of the function:def is_changed():
executed, changed_lines = execute_git('status --porcelain', output=False)
merge_not_finished = mod_path.exists('.git/MERGE_HEAD')
return changed_lines.strip() or merge_not_finished | [
" Checks if current project has any noncommited changes. "
]
|
Please provide a description of the function:def user_agent():
client_name = 'unknown_client_name'
try:
client_name = os.environ.get("EDX_REST_API_CLIENT_NAME") or socket.gethostbyname(socket.gethostname())
except: # pylint: disable=bare-except
pass # using 'unknown_client_name' is good enough. no need to log.
return "{} edx-rest-api-client/{} {}".format(
requests.utils.default_user_agent(), # e.g. "python-requests/2.9.1"
__version__, # version of this client
client_name
) | [
"\n Return a User-Agent that identifies this client.\n\n Example:\n python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce\n\n The last item in the list will be the application name, taken from the\n OS environment variable EDX_REST_API_CLIENT_NAME. If that environment\n variable is not set, it will default to the hostname.\n "
]
|
Please provide a description of the function:def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials',
refresh_token=None):
now = datetime.datetime.utcnow()
data = {
'grant_type': grant_type,
'client_id': client_id,
'client_secret': client_secret,
'token_type': token_type,
}
if refresh_token:
data['refresh_token'] = refresh_token
else:
assert grant_type != 'refresh_token', "refresh_token parameter required"
response = requests.post(
url,
data=data,
headers={
'User-Agent': USER_AGENT,
},
)
data = response.json()
try:
access_token = data['access_token']
expires_in = data['expires_in']
except KeyError:
raise requests.RequestException(response=response)
expires_at = now + datetime.timedelta(seconds=expires_in)
return access_token, expires_at | [
" Retrieves OAuth 2.0 access token using the given grant type.\n\n Args:\n url (str): Oauth2 access token endpoint\n client_id (str): client ID\n client_secret (str): client secret\n Kwargs:\n token_type (str): Type of token to return. Options include bearer and jwt.\n grant_type (str): One of 'client_credentials' or 'refresh_token'\n refresh_token (str): The previous access token (for grant_type=refresh_token)\n\n Returns:\n tuple: Tuple containing access token string and expiration datetime.\n "
]
|
Please provide a description of the function:def request(self, method, url, **kwargs): # pylint: disable=arguments-differ
self._check_auth()
return super(OAuthAPIClient, self).request(method, url, **kwargs) | [
"\n Overrides Session.request to ensure that the session is authenticated\n "
]
|
Please provide a description of the function:def run_command(self, scan_id, host, cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
options = self.get_scan_options(scan_id)
port = int(options['port'])
timeout = int(options['ssh_timeout'])
# For backward compatibility, consider the legacy mode to get
# credentials as scan_option.
# First and second modes should be removed in future releases.
# On the third case it receives the credentials as a subelement of
# the <target>.
credentials = self.get_scan_credentials(scan_id, host)
if ('username_password' in options and
':' in options['username_password']):
username, password = options['username_password'].split(':', 1)
elif 'username' in options and options['username']:
username = options['username']
password = options['password']
elif credentials:
cred_params = credentials.get('ssh')
username = cred_params.get('username', '')
password = cred_params.get('password', '')
else:
self.add_scan_error(scan_id, host=host,
value='Erroneous username_password value')
raise ValueError('Erroneous username_password value')
try:
ssh.connect(hostname=host, username=username, password=password,
timeout=timeout, port=port)
except (paramiko.ssh_exception.AuthenticationException,
socket.error) as err:
# Errors: No route to host, connection timeout, authentication
# failure etc,.
self.add_scan_error(scan_id, host=host, value=str(err))
return None
_, stdout, _ = ssh.exec_command(cmd)
result = stdout.readlines()
ssh.close()
return result | [
"\n Run a single command via SSH and return the content of stdout or\n None in case of an Error. A scan error is issued in the latter\n case.\n\n For logging into 'host', the scan options 'port', 'username',\n 'password' and 'ssh_timeout' are used.\n "
]
|
Please provide a description of the function:def get_result_xml(result):
result_xml = Element('result')
for name, value in [('name', result['name']),
('type', ResultType.get_str(result['type'])),
('severity', result['severity']),
('host', result['host']),
('test_id', result['test_id']),
('port', result['port']),
('qod', result['qod'])]:
result_xml.set(name, str(value))
result_xml.text = result['value']
return result_xml | [
" Formats a scan result to XML format.\n\n Arguments:\n result (dict): Dictionary with a scan result.\n\n Return:\n Result as xml element object.\n "
]
|
Please provide a description of the function:def simple_response_str(command, status, status_text, content=""):
response = Element('%s_response' % command)
for name, value in [('status', str(status)), ('status_text', status_text)]:
response.set(name, str(value))
if isinstance(content, list):
for elem in content:
response.append(elem)
elif isinstance(content, Element):
response.append(content)
else:
response.text = content
return tostring(response) | [
" Creates an OSP response XML string.\n\n Arguments:\n command (str): OSP Command to respond to.\n status (int): Status of the response.\n status_text (str): Status text of the response.\n content (str): Text part of the response XML element.\n\n Return:\n String of response in xml format.\n "
]
|
Please provide a description of the function:def bind_socket(address, port):
assert address
assert port
bindsocket = socket.socket()
try:
bindsocket.bind((address, port))
except socket.error:
logger.error("Couldn't bind socket on %s:%s", address, port)
return None
logger.info('Listening on %s:%s', address, port)
bindsocket.listen(0)
return bindsocket | [
" Returns a socket bound on (address:port). "
]
|
Please provide a description of the function:def bind_unix_socket(path):
assert path
bindsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.unlink(path)
except OSError:
if os.path.exists(path):
raise
try:
bindsocket.bind(path)
except socket.error:
logger.error("Couldn't bind socket on %s", path)
return None
logger.info('Listening on %s', path)
bindsocket.listen(0)
return bindsocket | [
" Returns a unix file socket bound on (path). "
]
|
Please provide a description of the function:def close_client_stream(client_stream, unix_path):
try:
client_stream.shutdown(socket.SHUT_RDWR)
if unix_path:
logger.debug('%s: Connection closed', unix_path)
else:
peer = client_stream.getpeername()
logger.debug('%s:%s: Connection closed', peer[0], peer[1])
except (socket.error, OSError) as exception:
logger.debug('Connection closing error: %s', exception)
client_stream.close() | [
" Closes provided client stream "
]
|
Please provide a description of the function:def set_command_attributes(self, name, attributes):
if self.command_exists(name):
command = self.commands.get(name)
command['attributes'] = attributes | [
" Sets the xml attributes of a specified command. "
]
|
Please provide a description of the function:def add_scanner_param(self, name, scanner_param):
assert name
assert scanner_param
self.scanner_params[name] = scanner_param
command = self.commands.get('start_scan')
command['elements'] = {
'scanner_params':
{k: v['name'] for k, v in self.scanner_params.items()}} | [
" Add a scanner parameter. "
]
|
Please provide a description of the function:def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None,
custom=None, vt_creation_time=None, vt_modification_time=None,
vt_dependencies=None, summary=None, impact=None, affected=None,
insight=None, solution=None, solution_t=None, detection=None,
qod_t=None, qod_v=None, severities=None):
if not vt_id:
return -2 # no valid vt_id
if self.vt_id_pattern.fullmatch(vt_id) is None:
return -2 # no valid vt_id
if vt_id in self.vts:
return -1 # The VT was already in the list.
if name is None:
name = ''
self.vts[vt_id] = {'name': name}
if custom is not None:
self.vts[vt_id]["custom"] = custom
if vt_params is not None:
self.vts[vt_id]["vt_params"] = vt_params
if vt_refs is not None:
self.vts[vt_id]["vt_refs"] = vt_refs
if vt_dependencies is not None:
self.vts[vt_id]["vt_dependencies"] = vt_dependencies
if vt_creation_time is not None:
self.vts[vt_id]["creation_time"] = vt_creation_time
if vt_modification_time is not None:
self.vts[vt_id]["modification_time"] = vt_modification_time
if summary is not None:
self.vts[vt_id]["summary"] = summary
if impact is not None:
self.vts[vt_id]["impact"] = impact
if affected is not None:
self.vts[vt_id]["affected"] = affected
if insight is not None:
self.vts[vt_id]["insight"] = insight
if solution is not None:
self.vts[vt_id]["solution"] = solution
if solution_t is not None:
self.vts[vt_id]["solution_type"] = solution_t
if detection is not None:
self.vts[vt_id]["detection"] = detection
if qod_t is not None:
self.vts[vt_id]["qod_type"] = qod_t
elif qod_v is not None:
self.vts[vt_id]["qod"] = qod_v
if severities is not None:
self.vts[vt_id]["severities"] = severities
return len(self.vts) | [
" Add a vulnerability test information.\n\n Returns: The new number of stored VTs.\n -1 in case the VT ID was already present and thus the\n new VT was not considered.\n -2 in case the vt_id was invalid.\n "
]
|
Please provide a description of the function:def _preprocess_scan_params(self, xml_params):
params = {}
for param in xml_params:
params[param.tag] = param.text or ''
# Set default values.
for key in self.scanner_params:
if key not in params:
params[key] = self.get_scanner_param_default(key)
if self.get_scanner_param_type(key) == 'selection':
params[key] = params[key].split('|')[0]
# Validate values.
for key in params:
param_type = self.get_scanner_param_type(key)
if not param_type:
continue
if param_type in ['integer', 'boolean']:
try:
params[key] = int(params[key])
except ValueError:
raise OSPDError('Invalid %s value' % key, 'start_scan')
if param_type == 'boolean':
if params[key] not in [0, 1]:
raise OSPDError('Invalid %s value' % key, 'start_scan')
elif param_type == 'selection':
selection = self.get_scanner_param_default(key).split('|')
if params[key] not in selection:
raise OSPDError('Invalid %s value' % key, 'start_scan')
if self.get_scanner_param_mandatory(key) and params[key] == '':
raise OSPDError('Mandatory %s value is missing' % key,
'start_scan')
return params | [
" Processes the scan parameters. "
]
|
Please provide a description of the function:def process_vts_params(self, scanner_vts):
vt_selection = {}
filters = list()
for vt in scanner_vts:
if vt.tag == 'vt_single':
vt_id = vt.attrib.get('id')
vt_selection[vt_id] = {}
for vt_value in vt:
if not vt_value.attrib.get('id'):
raise OSPDError('Invalid VT preference. No attribute id',
'start_scan')
vt_value_id = vt_value.attrib.get('id')
vt_value_value = vt_value.text if vt_value.text else ''
vt_selection[vt_id][vt_value_id] = vt_value_value
if vt.tag == 'vt_group':
vts_filter = vt.attrib.get('filter', None)
if vts_filter is None:
raise OSPDError('Invalid VT group. No filter given.',
'start_scan')
filters.append(vts_filter)
vt_selection['vt_groups'] = filters
return vt_selection | [
" Receive an XML object with the Vulnerability Tests an their\n parameters to be use in a scan and return a dictionary.\n\n @param: XML element with vt subelements. Each vt has an\n id attribute. Optional parameters can be included\n as vt child.\n Example form:\n <vt_selection>\n <vt_single id='vt1' />\n <vt_single id='vt2'>\n <vt_value id='param1'>value</vt_value>\n </vt_single>\n <vt_group filter='family=debian'/>\n <vt_group filter='family=general'/>\n </vt_selection>\n\n @return: Dictionary containing the vts attribute and subelements,\n like the VT's id and VT's parameters.\n Example form:\n {'vt1': {},\n 'vt2': {'value_id': 'value'},\n 'vt_groups': ['family=debian', 'family=general']}\n "
]
|
Please provide a description of the function:def process_credentials_elements(cred_tree):
credentials = {}
for credential in cred_tree:
service = credential.attrib.get('service')
credentials[service] = {}
credentials[service]['type'] = credential.attrib.get('type')
if service == 'ssh':
credentials[service]['port'] = credential.attrib.get('port')
for param in credential:
credentials[service][param.tag] = param.text
return credentials | [
" Receive an XML object with the credentials to run\n a scan against a given target.\n\n @param:\n <credentials>\n <credential type=\"up\" service=\"ssh\" port=\"22\">\n <username>scanuser</username>\n <password>mypass</password>\n </credential>\n <credential type=\"up\" service=\"smb\">\n <username>smbuser</username>\n <password>mypass</password>\n </credential>\n </credentials>\n\n @return: Dictionary containing the credentials for a given target.\n Example form:\n {'ssh': {'type': type,\n 'port': port,\n 'username': username,\n 'password': pass,\n },\n 'smb': {'type': type,\n 'username': username,\n 'password': pass,\n },\n }\n "
]
|
Please provide a description of the function:def process_targets_element(cls, scanner_target):
target_list = []
for target in scanner_target:
ports = ''
credentials = {}
for child in target:
if child.tag == 'hosts':
hosts = child.text
if child.tag == 'ports':
ports = child.text
if child.tag == 'credentials':
credentials = cls.process_credentials_elements(child)
if hosts:
target_list.append([hosts, ports, credentials])
else:
raise OSPDError('No target to scan', 'start_scan')
return target_list | [
" Receive an XML object with the target, ports and credentials to run\n a scan against.\n\n @param: XML element with target subelements. Each target has <hosts>\n and <ports> subelements. Hosts can be a single host, a host range,\n a comma-separated host list or a network address.\n <ports> and <credentials> are optional. Therefore each ospd-scanner\n should check for a valid ones if needed.\n\n Example form:\n <targets>\n <target>\n <hosts>localhosts</hosts>\n <ports>80,443</ports>\n </target>\n <target>\n <hosts>192.168.0.0/24</hosts>\n <ports>22</ports>\n <credentials>\n <credential type=\"up\" service=\"ssh\" port=\"22\">\n <username>scanuser</username>\n <password>mypass</password>\n </credential>\n <credential type=\"up\" service=\"smb\">\n <username>smbuser</username>\n <password>mypass</password>\n </credential>\n </credentials>\n </target>\n </targets>\n\n @return: A list of (hosts, port) tuples.\n Example form:\n [['localhost', '80,43'],\n ['192.168.0.0/24', '22', {'smb': {'type': type,\n 'port': port,\n 'username': username,\n 'password': pass,\n }}]]\n "
]
|
Please provide a description of the function:def handle_start_scan_command(self, scan_et):
target_str = scan_et.attrib.get('target')
ports_str = scan_et.attrib.get('ports')
# For backward compatibility, if target and ports attributes are set,
# <targets> element is ignored.
if target_str is None or ports_str is None:
target_list = scan_et.find('targets')
if target_list is None or not target_list:
raise OSPDError('No targets or ports', 'start_scan')
else:
scan_targets = self.process_targets_element(target_list)
else:
scan_targets = []
for single_target in target_str_to_list(target_str):
scan_targets.append([single_target, ports_str, ''])
scan_id = scan_et.attrib.get('scan_id')
if scan_id is not None and scan_id != '' and not valid_uuid(scan_id):
raise OSPDError('Invalid scan_id UUID', 'start_scan')
try:
parallel = int(scan_et.attrib.get('parallel', '1'))
if parallel < 1 or parallel > 20:
parallel = 1
except ValueError:
raise OSPDError('Invalid value for parallel scans. '
'It must be a number', 'start_scan')
scanner_params = scan_et.find('scanner_params')
if scanner_params is None:
raise OSPDError('No scanner_params element', 'start_scan')
params = self._preprocess_scan_params(scanner_params)
# VTS is an optional element. If present should not be empty.
vt_selection = {}
scanner_vts = scan_et.find('vt_selection')
if scanner_vts is not None:
if not scanner_vts:
raise OSPDError('VTs list is empty', 'start_scan')
else:
vt_selection = self.process_vts_params(scanner_vts)
# Dry run case.
if 'dry_run' in params and int(params['dry_run']):
scan_func = self.dry_run_scan
scan_params = None
else:
scan_func = self.start_scan
scan_params = self.process_scan_params(params)
scan_id = self.create_scan(scan_id, scan_targets,
scan_params, vt_selection)
scan_process = multiprocessing.Process(target=scan_func,
args=(scan_id,
scan_targets,
parallel))
self.scan_processes[scan_id] = scan_process
scan_process.start()
id_ = Element('id')
id_.text = scan_id
return simple_response_str('start_scan', 200, 'OK', id_) | [
" Handles <start_scan> command.\n\n @return: Response string for <start_scan> command.\n "
]
|
Please provide a description of the function:def handle_stop_scan_command(self, scan_et):
scan_id = scan_et.attrib.get('scan_id')
if scan_id is None or scan_id == '':
raise OSPDError('No scan_id attribute', 'stop_scan')
self.stop_scan(scan_id)
return simple_response_str('stop_scan', 200, 'OK') | [
" Handles <stop_scan> command.\n\n @return: Response string for <stop_scan> command.\n "
]
|
Please provide a description of the function:def finish_scan(self, scan_id):
self.set_scan_progress(scan_id, 100)
self.set_scan_status(scan_id, ScanStatus.FINISHED)
logger.info("%s: Scan finished.", scan_id) | [
" Sets a scan as finished. "
]
|
Please provide a description of the function:def get_scanner_param_type(self, param):
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return None
return entry.get('type') | [
" Returns type of a scanner parameter. "
]
|
Please provide a description of the function:def get_scanner_param_mandatory(self, param):
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return False
return entry.get('mandatory') | [
" Returns if a scanner parameter is mandatory. "
]
|
Please provide a description of the function:def get_scanner_param_default(self, param):
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return None
return entry.get('default') | [
" Returns default value of a scanner parameter. "
]
|
Please provide a description of the function:def get_scanner_params_xml(self):
scanner_params = Element('scanner_params')
for param_id, param in self.scanner_params.items():
param_xml = SubElement(scanner_params, 'scanner_param')
for name, value in [('id', param_id),
('type', param['type'])]:
param_xml.set(name, value)
for name, value in [('name', param['name']),
('description', param['description']),
('default', param['default']),
('mandatory', param['mandatory'])]:
elem = SubElement(param_xml, name)
elem.text = str(value)
return scanner_params | [
" Returns the OSP Daemon's scanner params in xml format. "
]
|
Please provide a description of the function:def new_client_stream(self, sock):
assert sock
newsocket, fromaddr = sock.accept()
logger.debug("New connection from"
" %s:%s", fromaddr[0], fromaddr[1])
# NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest
# protocol version that both the client and server support. In modern
# Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3
# being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for
# PROTOCOL_TLS which should be used once compatibility with Python 3.4
# is no longer desired.
try:
ssl_socket = ssl.wrap_socket(newsocket, cert_reqs=ssl.CERT_REQUIRED,
server_side=True,
certfile=self.certs['cert_file'],
keyfile=self.certs['key_file'],
ca_certs=self.certs['ca_file'],
ssl_version=ssl.PROTOCOL_SSLv23)
except (ssl.SSLError, socket.error) as message:
logger.error(message)
return None
return ssl_socket | [
" Returns a new ssl client stream from bind_socket. "
]
|
Please provide a description of the function:def write_to_stream(stream, response, block_len=1024):
try:
i_start = 0
i_end = block_len
while True:
if i_end > len(response):
stream(response[i_start:])
break
stream(response[i_start:i_end])
i_start = i_end
i_end += block_len
except (socket.timeout, socket.error) as exception:
logger.debug('Error sending response to the client: %s', exception) | [
"\n Send the response in blocks of the given len using the\n passed method dependending on the socket type.\n "
]
|
Please provide a description of the function:def handle_client_stream(self, stream, is_unix=False):
assert stream
data = []
stream.settimeout(2)
while True:
try:
if is_unix:
buf = stream.recv(1024)
else:
buf = stream.read(1024)
if not buf:
break
data.append(buf)
except (AttributeError, ValueError) as message:
logger.error(message)
return
except (ssl.SSLError) as exception:
logger.debug('Error: %s', exception[0])
break
except (socket.timeout) as exception:
logger.debug('Error: %s', exception)
break
data = b''.join(data)
if len(data) <= 0:
logger.debug("Empty client stream")
return
try:
response = self.handle_command(data)
except OSPDError as exception:
response = exception.as_xml()
logger.debug('Command error: %s', exception.message)
except Exception:
logger.exception('While handling client command:')
exception = OSPDError('Fatal error', 'error')
response = exception.as_xml()
if is_unix:
send_method = stream.send
else:
send_method = stream.write
self.write_to_stream(send_method, response) | [
" Handles stream of data received from client. "
]
|
Please provide a description of the function:def parallel_scan(self, scan_id, target):
try:
ret = self.exec_scan(scan_id, target)
if ret == 0:
self.add_scan_host_detail(scan_id, name='host_status',
host=target, value='0')
elif ret == 1:
self.add_scan_host_detail(scan_id, name='host_status',
host=target, value='1')
elif ret == 2:
self.add_scan_host_detail(scan_id, name='host_status',
host=target, value='2')
else:
logger.debug('%s: No host status returned', target)
except Exception as e:
self.add_scan_error(scan_id, name='', host=target,
value='Host process failure (%s).' % e)
logger.exception('While scanning %s:', target)
else:
logger.info("%s: Host scan finished.", target) | [
" Starts the scan with scan_id. "
]
|
Please provide a description of the function:def check_pending_target(self, scan_id, multiscan_proc):
for running_target_proc, running_target_id in multiscan_proc:
if not running_target_proc.is_alive():
target_prog = self.get_scan_target_progress(
scan_id, running_target_id)
if target_prog < 100:
self.stop_scan(scan_id)
running_target = (running_target_proc, running_target_id)
multiscan_proc.remove(running_target)
return multiscan_proc | [
" Check if a scan process is still alive. In case the process\n finished or is stopped, removes the process from the multiscan\n _process list.\n Processes dead and with progress < 100% are considered stopped\n or with failures. Then will try to stop the other runnings (target)\n scans owned by the same task.\n\n @input scan_id Scan_id of the whole scan.\n @input multiscan_proc A list with the scan process which\n may still be alive.\n\n @return Actualized list with current runnging scan processes.\n "
]
|
Please provide a description of the function:def calculate_progress(self, scan_id):
t_prog = dict()
for target in self.get_scan_target(scan_id):
t_prog[target] = self.get_scan_target_progress(scan_id, target)
return sum(t_prog.values())/len(t_prog) | [
" Calculate the total scan progress from the\n partial target progress. "
]
|
Please provide a description of the function:def start_scan(self, scan_id, targets, parallel=1):
os.setsid()
multiscan_proc = []
logger.info("%s: Scan started.", scan_id)
target_list = targets
if target_list is None or not target_list:
raise OSPDError('Erroneous targets list', 'start_scan')
for index, target in enumerate(target_list):
while len(multiscan_proc) >= parallel:
progress = self.calculate_progress(scan_id)
self.set_scan_progress(scan_id, progress)
multiscan_proc = self.check_pending_target(scan_id,
multiscan_proc)
time.sleep(1)
#If the scan status is stopped, does not launch anymore target scans
if self.get_scan_status(scan_id) == ScanStatus.STOPPED:
return
logger.info("%s: Host scan started on ports %s.", target[0], target[1])
scan_process = multiprocessing.Process(target=self.parallel_scan,
args=(scan_id, target[0]))
multiscan_proc.append((scan_process, target[0]))
scan_process.start()
self.set_scan_status(scan_id, ScanStatus.RUNNING)
# Wait until all single target were scanned
while multiscan_proc:
multiscan_proc = self.check_pending_target(scan_id, multiscan_proc)
if multiscan_proc:
progress = self.calculate_progress(scan_id)
self.set_scan_progress(scan_id, progress)
time.sleep(1)
# Only set the scan as finished if the scan was not stopped.
if self.get_scan_status(scan_id) != ScanStatus.STOPPED:
self.finish_scan(scan_id) | [
" Handle N parallel scans if 'parallel' is greater than 1. "
]
|
Please provide a description of the function:def dry_run_scan(self, scan_id, targets):
os.setsid()
for _, target in enumerate(targets):
host = resolve_hostname(target[0])
if host is None:
logger.info("Couldn't resolve %s.", target[0])
continue
port = self.get_scan_ports(scan_id, target=target[0])
logger.info("%s:%s: Dry run mode.", host, port)
self.add_scan_log(scan_id, name='', host=host,
value='Dry run result')
self.finish_scan(scan_id) | [
" Dry runs a scan. "
]
|
Please provide a description of the function:def handle_timeout(self, scan_id, host):
self.add_scan_error(scan_id, host=host, name="Timeout",
value="{0} exec timeout."
.format(self.get_scanner_name())) | [
" Handles scanner reaching timeout error. "
]
|
Please provide a description of the function:def set_scan_host_finished(self, scan_id, target, host):
self.scan_collection.set_host_finished(scan_id, target, host) | [
" Add the host in a list of finished hosts "
]
|
Please provide a description of the function:def set_scan_target_progress(
self, scan_id, target, host, progress):
self.scan_collection.set_target_progress(
scan_id, target, host, progress) | [
" Sets host's progress which is part of target. "
]
|
Please provide a description of the function:def handle_get_scans_command(self, scan_et):
scan_id = scan_et.attrib.get('scan_id')
details = scan_et.attrib.get('details')
pop_res = scan_et.attrib.get('pop_results')
if details and details == '0':
details = False
else:
details = True
if pop_res and pop_res == '1':
pop_res = True
else:
pop_res = False
responses = []
if scan_id and scan_id in self.scan_collection.ids_iterator():
self.check_scan_process(scan_id)
scan = self.get_scan_xml(scan_id, details, pop_res)
responses.append(scan)
elif scan_id:
text = "Failed to find scan '{0}'".format(scan_id)
return simple_response_str('get_scans', 404, text)
else:
for scan_id in self.scan_collection.ids_iterator():
self.check_scan_process(scan_id)
scan = self.get_scan_xml(scan_id, details, pop_res)
responses.append(scan)
return simple_response_str('get_scans', 200, 'OK', responses) | [
" Handles <get_scans> command.\n\n @return: Response string for <get_scans> command.\n "
]
|
Please provide a description of the function:def handle_get_vts_command(self, vt_et):
vt_id = vt_et.attrib.get('vt_id')
vt_filter = vt_et.attrib.get('filter')
if vt_id and vt_id not in self.vts:
text = "Failed to find vulnerability test '{0}'".format(vt_id)
return simple_response_str('get_vts', 404, text)
filtered_vts = None
if vt_filter:
filtered_vts = self.vts_filter.get_filtered_vts_list(
self.vts, vt_filter)
responses = []
vts_xml = self.get_vts_xml(vt_id, filtered_vts)
responses.append(vts_xml)
return simple_response_str('get_vts', 200, 'OK', responses) | [
" Handles <get_vts> command.\n\n @return: Response string for <get_vts> command.\n "
]
|
Please provide a description of the function:def handle_help_command(self, scan_et):
help_format = scan_et.attrib.get('format')
if help_format is None or help_format == "text":
# Default help format is text.
return simple_response_str('help', 200, 'OK',
self.get_help_text())
elif help_format == "xml":
text = self.get_xml_str(self.commands)
return simple_response_str('help', 200, 'OK', text)
raise OSPDError('Bogus help format', 'help') | [
" Handles <help> command.\n\n @return: Response string for <help> command.\n "
]
|
Please provide a description of the function:def get_help_text(self):
txt = str('\n')
for name, info in self.commands.items():
command_txt = "\t{0: <22} {1}\n".format(name, info['description'])
if info['attributes']:
command_txt = ''.join([command_txt, "\t Attributes:\n"])
for attrname, attrdesc in info['attributes'].items():
attr_txt = "\t {0: <22} {1}\n".format(attrname, attrdesc)
command_txt = ''.join([command_txt, attr_txt])
if info['elements']:
command_txt = ''.join([command_txt, "\t Elements:\n",
self.elements_as_text(info['elements'])])
txt = ''.join([txt, command_txt])
return txt | [
" Returns the help output in plain text format."
]
|
Please provide a description of the function:def elements_as_text(self, elems, indent=2):
assert elems
text = ""
for elename, eledesc in elems.items():
if isinstance(eledesc, dict):
desc_txt = self.elements_as_text(eledesc, indent + 2)
desc_txt = ''.join(['\n', desc_txt])
elif isinstance(eledesc, str):
desc_txt = ''.join([eledesc, '\n'])
else:
assert False, "Only string or dictionary"
ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename,
desc_txt)
text = ''.join([text, ele_txt])
return text | [
" Returns the elems dictionary as formatted plain text. "
]
|
Please provide a description of the function:def handle_delete_scan_command(self, scan_et):
scan_id = scan_et.attrib.get('scan_id')
if scan_id is None:
return simple_response_str('delete_scan', 404,
'No scan_id attribute')
if not self.scan_exists(scan_id):
text = "Failed to find scan '{0}'".format(scan_id)
return simple_response_str('delete_scan', 404, text)
self.check_scan_process(scan_id)
if self.delete_scan(scan_id):
return simple_response_str('delete_scan', 200, 'OK')
raise OSPDError('Scan in progress', 'delete_scan') | [
" Handles <delete_scan> command.\n\n @return: Response string for <delete_scan> command.\n "
]
|
Please provide a description of the function:def delete_scan(self, scan_id):
if self.get_scan_status(scan_id) == ScanStatus.RUNNING:
return 0
try:
del self.scan_processes[scan_id]
except KeyError:
logger.debug('Scan process for %s not found', scan_id)
return self.scan_collection.delete_scan(scan_id) | [
" Deletes scan_id scan from collection.\n\n @return: 1 if scan deleted, 0 otherwise.\n "
]
|
Please provide a description of the function:def get_scan_results_xml(self, scan_id, pop_res):
results = Element('results')
for result in self.scan_collection.results_iterator(scan_id, pop_res):
results.append(get_result_xml(result))
logger.info('Returning %d results', len(results))
return results | [
" Gets scan_id scan's results in XML format.\n\n @return: String of scan results in xml.\n "
]
|
Please provide a description of the function:def get_xml_str(self, data):
responses = []
for tag, value in data.items():
elem = Element(tag)
if isinstance(value, dict):
for value in self.get_xml_str(value):
elem.append(value)
elif isinstance(value, list):
value = ', '.join([m for m in value])
elem.text = value
else:
elem.text = value
responses.append(elem)
return responses | [
" Creates a string in XML Format using the provided data structure.\n\n @param: Dictionary of xml tags and their elements.\n\n @return: String of data in xml format.\n "
]
|
Please provide a description of the function:def get_scan_xml(self, scan_id, detailed=True, pop_res=False):
if not scan_id:
return Element('scan')
target = ','.join(self.get_scan_target(scan_id))
progress = self.get_scan_progress(scan_id)
status = self.get_scan_status(scan_id)
start_time = self.get_scan_start_time(scan_id)
end_time = self.get_scan_end_time(scan_id)
response = Element('scan')
for name, value in [('id', scan_id),
('target', target),
('progress', progress),
('status', status.name.lower()),
('start_time', start_time),
('end_time', end_time)]:
response.set(name, str(value))
if detailed:
response.append(self.get_scan_results_xml(scan_id, pop_res))
return response | [
" Gets scan in XML format.\n\n @return: String of scan in XML format.\n "
]
|
Please provide a description of the function:def get_vt_xml(self, vt_id):
if not vt_id:
return Element('vt')
vt = self.vts.get(vt_id)
name = vt.get('name')
vt_xml = Element('vt')
vt_xml.set('id', vt_id)
for name, value in [('name', name)]:
elem = SubElement(vt_xml, name)
elem.text = str(value)
if vt.get('vt_params'):
params_xml_str = self.get_params_vt_as_xml_str(
vt_id, vt.get('vt_params'))
vt_xml.append(secET.fromstring(params_xml_str))
if vt.get('vt_refs'):
refs_xml_str = self.get_refs_vt_as_xml_str(
vt_id, vt.get('vt_refs'))
vt_xml.append(secET.fromstring(refs_xml_str))
if vt.get('vt_dependencies'):
dependencies = self.get_dependencies_vt_as_xml_str(
vt_id, vt.get('vt_dependencies'))
vt_xml.append(secET.fromstring(dependencies))
if vt.get('creation_time'):
vt_ctime = self.get_creation_time_vt_as_xml_str(
vt_id, vt.get('creation_time'))
vt_xml.append(secET.fromstring(vt_ctime))
if vt.get('modification_time'):
vt_mtime = self.get_modification_time_vt_as_xml_str(
vt_id, vt.get('modification_time'))
vt_xml.append(secET.fromstring(vt_mtime))
if vt.get('summary'):
summary_xml_str = self.get_summary_vt_as_xml_str(
vt_id, vt.get('summary'))
vt_xml.append(secET.fromstring(summary_xml_str))
if vt.get('impact'):
impact_xml_str = self.get_impact_vt_as_xml_str(
vt_id, vt.get('impact'))
vt_xml.append(secET.fromstring(impact_xml_str))
if vt.get('affected'):
affected_xml_str = self.get_affected_vt_as_xml_str(
vt_id, vt.get('affected'))
vt_xml.append(secET.fromstring(affected_xml_str))
if vt.get('insight'):
insight_xml_str = self.get_insight_vt_as_xml_str(
vt_id, vt.get('insight'))
vt_xml.append(secET.fromstring(insight_xml_str))
if vt.get('solution'):
solution_xml_str = self.get_solution_vt_as_xml_str(
vt_id, vt.get('solution'), vt.get('solution_type'))
vt_xml.append(secET.fromstring(solution_xml_str))
if vt.get('detection') or vt.get('qod_type') or vt.get('qod'):
detection_xml_str = self.get_detection_vt_as_xml_str(
vt_id, vt.get('detection'), vt.get('qod_type'), vt.get('qod'))
vt_xml.append(secET.fromstring(detection_xml_str))
if vt.get('severities'):
severities_xml_str = self.get_severities_vt_as_xml_str(
vt_id, vt.get('severities'))
vt_xml.append(secET.fromstring(severities_xml_str))
if vt.get('custom'):
custom_xml_str = self.get_custom_vt_as_xml_str(
vt_id, vt.get('custom'))
vt_xml.append(secET.fromstring(custom_xml_str))
return vt_xml | [
" Gets a single vulnerability test information in XML format.\n\n @return: String of single vulnerability test information in XML format.\n "
]
|
Please provide a description of the function:def get_vts_xml(self, vt_id=None, filtered_vts=None):
vts_xml = Element('vts')
if vt_id:
vts_xml.append(self.get_vt_xml(vt_id))
elif filtered_vts:
for vt_id in filtered_vts:
vts_xml.append(self.get_vt_xml(vt_id))
else:
for vt_id in self.vts:
vts_xml.append(self.get_vt_xml(vt_id))
return vts_xml | [
" Gets collection of vulnerability test information in XML format.\n If vt_id is specified, the collection will contain only this vt, if\n found.\n If no vt_id is specified, the collection will contain all vts or those\n passed in filtered_vts.\n\n Arguments:\n vt_id (vt_id, optional): ID of the vt to get.\n filtered_vts (dict, optional): Filtered VTs collection.\n\n Return:\n String of collection of vulnerability test information in\n XML format.\n "
]
|
Please provide a description of the function:def handle_get_scanner_details(self):
desc_xml = Element('description')
desc_xml.text = self.get_scanner_description()
details = [
desc_xml,
self.get_scanner_params_xml()
]
return simple_response_str('get_scanner_details', 200, 'OK', details) | [
" Handles <get_scanner_details> command.\n\n @return: Response string for <get_scanner_details> command.\n "
]
|
Please provide a description of the function:def handle_get_version_command(self):
protocol = Element('protocol')
for name, value in [('name', 'OSP'), ('version', self.get_protocol_version())]:
elem = SubElement(protocol, name)
elem.text = value
daemon = Element('daemon')
for name, value in [('name', self.get_daemon_name()), ('version', self.get_daemon_version())]:
elem = SubElement(daemon, name)
elem.text = value
scanner = Element('scanner')
for name, value in [('name', self.get_scanner_name()), ('version', self.get_scanner_version())]:
elem = SubElement(scanner, name)
elem.text = value
content = [protocol, daemon, scanner]
if self.get_vts_version():
vts = Element('vts')
elem = SubElement(vts, 'version')
elem.text = self.get_vts_version()
content.append(vts)
return simple_response_str('get_version', 200, 'OK', content) | [
" Handles <get_version> command.\n\n @return: Response string for <get_version> command.\n "
]
|
Please provide a description of the function:def handle_command(self, command):
try:
tree = secET.fromstring(command)
except secET.ParseError:
logger.debug("Erroneous client input: %s", command)
raise OSPDError('Invalid data')
if not self.command_exists(tree.tag) and tree.tag != "authenticate":
raise OSPDError('Bogus command name')
if tree.tag == "get_version":
return self.handle_get_version_command()
elif tree.tag == "start_scan":
return self.handle_start_scan_command(tree)
elif tree.tag == "stop_scan":
return self.handle_stop_scan_command(tree)
elif tree.tag == "get_scans":
return self.handle_get_scans_command(tree)
elif tree.tag == "get_vts":
return self.handle_get_vts_command(tree)
elif tree.tag == "delete_scan":
return self.handle_delete_scan_command(tree)
elif tree.tag == "help":
return self.handle_help_command(tree)
elif tree.tag == "get_scanner_details":
return self.handle_get_scanner_details()
else:
assert False, "Unhandled command: {0}".format(tree.tag) | [
" Handles an osp command in a string.\n\n @return: OSP Response to command.\n "
]
|
Please provide a description of the function:def run(self, address, port, unix_path):
assert address or unix_path
if unix_path:
sock = bind_unix_socket(unix_path)
else:
sock = bind_socket(address, port)
if sock is None:
return False
sock.setblocking(False)
inputs = [sock]
outputs = []
try:
while True:
readable, _, _ = select.select(
inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD)
for r_socket in readable:
if unix_path and r_socket is sock:
client_stream, _ = sock.accept()
logger.debug("New connection from %s", unix_path)
self.handle_client_stream(client_stream, True)
else:
client_stream = self.new_client_stream(sock)
if client_stream is None:
continue
self.handle_client_stream(client_stream, False)
close_client_stream(client_stream, unix_path)
self.scheduler()
except KeyboardInterrupt:
logger.info("Received Ctrl-C shutting-down ...")
finally:
sock.shutdown(socket.SHUT_RDWR)
sock.close() | [
" Starts the Daemon, handling commands until interrupted.\n\n @return False if error. Runs indefinitely otherwise.\n "
]
|
Please provide a description of the function:def create_scan(self, scan_id, targets, options, vts):
if self.scan_exists(scan_id):
logger.info("Scan %s exists. Resuming scan.", scan_id)
return self.scan_collection.create_scan(scan_id, targets, options, vts) | [
" Creates a new scan.\n\n @target: Target to scan.\n @options: Miscellaneous scan options.\n\n @return: New scan's ID.\n "
]
|
Please provide a description of the function:def set_scan_option(self, scan_id, name, value):
return self.scan_collection.set_option(scan_id, name, value) | [
" Sets a scan's option to a provided value. "
]
|
Please provide a description of the function:def check_scan_process(self, scan_id):
scan_process = self.scan_processes[scan_id]
progress = self.get_scan_progress(scan_id)
if progress < 100 and not scan_process.is_alive():
self.set_scan_status(scan_id, ScanStatus.STOPPED)
self.add_scan_error(scan_id, name="", host="",
value="Scan process failure.")
logger.info("%s: Scan stopped with errors.", scan_id)
elif progress == 100:
scan_process.join() | [
" Check the scan's process, and terminate the scan if not alive. "
]
|
Please provide a description of the function:def add_scan_log(self, scan_id, host='', name='', value='', port='',
test_id='', qod=''):
self.scan_collection.add_result(scan_id, ResultType.LOG, host, name,
value, port, test_id, 0.0, qod) | [
" Adds a log result to scan_id scan. "
]
|
Please provide a description of the function:def add_scan_error(self, scan_id, host='', name='', value='', port=''):
self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name,
value, port) | [
" Adds an error result to scan_id scan. "
]
|
Please provide a description of the function:def add_scan_host_detail(self, scan_id, host='', name='', value=''):
self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host,
name, value) | [
" Adds a host detail result to scan_id scan. "
]
|
Please provide a description of the function:def add_scan_alarm(self, scan_id, host='', name='', value='', port='',
test_id='', severity='', qod=''):
self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name,
value, port, test_id, severity, qod) | [
" Adds an alarm result to scan_id scan. "
]
|
Please provide a description of the function:def parse_filters(self, vt_filter):
filter_list = vt_filter.split(';')
filters = list()
for single_filter in filter_list:
filter_aux = re.split('(\W)', single_filter, 1)
if len(filter_aux) < 3:
raise OSPDError("Invalid number of argument in the filter", "get_vts")
_element, _oper, _val = filter_aux
if _element not in self.allowed_filter:
raise OSPDError("Invalid filter element", "get_vts")
if _oper not in self.filter_operator:
raise OSPDError("Invalid filter operator", "get_vts")
filters.append(filter_aux)
return filters | [
" Parse a string containing one or more filters\n and return a list of filters\n\n Arguments:\n vt_filter (string): String containing filters separated with\n semicolon.\n Return:\n List with filters. Each filters is a list with 3 elements\n e.g. [arg, operator, value]\n "
]
|
Please provide a description of the function:def format_filter_value(self, element, value):
format_func = self.allowed_filter.get(element)
return format_func(value) | [
" Calls the specific function to format value,\n depending on the given element.\n\n Arguments:\n element (string): The element of the VT to be formatted.\n value (dictionary): The element value.\n\n Returns:\n Returns a formatted value.\n\n "
]
|
Please provide a description of the function:def get_filtered_vts_list(self, vts, vt_filter):
if not vt_filter:
raise RequiredArgument('vt_filter: A valid filter is required.')
filters = self.parse_filters(vt_filter)
if not filters:
return None
_vts_aux = vts.copy()
for _element, _oper, _filter_val in filters:
for vt_id in _vts_aux.copy():
if not _vts_aux[vt_id].get(_element):
_vts_aux.pop(vt_id)
continue
_elem_val = _vts_aux[vt_id].get(_element)
_val = self.format_filter_value(_element, _elem_val)
if self.filter_operator[_oper](_val, _filter_val):
continue
else:
_vts_aux.pop(vt_id)
return _vts_aux | [
" Gets a collection of vulnerability test from the vts dictionary,\n which match the filter.\n\n Arguments:\n vt_filter (string): Filter to apply to the vts collection.\n vts (dictionary): The complete vts collection.\n\n Returns:\n Dictionary with filtered vulnerability tests.\n "
]
|
Please provide a description of the function:def cvss_base_v2_value(cls, cvss_base_vector):
if not cvss_base_vector:
return None
_av, _ac, _au, _c, _i, _a = cls._parse_cvss_base_vector(
cvss_base_vector)
_impact = 10.41 * (1 - (1 - cvss_v2_metrics['C'].get(_c)) *
(1 - cvss_v2_metrics['I'].get(_i)) *
(1 - cvss_v2_metrics['A'].get(_a)))
_exploitability = (20 * cvss_v2_metrics['AV'].get(_av) *
cvss_v2_metrics['AC'].get(_ac) *
cvss_v2_metrics['Au'].get(_au))
f_impact = 0 if _impact == 0 else 1.176
cvss_base = ((0.6 * _impact) + (0.4 * _exploitability) - 1.5) * f_impact
return round(cvss_base, 1) | [
" Calculate the cvss base score from a cvss base vector\n for cvss version 2.\n Arguments:\n cvss_base_vector (str) Cvss base vector v2.\n\n Return the calculated score\n "
]
|
Please provide a description of the function:def cvss_base_v3_value(cls, cvss_base_vector):
if not cvss_base_vector:
return None
_ver, _av, _ac, _pr, _ui, _s, _c, _i, _a = cls._parse_cvss_base_vector(
cvss_base_vector)
scope_changed = cvss_v3_metrics['S'].get(_s)
isc_base = 1 - (
(1 - cvss_v3_metrics['C'].get(_c)) *
(1 - cvss_v3_metrics['I'].get(_i)) *
(1 - cvss_v3_metrics['A'].get(_a))
)
if scope_changed:
_priv_req = cvss_v3_metrics['PR_SC'].get(_pr)
else:
_priv_req = cvss_v3_metrics['PR_SU'].get(_pr)
_exploitability = (
8.22 *
cvss_v3_metrics['AV'].get(_av) *
cvss_v3_metrics['AC'].get(_ac) *
_priv_req *
cvss_v3_metrics['UI'].get(_ui)
)
if scope_changed:
_impact = (7.52 * (isc_base - 0.029) -
3.25 * pow(isc_base - 0.02, 15))
_base_score = min (1.08 * (_impact + _exploitability), 10)
else:
_impact = 6.42 * isc_base
_base_score = min (_impact + _exploitability, 10)
if _impact > 0 :
return cls.roundup(_base_score)
return 0 | [
" Calculate the cvss base score from a cvss base vector\n for cvss version 3.\n Arguments:\n cvss_base_vector (str) Cvss base vector v3.\n\n Return the calculated score, None on fail.\n "
]
|
Please provide a description of the function:def inet_pton(address_family, ip_string):
global __inet_pton
if __inet_pton is None:
if hasattr(socket, 'inet_pton'):
__inet_pton = socket.inet_pton
else:
from ospd import win_socket
__inet_pton = win_socket.inet_pton
return __inet_pton(address_family, ip_string) | [
" A platform independent version of inet_pton "
]
|
Please provide a description of the function:def inet_ntop(address_family, packed_ip):
global __inet_ntop
if __inet_ntop is None:
if hasattr(socket, 'inet_ntop'):
__inet_ntop = socket.inet_ntop
else:
from ospd import win_socket
__inet_ntop = win_socket.inet_ntop
return __inet_ntop(address_family, packed_ip) | [
" A platform independent version of inet_ntop "
]
|
Please provide a description of the function:def ipv4_range_to_list(start_packed, end_packed):
new_list = list()
start = struct.unpack('!L', start_packed)[0]
end = struct.unpack('!L', end_packed)[0]
for value in range(start, end + 1):
new_ip = socket.inet_ntoa(struct.pack('!L', value))
new_list.append(new_ip)
return new_list | [
" Return a list of IPv4 entries from start_packed to end_packed. "
]
|
Please provide a description of the function:def target_to_ipv4_short(target):
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_value = int(splitted[1])
except (socket.error, ValueError):
return None
start_value = int(binascii.hexlify(bytes(start_packed[3])), 16)
if end_value < 0 or end_value > 255 or end_value < start_value:
return None
end_packed = start_packed[0:3] + struct.pack('B', end_value)
return ipv4_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv4 short range list from a target string. "
]
|
Please provide a description of the function:def target_to_ipv4_cidr(target):
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
block = int(splitted[1])
except (socket.error, ValueError):
return None
if block <= 0 or block > 30:
return None
start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block)
start_value = (start_value << (32 - block)) + 1
end_value = (start_value | (0xffffffff >> block)) - 1
start_packed = struct.pack('!I', start_value)
end_packed = struct.pack('!I', end_value)
return ipv4_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv4 CIDR list from a target string. "
]
|
Please provide a description of the function:def target_to_ipv6_cidr(target):
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
block = int(splitted[1])
except (socket.error, ValueError):
return None
if block <= 0 or block > 126:
return None
start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block)
start_value = (start_value << (128 - block)) + 1
end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1
high = start_value >> 64
low = start_value & ((1 << 64) - 1)
start_packed = struct.pack('!QQ', high, low)
high = end_value >> 64
low = end_value & ((1 << 64) - 1)
end_packed = struct.pack('!QQ', high, low)
return ipv6_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv6 CIDR list from a target string. "
]
|
Please provide a description of the function:def target_to_ipv4_long(target):
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_packed = inet_pton(socket.AF_INET, splitted[1])
except socket.error:
return None
if end_packed < start_packed:
return None
return ipv4_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv4 long-range list from a target string. "
]
|
Please provide a description of the function:def ipv6_range_to_list(start_packed, end_packed):
new_list = list()
start = int(binascii.hexlify(start_packed), 16)
end = int(binascii.hexlify(end_packed), 16)
for value in range(start, end + 1):
high = value >> 64
low = value & ((1 << 64) - 1)
new_ip = inet_ntop(socket.AF_INET6,
struct.pack('!2Q', high, low))
new_list.append(new_ip)
return new_list | [
" Return a list of IPv6 entries from start_packed to end_packed. "
]
|
Please provide a description of the function:def target_to_ipv6_short(target):
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
end_value = int(splitted[1], 16)
except (socket.error, ValueError):
return None
start_value = int(binascii.hexlify(start_packed[14:]), 16)
if end_value < 0 or end_value > 0xffff or end_value < start_value:
return None
end_packed = start_packed[:14] + struct.pack('!H', end_value)
return ipv6_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv6 short-range list from a target string. "
]
|
Please provide a description of the function:def target_to_ipv6_long(target):
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
end_packed = inet_pton(socket.AF_INET6, splitted[1])
except socket.error:
return None
if end_packed < start_packed:
return None
return ipv6_range_to_list(start_packed, end_packed) | [
" Attempt to return a IPv6 long-range list from a target string. "
]
|
Please provide a description of the function:def target_to_hostname(target):
if len(target) == 0 or len(target) > 255:
return None
if not re.match(r'^[\w.-]+$', target):
return None
return [target] | [
" Attempt to return a single hostname list from a target string. "
]
|
Please provide a description of the function:def target_to_list(target):
# Is it an IPv4 address ?
new_list = target_to_ipv4(target)
# Is it an IPv6 address ?
if not new_list:
new_list = target_to_ipv6(target)
# Is it an IPv4 CIDR ?
if not new_list:
new_list = target_to_ipv4_cidr(target)
# Is it an IPv6 CIDR ?
if not new_list:
new_list = target_to_ipv6_cidr(target)
# Is it an IPv4 short-range ?
if not new_list:
new_list = target_to_ipv4_short(target)
# Is it an IPv4 long-range ?
if not new_list:
new_list = target_to_ipv4_long(target)
# Is it an IPv6 short-range ?
if not new_list:
new_list = target_to_ipv6_short(target)
# Is it an IPv6 long-range ?
if not new_list:
new_list = target_to_ipv6_long(target)
# Is it a hostname ?
if not new_list:
new_list = target_to_hostname(target)
return new_list | [
" Attempt to return a list of single hosts from a target string. "
]
|
Please provide a description of the function:def target_str_to_list(target_str):
new_list = list()
for target in target_str.split(','):
target = target.strip()
target_list = target_to_list(target)
if target_list:
new_list.extend(target_list)
else:
LOGGER.info("{0}: Invalid target value".format(target))
return None
return list(collections.OrderedDict.fromkeys(new_list)) | [
" Parses a targets string into a list of individual targets. "
]
|
Please provide a description of the function:def port_range_expand(portrange):
if not portrange or '-' not in portrange:
LOGGER.info("Invalid port range format")
return None
port_list = list()
for single_port in range(int(portrange[:portrange.index('-')]),
int(portrange[portrange.index('-') + 1:]) + 1):
port_list.append(single_port)
return port_list | [
"\n Receive a port range and expands it in individual ports.\n\n @input Port range.\n e.g. \"4-8\"\n\n @return List of integers.\n e.g. [4, 5, 6, 7, 8]\n "
]
|
Please provide a description of the function:def port_str_arrange(ports):
b_tcp = ports.find("T")
b_udp = ports.find("U")
if (b_udp != -1 and b_tcp != -1) and b_udp < b_tcp:
return ports[b_tcp:] + ports[b_udp:b_tcp]
return ports | [
" Gives a str in the format (always tcp listed first).\n T:<tcp ports/portrange comma separated>U:<udp ports comma separated>\n "
]
|
Please provide a description of the function:def ports_str_check_failed(port_str):
pattern = r'[^TU:0-9, \-]'
if (
re.search(pattern, port_str)
or port_str.count('T') > 1
or port_str.count('U') > 1
or port_str.count(':') < (port_str.count('T') + port_str.count('U'))
):
return True
return False | [
"\n Check if the port string is well formed.\n Return True if fail, False other case.\n "
]
|
Please provide a description of the function:def ports_as_list(port_str):
if not port_str:
LOGGER.info("Invalid port value")
return [None, None]
if ports_str_check_failed(port_str):
LOGGER.info("{0}: Port list malformed.")
return [None, None]
tcp_list = list()
udp_list = list()
ports = port_str.replace(' ', '')
b_tcp = ports.find("T")
b_udp = ports.find("U")
if ports[b_tcp - 1] == ',':
ports = ports[:b_tcp - 1] + ports[b_tcp:]
if ports[b_udp - 1] == ',':
ports = ports[:b_udp - 1] + ports[b_udp:]
ports = port_str_arrange(ports)
tports = ''
uports = ''
# TCP ports listed first, then UDP ports
if b_udp != -1 and b_tcp != -1:
tports = ports[ports.index('T:') + 2:ports.index('U:')]
uports = ports[ports.index('U:') + 2:]
# Only UDP ports
elif b_tcp == -1 and b_udp != -1:
uports = ports[ports.index('U:') + 2:]
# Only TCP ports
elif b_udp == -1 and b_tcp != -1:
tports = ports[ports.index('T:') + 2:]
else:
tports = ports
if tports:
for port in tports.split(','):
if '-' in port:
tcp_list.extend(port_range_expand(port))
else:
tcp_list.append(int(port))
tcp_list.sort()
if uports:
for port in uports.split(','):
if '-' in port:
udp_list.extend(port_range_expand(port))
else:
udp_list.append(int(port))
udp_list.sort()
return (tcp_list, udp_list) | [
"\n Parses a ports string into two list of individual tcp and udp ports.\n\n @input string containing a port list\n e.g. T:1,2,3,5-8 U:22,80,600-1024\n\n @return two list of sorted integers, for tcp and udp ports respectively.\n "
]
|
Please provide a description of the function:def port_list_compress(port_list):
if not port_list or len(port_list) == 0:
LOGGER.info("Invalid or empty port list.")
return ''
port_list = sorted(set(port_list))
compressed_list = []
for key, group in itertools.groupby(enumerate(port_list),
lambda t: t[1] - t[0]):
group = list(group)
if group[0][1] == group[-1][1]:
compressed_list.append(str(group[0][1]))
else:
compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1]))
return ','.join(compressed_list) | [
" Compress a port list and return a string. "
]
|
Please provide a description of the function:def valid_uuid(value):
try:
uuid.UUID(value, version=4)
return True
except (TypeError, ValueError, AttributeError):
return False | [
" Check if value is a valid UUID. "
]
|
Please provide a description of the function:def create_args_parser(description):
parser = argparse.ArgumentParser(description=description)
def network_port(string):
value = int(string)
if not 0 < value <= 65535:
raise argparse.ArgumentTypeError(
'port must be in ]0,65535] interval')
return value
def cacert_file(cacert):
try:
context = ssl.create_default_context(cafile=cacert)
except AttributeError:
# Python version < 2.7.9
return cacert
except IOError:
raise argparse.ArgumentTypeError('CA Certificate not found')
try:
not_after = context.get_ca_certs()[0]['notAfter']
not_after = ssl.cert_time_to_seconds(not_after)
not_before = context.get_ca_certs()[0]['notBefore']
not_before = ssl.cert_time_to_seconds(not_before)
except (KeyError, IndexError):
raise argparse.ArgumentTypeError('CA Certificate is erroneous')
if not_after < int(time.time()):
raise argparse.ArgumentTypeError('CA Certificate expired')
if not_before > int(time.time()):
raise argparse.ArgumentTypeError('CA Certificate not active yet')
return cacert
def log_level(string):
value = getattr(logging, string.upper(), None)
if not isinstance(value, int):
raise argparse.ArgumentTypeError(
'log level must be one of {debug,info,warning,error,critical}')
return value
def filename(string):
if not os.path.isfile(string):
raise argparse.ArgumentTypeError(
'%s is not a valid file path' % string)
return string
parser.add_argument('-p', '--port', default=PORT, type=network_port,
help='TCP Port to listen on. Default: {0}'.format(PORT))
parser.add_argument('-b', '--bind-address', default=ADDRESS,
help='Address to listen on. Default: {0}'
.format(ADDRESS))
parser.add_argument('-u', '--unix-socket',
help='Unix file socket to listen on.')
parser.add_argument('-k', '--key-file', type=filename,
help='Server key file. Default: {0}'.format(KEY_FILE))
parser.add_argument('-c', '--cert-file', type=filename,
help='Server cert file. Default: {0}'.format(CERT_FILE))
parser.add_argument('--ca-file', type=cacert_file,
help='CA cert file. Default: {0}'.format(CA_FILE))
parser.add_argument('-L', '--log-level', default='warning', type=log_level,
help='Wished level of logging. Default: WARNING')
parser.add_argument('--foreground', action='store_true',
help='Run in foreground and logs all messages to console.')
parser.add_argument('-l', '--log-file', type=filename,
help='Path to the logging file.')
parser.add_argument('--version', action='store_true',
help='Print version then exit.')
return parser | [
" Create a command-line arguments parser for OSPD. ",
" Check if provided string is a valid network port. ",
" Check if provided file is a valid CA Certificate ",
" Check if provided string is a valid log level. ",
" Check if provided string is a valid file path. "
]
|
Please provide a description of the function:def go_to_background():
try:
if os.fork():
sys.exit()
except OSError as errmsg:
LOGGER.error('Fork failed: {0}'.format(errmsg))
sys.exit('Fork failed') | [
" Daemonize the running process. "
]
|
Please provide a description of the function:def get_common_args(parser, args=None):
options = parser.parse_args(args)
# TCP Port to listen on.
port = options.port
# Network address to bind listener to
address = options.bind_address
# Unix file socket to listen on
unix_socket = options.unix_socket
# Debug level.
log_level = options.log_level
# Server key path.
keyfile = options.key_file or KEY_FILE
# Server cert path.
certfile = options.cert_file or CERT_FILE
# CA cert path.
cafile = options.ca_file or CA_FILE
common_args = dict()
common_args['port'] = port
common_args['address'] = address
common_args['unix_socket'] = unix_socket
common_args['keyfile'] = keyfile
common_args['certfile'] = certfile
common_args['cafile'] = cafile
common_args['log_level'] = log_level
common_args['foreground'] = options.foreground
common_args['log_file'] = options.log_file
common_args['version'] = options.version
return common_args | [
" Return list of OSPD common command-line arguments from parser, after\n validating provided values or setting default ones.\n\n "
]
|
Please provide a description of the function:def print_version(wrapper):
scanner_name = wrapper.get_scanner_name()
server_version = wrapper.get_server_version()
print("OSP Server for {0} version {1}".format(scanner_name, server_version))
protocol_version = wrapper.get_protocol_version()
print("OSP Version: {0}".format(protocol_version))
daemon_name = wrapper.get_daemon_name()
daemon_version = wrapper.get_daemon_version()
print("Using: {0} {1}".format(daemon_name, daemon_version))
print("Copyright (C) 2014, 2015 Greenbone Networks GmbH\n"
"License GPLv2+: GNU GPL version 2 or later\n"
"This is free software: you are free to change"
" and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.") | [
" Prints the server version and license information."
]
|
Please provide a description of the function:def main(name, klass):
# Common args parser.
parser = create_args_parser(name)
# Common args
cargs = get_common_args(parser)
logging.getLogger().setLevel(cargs['log_level'])
wrapper = klass(certfile=cargs['certfile'], keyfile=cargs['keyfile'],
cafile=cargs['cafile'])
if cargs['version']:
print_version(wrapper)
sys.exit()
if cargs['foreground']:
console = logging.StreamHandler()
console.setFormatter(
logging.Formatter(
'%(asctime)s %(name)s: %(levelname)s: %(message)s'))
logging.getLogger().addHandler(console)
elif cargs['log_file']:
logfile = logging.handlers.WatchedFileHandler(cargs['log_file'])
logfile.setFormatter(
logging.Formatter(
'%(asctime)s %(name)s: %(levelname)s: %(message)s'))
logging.getLogger().addHandler(logfile)
go_to_background()
else:
syslog = logging.handlers.SysLogHandler('/dev/log')
syslog.setFormatter(
logging.Formatter('%(name)s: %(levelname)s: %(message)s'))
logging.getLogger().addHandler(syslog)
# Duplicate syslog's file descriptor to stout/stderr.
syslog_fd = syslog.socket.fileno()
os.dup2(syslog_fd, 1)
os.dup2(syslog_fd, 2)
go_to_background()
if not wrapper.check():
return 1
return wrapper.run(cargs['address'], cargs['port'], cargs['unix_socket']) | [
" OSPD Main function. "
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.