mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
feat: Add support for active scanning in paranoid mode (#31)
* feat: Add support for active scanning in paranoid mode * docs: Fix README
This commit is contained in:
@@ -61,6 +61,7 @@ pnpm add <package-name>
|
|||||||
- [Build from Source](#build-from-source)
|
- [Build from Source](#build-from-source)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
- [Silent Mode](#silent-mode)
|
- [Silent Mode](#silent-mode)
|
||||||
|
- [Dry Run](#dry-run)
|
||||||
- [Verbose Mode](#verbose-mode)
|
- [Verbose Mode](#verbose-mode)
|
||||||
- [Debugging](#debugging)
|
- [Debugging](#debugging)
|
||||||
- [🤝 Contributing](#-contributing)
|
- [🤝 Contributing](#-contributing)
|
||||||
@@ -145,6 +146,15 @@ Use the `--silent` flag to run PMG in silent mode:
|
|||||||
pmg --silent npm install <package-name>
|
pmg --silent npm install <package-name>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Dry Run
|
||||||
|
|
||||||
|
Use the `--dry-run` flag to skip actual package installation. When enabled `pmg` will not execute
|
||||||
|
package manager commands. Useful for checking packages and their transitive dependencies for malware.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pmg --dry-run npm install <package-name>
|
||||||
|
```
|
||||||
|
|
||||||
### Verbose Mode
|
### Verbose Mode
|
||||||
|
|
||||||
Use the `--verbose` flag to run PMG in verbose mode:
|
Use the `--verbose` flag to run PMG in verbose mode:
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package analyzer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"buf.build/gen/go/safedep/api/grpc/go/safedep/services/malysis/v1/malysisv1grpc"
|
||||||
|
malysisv1pb "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/malysis/v1"
|
||||||
|
packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1"
|
||||||
|
malysisv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/malysis/v1"
|
||||||
|
drygrpc "github.com/safedep/dry/adapters/grpc"
|
||||||
|
"github.com/safedep/dry/log"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MalysisActiveScanAnalyzerConfig struct {
|
||||||
|
Timeout time.Duration
|
||||||
|
TenantId string
|
||||||
|
ApiKey string
|
||||||
|
}
|
||||||
|
|
||||||
|
func DefaultMalysisActiveScanAnalyzerConfig() MalysisActiveScanAnalyzerConfig {
|
||||||
|
return MalysisActiveScanAnalyzerConfig{
|
||||||
|
Timeout: 5 * time.Minute,
|
||||||
|
TenantId: os.Getenv("SAFEDEP_TENANT_ID"),
|
||||||
|
ApiKey: os.Getenv("SAFEDEP_API_KEY"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type malysisActiveScanAnalyzer struct {
|
||||||
|
config MalysisActiveScanAnalyzerConfig
|
||||||
|
client malysisv1grpc.MalwareAnalysisServiceClient
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Analyzer = &malysisActiveScanAnalyzer{}
|
||||||
|
|
||||||
|
func NewMalysisActiveScanAnalyzer(config MalysisActiveScanAnalyzerConfig) (*malysisActiveScanAnalyzer, error) {
|
||||||
|
if config.TenantId == "" || config.ApiKey == "" {
|
||||||
|
return nil, fmt.Errorf("active scanning requires SafeDep Cloud authentication credentials")
|
||||||
|
}
|
||||||
|
|
||||||
|
headers := http.Header{}
|
||||||
|
headers.Set("x-tenant-id", config.TenantId)
|
||||||
|
|
||||||
|
client, err := drygrpc.GrpcClient("pmg-malysis-active-scan",
|
||||||
|
"api.safedep.io", "443", config.ApiKey, headers, []grpc.DialOption{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create gRPC client: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &malysisActiveScanAnalyzer{
|
||||||
|
config: config,
|
||||||
|
client: malysisv1grpc.NewMalwareAnalysisServiceClient(client),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *malysisActiveScanAnalyzer) Name() string {
|
||||||
|
return "malysis-active-scan"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *malysisActiveScanAnalyzer) Analyze(ctx context.Context,
|
||||||
|
packageVersion *packagev1.PackageVersion) (*PackageVersionAnalysisResult, error) {
|
||||||
|
|
||||||
|
log.Debugf("Running active analysis on package %s@%s", packageVersion.Package.Name, packageVersion.Version)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, a.config.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
scanResponse, err := a.client.AnalyzePackage(ctx, &malysisv1.AnalyzePackageRequest{
|
||||||
|
Target: &malysisv1pb.PackageAnalysisTarget{
|
||||||
|
PackageVersion: packageVersion,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to submit package for active scanning: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var res *malysisv1.GetAnalysisReportResponse
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Debugf("Active analysis on package %s@%s timed out", packageVersion.Package.Name, packageVersion.Version)
|
||||||
|
return nil, fmt.Errorf("active scanning timed out")
|
||||||
|
case <-time.After(1 * time.Second):
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err = a.client.GetAnalysisReport(ctx, &malysisv1.GetAnalysisReportRequest{
|
||||||
|
AnalysisId: scanResponse.AnalysisId,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get analysis report: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.Status == malysisv1.AnalysisStatus_ANALYSIS_STATUS_COMPLETED {
|
||||||
|
log.Debugf("Active analysis on package %s@%s completed", packageVersion.Package.Name, packageVersion.Version)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pvr := &PackageVersionAnalysisResult{
|
||||||
|
PackageVersion: packageVersion,
|
||||||
|
AnalysisID: scanResponse.AnalysisId,
|
||||||
|
ReferenceURL: malysisReportUrl(scanResponse.AnalysisId),
|
||||||
|
Action: ActionAllow,
|
||||||
|
Summary: res.GetReport().GetInference().GetSummary(),
|
||||||
|
Data: res.GetReport(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.GetReport().GetInference().GetIsMalware() {
|
||||||
|
pvr.Action = ActionConfirm
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.GetVerificationRecord().GetIsMalware() {
|
||||||
|
pvr.Action = ActionBlock
|
||||||
|
}
|
||||||
|
|
||||||
|
return pvr, nil
|
||||||
|
}
|
||||||
+20
-5
@@ -22,9 +22,22 @@ func executeCommonFlow(ctx context.Context, config config.Config, pm packagemana
|
|||||||
return fmt.Errorf("failed to create npm dependency resolver: %w", err)
|
return fmt.Errorf("failed to create npm dependency resolver: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
malysisQueryAnalyzer, err := analyzer.NewMalysisQueryAnalyzer(analyzer.MalysisQueryAnalyzerConfig{})
|
var analyzers []analyzer.PackageVersionAnalyzer
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create malysis query analyzer: %w", err)
|
if config.Paranoid {
|
||||||
|
malysisActiveScanAnalyzer, err := analyzer.NewMalysisActiveScanAnalyzer(analyzer.DefaultMalysisActiveScanAnalyzerConfig())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create malysis active scan analyzer: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
analyzers = append(analyzers, malysisActiveScanAnalyzer)
|
||||||
|
} else {
|
||||||
|
malysisQueryAnalyzer, err := analyzer.NewMalysisQueryAnalyzer(analyzer.MalysisQueryAnalyzerConfig{})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create malysis query analyzer: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
analyzers = append(analyzers, malysisQueryAnalyzer)
|
||||||
}
|
}
|
||||||
|
|
||||||
interaction := guard.PackageManagerGuardInteraction{
|
interaction := guard.PackageManagerGuardInteraction{
|
||||||
@@ -34,8 +47,10 @@ func executeCommonFlow(ctx context.Context, config config.Config, pm packagemana
|
|||||||
Block: ui.Block,
|
Block: ui.Block,
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy, err := guard.NewPackageManagerGuard(guard.DefaultPackageManagerGuardConfig(),
|
guardConfig := guard.DefaultPackageManagerGuardConfig()
|
||||||
pm, packageResolver, []analyzer.PackageVersionAnalyzer{malysisQueryAnalyzer}, interaction)
|
guardConfig.DryRun = config.DryRun
|
||||||
|
|
||||||
|
proxy, err := guard.NewPackageManagerGuard(guardConfig, pm, packageResolver, analyzers, interaction)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create package manager guard: %w", err)
|
return fmt.Errorf("failed to create package manager guard: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ type Config struct {
|
|||||||
Transitive bool
|
Transitive bool
|
||||||
TransitiveDepth int
|
TransitiveDepth int
|
||||||
IncludeDevDependencies bool
|
IncludeDevDependencies bool
|
||||||
|
Paranoid bool
|
||||||
|
|
||||||
|
// DryRun to check for packages for risks.
|
||||||
|
// Do not actually execute any commands.
|
||||||
|
DryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inject config into context while protecting against context poisoning
|
// Inject config into context while protecting against context poisoning
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ type PackageManagerGuardConfig struct {
|
|||||||
ResolveDependencies bool
|
ResolveDependencies bool
|
||||||
MaxConcurrentAnalyzes int
|
MaxConcurrentAnalyzes int
|
||||||
AnalysisTimeout time.Duration
|
AnalysisTimeout time.Duration
|
||||||
|
DryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func DefaultPackageManagerGuardConfig() PackageManagerGuardConfig {
|
func DefaultPackageManagerGuardConfig() PackageManagerGuardConfig {
|
||||||
@@ -41,6 +42,7 @@ func DefaultPackageManagerGuardConfig() PackageManagerGuardConfig {
|
|||||||
ResolveDependencies: true,
|
ResolveDependencies: true,
|
||||||
MaxConcurrentAnalyzes: 10,
|
MaxConcurrentAnalyzes: 10,
|
||||||
AnalysisTimeout: 5 * time.Minute,
|
AnalysisTimeout: 5 * time.Minute,
|
||||||
|
DryRun: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,6 +162,11 @@ func (g *packageManagerGuard) continueExecution(ctx context.Context, pc *package
|
|||||||
return fmt.Errorf("no command to execute")
|
return fmt.Errorf("no command to execute")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if g.config.DryRun {
|
||||||
|
log.Debugf("Dry run, skipping command execution")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
cmd := exec.CommandContext(ctx, pc.Command.Exe, pc.Command.Args...)
|
cmd := exec.CommandContext(ctx, pc.Command.Exe, pc.Command.Args...)
|
||||||
cmd.Stdin = os.Stdin
|
cmd.Stdin = os.Stdin
|
||||||
cmd.Stdout = os.Stdout
|
cmd.Stdout = os.Stdout
|
||||||
|
|||||||
@@ -74,6 +74,8 @@ func main() {
|
|||||||
"Maximum depth of transitive dependencies to resolve")
|
"Maximum depth of transitive dependencies to resolve")
|
||||||
cmd.PersistentFlags().BoolVar(&globalConfig.IncludeDevDependencies, "include-dev-dependencies", false,
|
cmd.PersistentFlags().BoolVar(&globalConfig.IncludeDevDependencies, "include-dev-dependencies", false,
|
||||||
"Include dev dependencies in the dependency graph (slows down resolution)")
|
"Include dev dependencies in the dependency graph (slows down resolution)")
|
||||||
|
cmd.PersistentFlags().BoolVar(&globalConfig.DryRun, "dry-run", false, "Dry run skips execution of package manager")
|
||||||
|
cmd.PersistentFlags().BoolVar(&globalConfig.Paranoid, "paranoid", false, "Perform active scanning of unknown packages (slow)")
|
||||||
|
|
||||||
cmd.AddCommand(npm.NewNpmCommand())
|
cmd.AddCommand(npm.NewNpmCommand())
|
||||||
cmd.AddCommand(npm.NewPnpmCommand())
|
cmd.AddCommand(npm.NewPnpmCommand())
|
||||||
|
|||||||
Reference in New Issue
Block a user