Skip to content

Commit

Permalink
[skip actions] [pydriller] 2023-12-20T08:45:31+02:00
Browse files Browse the repository at this point in the history
  • Loading branch information
babenek committed Feb 7, 2024
1 parent 3d7de32 commit f2dfebe
Show file tree
Hide file tree
Showing 12 changed files with 258 additions and 70 deletions.
3 changes: 3 additions & 0 deletions .mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,8 @@ ignore_missing_imports = True
[mypy-docx.*]
ignore_missing_imports = True

[mypy-pydriller.*]
ignore_missing_imports = True

[mypy-base62.*]
ignore_missing_imports = True
103 changes: 101 additions & 2 deletions credsweeper/__main__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import base64
import binascii
import hashlib
import io
import logging
import os
import sys
import time
from argparse import ArgumentParser, ArgumentTypeError, Namespace
from typing import Any, Union, Optional, Dict
from typing import Any, Union, Optional, Dict, List, Tuple

from pydriller import Repository

from credsweeper import __version__
from credsweeper.app import APP_PATH, CredSweeper
Expand Down Expand Up @@ -116,6 +121,17 @@ def get_arguments() -> Namespace:
const="log.yaml",
dest="export_log_config",
metavar="PATH")
group.add_argument("--git", nargs="+", help="git repo to scan", dest="git", metavar="PATH")
parser.add_argument("--commits",
help="scan git repo for N commits only",
type=positive_int,
dest="commits",
default=0,
metavar="POSITIVE_INT")
parser.add_argument("--branch",
help="scan git repo for single branch, otherwise - all branches were scanned (slow)",
dest="branch",
type=str)
parser.add_argument("--rules",
nargs="?",
help="path of rule config file (default: credsweeper/rules/config.yaml). "
Expand Down Expand Up @@ -300,9 +316,85 @@ def scan(args: Namespace, content_provider: FilesProvider, json_filename: Option
return credsweeper.run(content_provider=content_provider)
except Exception as exc:
logger.critical(exc, exc_info=True)
logger.exception(exc)
return -1


def scan_git(args: Namespace) -> Tuple[int, int, int]:
"""Scan repository for branches and commits
Returns:
total credentials found
total scanned branches
total scanned commits
"""
total_credentials = 0
total_branches = 0
total_commits = 0
try:
sha1git = hashlib.sha1(str(args.git).encode()).digest()
repo_hash = base64.b32encode(sha1git).decode("ascii")
journal_filename = f"{repo_hash}.json"
logger.info(f"{args.git} sha1 in base32 {repo_hash}")
repo_journal = Util.json_load(journal_filename)
if not isinstance(repo_journal, dict):
with open(journal_filename, "w") as f:
f.write("{}")
repo_journal = dict()
credsweeper = CredSweeper(rule_path=args.rule_path,
config_path=args.config_path,
api_validation=args.api_validation,
sort_output=args.sort_output,
use_filters=args.no_filters,
pool_count=args.jobs,
ml_batch_size=args.ml_batch_size,
ml_threshold=args.ml_threshold,
azure=args.azure,
cuda=args.cuda,
find_by_ext=args.find_by_ext,
depth=args.depth,
doc=args.doc,
severity=args.severity,
size_limit=args.size_limit,
log_level=args.log)
repository = Repository(args.git, only_in_branch=args.branch)
for commit in repository.traverse_commits():
if commit.hash in repo_journal:
logger.debug(f"Skip already scanned commit: {commit.hash}")
continue
logger.info(f"Scan commit: {commit.hash}")
paths: List[Tuple[str, io.BytesIO]] = []
for file in commit.modified_files:
logger.info(f"FILE: {file.old_path} -> {file.new_path}")
try:
if file.new_path is not None:
_io = io.BytesIO(file.content)
paths.append((file.filename, _io))
except ValueError as exc:
logger.error("Possible missed submodule:%s", str(exc))
provider = TextProvider(paths)
if args.json_filename:
ext = Util.get_extension(args.json_filename, False)
credsweeper.json_filename = f"{args.json_filename[:-len(ext)]}.{commit.hash}{ext}"
if args.xlsx_filename:
ext = Util.get_extension(args.xlsx_filename, False)
credsweeper.xlsx_filename = f"{args.xlsx_filename[:-len(ext)]}.{commit.hash}{ext}"

commit_cred_number = credsweeper.run(provider)
if credsweeper.is_ml_validator_inited:
# reset not-pickled object for multiprocess
credsweeper.ml_validator = None
credsweeper.credential_manager.candidates.clear()
total_credentials += commit_cred_number
total_commits += 1
repo_journal[commit.hash] = commit_cred_number
Util.json_dump(repo_journal, journal_filename)
total_branches += 1
except Exception as exc:
logger.critical(exc, exc_info=True)
return -1, total_branches, total_commits
return total_credentials, total_branches, total_commits


def main() -> int:
"""Main function"""
result = EXIT_FAILURE
Expand All @@ -311,7 +403,7 @@ def main() -> int:
if args.banner:
print(f"CredSweeper {__version__} crc32:{check_integrity():08x}")
Logger.init_logging(args.log, args.log_config_path)
logger.info(f"Init CredSweeper object with arguments: {args}")
logger.info(f"Init CredSweeper object with arguments: {args} CWD: {os.getcwd()}")
summary: Dict[str, int] = {}
if args.path:
logger.info(f"Run analyzer on path: {args.path}")
Expand All @@ -334,6 +426,13 @@ def main() -> int:
summary["Deleted File Credentials"] = del_credentials_number
if 0 <= add_credentials_number and 0 <= del_credentials_number:
result = EXIT_SUCCESS
elif args.git:
logger.info(f"Run analyzer on GIT: {args.git}")
credentials_number, branches_number, commits_number = scan_git(args)
summary[
f"Detected Credentials in {branches_number} branches and {commits_number} commits "] = credentials_number
if 0 <= credentials_number:
result = EXIT_SUCCESS
elif args.export_config:
logging.info(f"Exporting default config to file: {args.export_config}")
config_dict = Util.json_load(APP_PATH / "secret" / "config.json")
Expand Down
15 changes: 14 additions & 1 deletion credsweeper/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,18 @@ def _use_ml_validation(self) -> bool:

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

@property
def is_ml_validator_inited(self) -> bool:
"""method to check whether ml_validator was inited without creation"""
return bool(self.__ml_validator)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

@property
def ml_validator(self) -> MlValidator:
"""ml_validator getter"""
from credsweeper.ml_model import MlValidator
if not self.__ml_validator:
if not self.is_ml_validator_inited:
self.__ml_validator: MlValidator = MlValidator(threshold=self.ml_threshold)
assert self.__ml_validator, "self.__ml_validator was not initialized"
return self.__ml_validator
Expand Down Expand Up @@ -372,6 +379,12 @@ def export_results(self) -> None:

credentials = self.credential_manager.get_credentials()

if credentials:
logger.info(f"Exporting {len(credentials)} credentials")
else:
logger.info("No credentials were found")
return

if self.sort_output:
credentials.sort(key=lambda x: ( #
x.line_data_list[0].path, #
Expand Down
1 change: 1 addition & 0 deletions credsweeper/common/keyword_checklist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,7 @@ since
single
sites
sizing
skip
sleep
slice
slick
Expand Down
8 changes: 4 additions & 4 deletions credsweeper/file_handler/files_provider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import io
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Union, Tuple
from typing import List, Union, Tuple, Sequence

from credsweeper.config import Config
from credsweeper.file_handler.diff_content_provider import DiffContentProvider
Expand All @@ -11,7 +11,7 @@
class FilesProvider(ABC):
"""Base class for all files provider objects."""

def __init__(self, paths: List[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]) -> None:
def __init__(self, paths: Sequence[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]) -> None:
"""Initialize Files Provider object for 'paths'.
Args:
Expand All @@ -21,12 +21,12 @@ def __init__(self, paths: List[Union[str, Path, io.BytesIO, Tuple[Union[str, Pat
self.paths = paths

@property
def paths(self) -> List[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]:
def paths(self) -> Sequence[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]:
"""paths getter"""
return self.__paths

@paths.setter
def paths(self, paths: List[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]) -> None:
def paths(self, paths: Sequence[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]]) -> None:
"""paths setter"""
self.__paths = paths

Expand Down
8 changes: 2 additions & 6 deletions credsweeper/file_handler/patch_provider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import io
import logging
from pathlib import Path
from typing import List, Union, Tuple
from typing import List, Union, Tuple, Sequence

from credsweeper import TextContentProvider
from credsweeper.common.constants import DiffRowType
Expand All @@ -22,20 +22,16 @@ class PatchProvider(FilesProvider):
Parameters:
paths: file paths list to scan. All files should be in `.patch` format
change_type: string, type of analyses changes in patch (added or deleted)
skip_ignored: boolean variable, Checking the directory to the list
of ignored directories from the gitignore file
"""

def __init__(self, paths: List[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]],
def __init__(self, paths: Sequence[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]],
change_type: DiffRowType) -> None:
"""Initialize Files Patch Provider for patch files from 'paths'.
Args:
paths: file paths list to scan. All files should be in `.patch` format
change_type: string, type of analyses changes in patch (added or deleted)
skip_ignored: boolean variable, Checking the directory to the list
of ignored directories from the gitignore file
"""
super().__init__(paths)
Expand Down
4 changes: 2 additions & 2 deletions credsweeper/file_handler/text_provider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import io
import logging
from pathlib import Path
from typing import List, Optional, Union, Tuple
from typing import List, Optional, Union, Tuple, Sequence

from credsweeper import DiffContentProvider
from credsweeper.config import Config
Expand All @@ -24,7 +24,7 @@ class TextProvider(FilesProvider):
"""

def __init__(self,
paths: List[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]],
paths: Sequence[Union[str, Path, io.BytesIO, Tuple[Union[str, Path], io.BytesIO]]],
skip_ignored: Optional[bool] = None) -> None:
"""Initialize Files Text Provider for files from 'paths'.
Expand Down
7 changes: 6 additions & 1 deletion docs/source/guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Get all argument list:
.. code-block:: text
usage: python -m credsweeper [-h] (--path PATH [PATH ...] | --diff_path PATH [PATH ...] | --export_config [PATH] | --export_log_config [PATH]) [--rules [PATH]] [--severity SEVERITY] [--config [PATH]]
usage: python -m credsweeper [-h] (--path PATH [PATH ...] | --diff_path PATH [PATH ...] | --export_config [PATH] | --export_log_config [PATH] | --git PATH [PATH ...]) [--commits POSITIVE_INT] [--branch BRANCH] [--rules [PATH]] [--severity SEVERITY] [--config [PATH]]
[--log_config [PATH]] [--denylist PATH] [--find-by-ext] [--depth POSITIVE_INT] [--no-filters] [--doc] [--ml_threshold FLOAT_OR_STR] [--ml_batch_size POSITIVE_INT]
[--azure | --cuda] [--api_validation] [--jobs POSITIVE_INT] [--skip_ignored] [--save-json [PATH]] [--save-xlsx [PATH]] [--sort] [--log LOG_LEVEL] [--size_limit SIZE_LIMIT]
[--banner] [--version]
Expand All @@ -27,6 +27,11 @@ Get all argument list:
exporting default config to file (default: config.json)
--export_log_config [PATH]
exporting default logger config to file (default: log.yaml)
--git PATH [PATH ...]
git repo to scan
--commits POSITIVE_INT
scan git repo for N commits only
--branch BRANCH scan git repo for single branch, otherwise - all branches were scanned (slow)
--rules [PATH] path of rule config file (default: credsweeper/rules/config.yaml). severity:['critical', 'high', 'medium', 'low', 'info'] type:['keyword', 'pattern', 'pem_key', 'multi']
--severity SEVERITY set minimum level for rules to apply ['critical', 'high', 'medium', 'low', 'info'](default: 'Severity.INFO', case insensitive)
--config [PATH] use custom config (default: built-in)
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pdfminer.six==20231228
password-strength==0.0.3.post2
python-dateutil==2.8.2
pyjks==20.0.0
PyDriller==2.6
pybase62==1.0.0
base58==2.1.1

Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"onnxruntime", #
"python-dateutil", #
"pyjks", #
"PyDriller", #
"pybase62", #
"base58", #
]
Expand Down
Loading

0 comments on commit f2dfebe

Please sign in to comment.