Check security features of an ELF file.
1554
def checksec_app(_parser, _, args):  # pragma: no cover
    

    import sys
    import argparse
    import csv
    import os.path

    def checksec(elf, path, fortifiable_funcs):
        relro = 0
        nx = False
        pie = 0
        rpath = False
        runpath = False

        for header in elf.program_headers:
            if header.type == ELF.ProgramHeader.Type.gnu_relro:
                relro = 1
            elif header.type == ELF.ProgramHeader.Type.gnu_stack:
                if not header.flags & ELF.ProgramHeader.Flags.x:
                    nx = True

        if elf.type == ELF.Type.shared:
            pie = 1

        for entry in elf.dynamic_section_entries:
            if entry.type == ELF.DynamicSectionEntry.Type.bind_now and relro == 1:
                relro = 2
            elif entry.type == ELF.DynamicSectionEntry.Type.flags and \
                    entry.value & ELF.DynamicSectionEntry.Flags.bind_now:
                relro = 2
            elif entry.type == ELF.DynamicSectionEntry.Type.flags_1 and \
                    entry.value & ELF.DynamicSectionEntry.Flags_1.now:
                relro = 2
            elif entry.type == ELF.DynamicSectionEntry.Type.debug and pie == 1:
                pie = 2
            elif entry.type == ELF.DynamicSectionEntry.Type.rpath:
                rpath = True
            elif entry.type == ELF.DynamicSectionEntry.Type.runpath:
                runpath = True

        rtl_symbol_names = set(
            symbol.name
            for symbol in elf.symbols
            if symbol.name and symbol.shndx == ELF.Symbol.SpecialSection.undef
        )

        fortified = fortifiable_funcs & rtl_symbol_names
        unfortified = fortifiable_funcs & set('__%s_chk' % symbol_name for symbol_name in rtl_symbol_names)

        canary = '__stack_chk_fail' in rtl_symbol_names

        return {
            'path': path,
            'relro': relro,
            'nx': nx,
            'pie': pie,
            'rpath': rpath,
            'runpath': runpath,
            'canary': canary,
            'fortified': len(fortified),
            'unfortified': len(unfortified),
            'fortifiable': len(fortified | unfortified),
        }

    def check_paths(paths, fortifiable_funcs):
        for path in paths:
            if os.path.isdir(path):
                for data in check_paths(
                        (os.path.join(path, fn) for fn in os.listdir(path) if fn not in ('.', '..')),
                        fortifiable_funcs,
                ):
                    yield data
            else:
                try:
                    elf = ELF(path)
                except:
                    continue

                yield checksec(elf, path, fortifiable_funcs)

    parser = argparse.ArgumentParser(
        prog=_parser.prog,
        description=_parser.description,
    )
    parser.add_argument('path', nargs='+', help='ELF file to check security features of')
    parser.add_argument(
        '-f', '--format',
        dest='format',
        choices=['text', 'csv'],
        default='text',
        help='set output format'
    )
    parser.add_argument(
        '-l', '--libc',
        dest='libc',
        help='path to the applicable libc.so'
    )
    args = parser.parse_args(args)

    if args.libc:
        libc = ELF(args.libc)
        fortifiable_funcs = set([
            symbol.name
            for symbol in libc.symbols
            if symbol.name.startswith('__') and symbol.name.endswith('_chk')
        ])
    else:
        fortifiable_funcs = set('''__wctomb_chk __wcsncat_chk __mbstowcs_chk __strncpy_chk __syslog_chk __mempcpy_chk
                                   __fprintf_chk __recvfrom_chk __readlinkat_chk __wcsncpy_chk __fread_chk
                                   __getlogin_r_chk __vfwprintf_chk __recv_chk __strncat_chk __printf_chk __confstr_chk
                                   __pread_chk __ppoll_chk __ptsname_r_chk __wcscat_chk __snprintf_chk __vwprintf_chk
                                   __memset_chk __memmove_chk __gets_chk __fgetws_unlocked_chk __asprintf_chk __poll_chk
                                   __fdelt_chk __fgets_unlocked_chk __strcat_chk __vsyslog_chk __stpcpy_chk
                                   __vdprintf_chk __strcpy_chk __obstack_printf_chk __getwd_chk __pread64_chk
                                   __wcpcpy_chk __fread_unlocked_chk __dprintf_chk __fgets_chk __wcpncpy_chk
                                   __obstack_vprintf_chk __wprintf_chk __getgroups_chk __wcscpy_chk __vfprintf_chk
                                   __fgetws_chk __vswprintf_chk __ttyname_r_chk __mbsrtowcs_chk
                                   __wmempcpy_chk __wcsrtombs_chk __fwprintf_chk __read_chk __getcwd_chk __vsnprintf_chk
                                   __memcpy_chk __wmemmove_chk __vasprintf_chk __sprintf_chk __vprintf_chk
                                   __mbsnrtowcs_chk __wcrtomb_chk __realpath_chk __vsprintf_chk __wcsnrtombs_chk
                                   __gethostname_chk __swprintf_chk __readlink_chk __wmemset_chk __getdomainname_chk
                                   __wmemcpy_chk __longjmp_chk __stpncpy_chk __wcstombs_chk'''.split())

    if args.format == 'text':
        print('RELRO    CANARY  NX   PIE  RPATH  RUNPATH  FORTIFIED  PATH')
        for data in check_paths(args.path, fortifiable_funcs):
            print('{:7}  {:6}  {:3}  {:3}  {:5}  {:7}  {:>9}  {}'.format(
                ('No', 'Partial', 'Full')[data['relro']],
                'Yes' if data['canary'] else 'No',
                'Yes' if data['nx'] else 'No',
                ('No', 'DSO', 'Yes')[data['pie']],
                'Yes' if data['rpath'] else 'No',
                'Yes' if data['runpath'] else 'No',
                '{}/{}/{}'.format(data['fortified'], data['unfortified'], data['fortifiable']),
                data['path']
            ))
    else:
        writer = csv.writer(sys.stdout)
        writer.writerow(['path', 'relro', 'canary', 'nx', 'pie', 'rpath', 'runpath', 'fortified', 'unfortified',
                         'fortifiable'])
        for data in check_paths(args.path, fortifiable_funcs):
            writer.writerow([
                data['path'],
                ('no', 'partial', 'full')[data['relro']],
                'yes' if data['canary'] else 'no',
                'yes' if data['nx'] else 'no',
                ('no', 'dso', 'yes')[data['pie']],
                'yes' if data['rpath'] else 'no',
                'yes' if data['runpath'] else 'no',
                data['fortified'],
                data['unfortified'],
                data['fortifiable'],
            ])
1044659
def check_deps(deps):
        """"""
        if not isinstance(deps, list):
            deps = [deps]
        checks = list(Environment.has_apps(deps))
        if not all(checks):
            for name, available in list(dict(zip(deps, checks)).items()):
                if not available:
                    error_msg = "The required application/dependency '{0}'" \
                                " isn't available.".format(name)
                    raise SystemError(error_msg)
1053376
def _check(self):
        """"""
        final = self._md_context.digest()
        exp = self._inf._md_expect
        if exp is None:
            return
        if final is None:
            return
        if self._returncode:
            check_returncode(self, '')
        if self._remain != 0:
            raise BadRarFile("Failed the read enough data")
        if final != exp:
            raise BadRarFile("Corrupt file - CRC check failed: %s - exp=%r got=%r" % (
                self._inf.filename, exp, final))
1092329
def _check_file(self):
        
        if not os.path.exists(self.file_path):
            return False
        self._migrate()
        config = configparser.RawConfigParser()
        config.read(self.file_path)
        try:
            config.get(
                escape_for_ini('keyring-setting'),
                escape_for_ini('password reference'),
            )
        except (configparser.NoSectionError, configparser.NoOptionError):
            return False
        try:
            self._check_scheme(config)
        except AttributeError:
            # accept a missing scheme
            return True
        return self._check_version(config)
926808
def check_version(ctx, param, value):
    """"""
    if ctx.resilient_parsing:
        return

    if not value and ctx.invoked_subcommand != 'run':
        ctx.call_on_close(_check_version)
1081724
def check_ssl():
    """"""
    try:
        import ssl
    except:
        log.warning('Error importing SSL module', stack_info=True)
        print(SSL_ERROR_MESSAGE)
        sys.exit(1)
    else:
        log.info('SSL module is available')
        return ssl
364778
protected function checkEnvironment()
    {
        if (OS::is(OS::WIN)) {
            $this->error('Swoole extension doesn\'t support Windows OS.');

            exit(1);
        }

        if (! extension_loaded('swoole')) {
            $this->error('Can\'t detect Swoole extension installed.');

            exit(1);
        }

        if (! version_compare(swoole_version(), '4.3.1', 'ge')) {
            $this->error('Your Swoole version must be higher than `4.3.1`.');

            exit(1);
        }
    }
285652
def check(path_dir, requirements_name='requirements.txt'):
    ''''''
    requirements = _load_requirements(requirements_name, path_dir)
    imported_modules = _iter_modules(path_dir)
    installed_packages = _list_installed_packages()

    imported_modules.update(_excluded_imports())

    diff = {lib for lib in installed_packages if lib not in imported_modules}
    with_dependencies, _ = _list_dependencies(diff)
    unused_dependencies = sorted([d for d in diff if d in requirements])

    for unused_dependency in unused_dependencies:
        if with_dependencies.get(unused_dependency):
            print('    - {}'.format(unused_dependency))
            for dependency in with_dependencies.get(unused_dependency):
                print('\t - {}'.format(dependency))
        else:
            print('    - {}'.format(unused_dependency))
369605
def check(self, feature):
        """"""
        input = feature.input
        is_str = isa(str)
        is_nested_str = all_fn(
            iterable, lambda x: all(is_str, x))
        assert is_str(input) or is_nested_str(input)
690346
def check_ast(self):
        """"""
        try:
            tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
        except (ValueError, SyntaxError, TypeError):
            return self.report_invalid_syntax()
        for name, cls, __ in self._ast_checks:
            checker = cls(tree, self.filename)
            for lineno, offset, text, check in checker.run():
                if not self.lines or not noqa(self.lines[lineno - 1]):
                    self.report_error(lineno, offset, text, check)
360556
def verify():
    """"""
    verbose = True
    log(
        "Verifying current directory as a Dallinger experiment...",
        delay=0,
        verbose=verbose,
    )
    ok = verify_package(verbose=verbose)
    if ok:
        log("✓ Everything looks good!", delay=0, verbose=verbose)
    else:
        log("☹ Some problems were found.", delay=0, verbose=verbose)
272837
def ls(system, user, local, include_missing):
    """"""

    # default action is to list *all* auto-detected files
    if not (system or user or local):
        system = user = local = True

    for path in get_configfile_paths(system=system, user=user, local=local,
                                     only_existing=not include_missing):
        click.echo(path)
244533
def check_simple(self, checks, radl):
        """"""

        for f in self.features:
            if not isinstance(f, Feature) or f.prop not in checks:
                continue
            f._check(checks[f.prop], radl)
717612
def is_executable(path):
  """"""
  return os.path.isfile(path) and os.access(path, os.X_OK)
1134216
function checkOlderIE() {
  const ua = navigator.userAgent;
  const isIE = ua.indexOf('MSIE') !== -1 || ua.indexOf('Trident') !== -1;
  if (!isIE) {
    return false;
  }
  const version = ua.match(/(MSIE\s|Trident.*rv:)([\w.]+)/)[2];
  const versionNumber = parseFloat(version);
  if (versionNumber < 10) {
    return true;
  }
  return false;
}
710166
def architecture(file)
      return :invalid unless File.exist?(file)

      f = File.open(file)
      str = ELFTools::ELFFile.new(f).machine
      {
        'Advanced Micro Devices X86-64' => :amd64,
        'Intel 80386' => :i386,
        'ARM' => :arm,
        'AArch64' => :aarch64,
        'MIPS R3000' => :mips
      }[str] || :unknown
    rescue ELFTools::ELFError # not a valid ELF
      :invalid
    ensure
      f&.close
    end
78520
private boolean checkOSSCredentials(UnderFileSystemConfiguration conf) {
    return conf.isSet(PropertyKey.OSS_ACCESS_KEY)
        && conf.isSet(PropertyKey.OSS_SECRET_KEY)
        && conf.isSet(PropertyKey.OSS_ENDPOINT_KEY);
  }