mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
feat: Add Support for Proxy Based Npm Interceptor (#87)
* feat: Add experimental proxy based npm interceptor * refactor: Analysis cache * ci: Add E2E for npm proxy * fix: Handle dry-run in proxy flow * fix: Handle special case for scope package name * fix: Misc fixes * fix: Code review fixes * fix: Code review fixes * refactor: Reusable code into base registry interceptor * Pause npm process during user confirmation (#90) * pause npm process when prompting user for confirmation * disable progress bar * fix logging and close chan on return * update use of deprecated field * refactor: Separation of concerns for handling process state * fix: Safe permission for cert file * fix: Handle nil check for interaction hook * fix: Add test for base registry * Fix goreleaser for windows build (#93) * introduce platform specific process control * rename common.go to common_flow.go * feat: Add support for pause resume on windows * fix: Code review fixes * test: Add confirmation handler tests --------- Co-authored-by: Sahil Bansal <bansalsahil315@gmail.com>
This commit is contained in:
co-authored by
Sahil Bansal
parent
20c854e473
commit
779deeb23d
@@ -26,21 +26,17 @@ func TestLoggerInitialization(t *testing.T) {
|
||||
|
||||
// Initialize logger
|
||||
err := InitializeWithDir(logDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to initialize logger")
|
||||
defer Close()
|
||||
|
||||
// Check that directory was created
|
||||
if _, err := os.Stat(logDir); os.IsNotExist(err) {
|
||||
t.Errorf("Log directory was not created: %s", logDir)
|
||||
}
|
||||
_, err = os.Stat(logDir)
|
||||
assert.False(t, os.IsNotExist(err), "Log directory was not created: %s", logDir)
|
||||
|
||||
// Check that log file was created
|
||||
expectedLogFile := filepath.Join(logDir, time.Now().Format("20060102")+"-pmg.log")
|
||||
if _, err := os.Stat(expectedLogFile); os.IsNotExist(err) {
|
||||
t.Errorf("Log file was not created: %s", expectedLogFile)
|
||||
}
|
||||
_, err = os.Stat(expectedLogFile)
|
||||
assert.False(t, os.IsNotExist(err), "Log file was not created: %s", expectedLogFile)
|
||||
}
|
||||
|
||||
func TestLogEvent(t *testing.T) {
|
||||
@@ -50,9 +46,7 @@ func TestLogEvent(t *testing.T) {
|
||||
|
||||
// Initialize logger
|
||||
err := reinitializeForTest(logDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to initialize logger")
|
||||
defer Close()
|
||||
|
||||
// Log an event
|
||||
@@ -68,31 +62,21 @@ func TestLogEvent(t *testing.T) {
|
||||
}
|
||||
|
||||
err = LogEvent(event)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to log event: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to log event")
|
||||
|
||||
// Read the log file and verify the event was written
|
||||
logFilePath := filepath.Join(logDir, time.Now().Format("20060102")+"-pmg.log")
|
||||
data, err := os.ReadFile(logFilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read log file: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to read log file")
|
||||
|
||||
// Parse the JSON
|
||||
var loggedEvent Event
|
||||
err = json.Unmarshal(data, &loggedEvent)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse logged event: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to parse logged event")
|
||||
|
||||
// Verify the event
|
||||
if loggedEvent.EventType != EventTypeMalwareBlocked {
|
||||
t.Errorf("Expected event type %s, got %s", EventTypeMalwareBlocked, loggedEvent.EventType)
|
||||
}
|
||||
if loggedEvent.PackageName != "evil-package" {
|
||||
t.Errorf("Expected package name 'evil-package', got '%s'", loggedEvent.PackageName)
|
||||
}
|
||||
assert.Equal(t, EventTypeMalwareBlocked, loggedEvent.EventType)
|
||||
assert.Equal(t, "evil-package", loggedEvent.PackageName)
|
||||
}
|
||||
|
||||
func TestLogMalwareBlocked(t *testing.T) {
|
||||
@@ -102,9 +86,7 @@ func TestLogMalwareBlocked(t *testing.T) {
|
||||
|
||||
// Initialize logger
|
||||
err := reinitializeForTest(logDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to initialize logger")
|
||||
defer Close()
|
||||
|
||||
// Log malware blocked event
|
||||
@@ -113,25 +95,15 @@ func TestLogMalwareBlocked(t *testing.T) {
|
||||
// Read and verify
|
||||
logFilePath := filepath.Join(logDir, time.Now().Format("20060102")+"-pmg.log")
|
||||
data, err := os.ReadFile(logFilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read log file: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to read log file")
|
||||
|
||||
var event Event
|
||||
err = json.Unmarshal(data, &event)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse event: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to parse event")
|
||||
|
||||
if event.EventType != EventTypeMalwareBlocked {
|
||||
t.Errorf("Expected event type %s, got %s", EventTypeMalwareBlocked, event.EventType)
|
||||
}
|
||||
if event.PackageName != "malicious-pkg" {
|
||||
t.Errorf("Expected package 'malicious-pkg', got '%s'", event.PackageName)
|
||||
}
|
||||
if event.Ecosystem != "pypi" {
|
||||
t.Errorf("Expected ecosystem 'pypi', got '%s'", event.Ecosystem)
|
||||
}
|
||||
assert.Equal(t, EventTypeMalwareBlocked, event.EventType)
|
||||
assert.Equal(t, "malicious-pkg", event.PackageName)
|
||||
assert.Equal(t, "pypi", event.Ecosystem)
|
||||
}
|
||||
|
||||
func TestInitializeWithFile(t *testing.T) {
|
||||
@@ -148,9 +120,7 @@ func TestInitializeWithFile(t *testing.T) {
|
||||
// Reset for custom file
|
||||
once = sync.Once{}
|
||||
err = InitializeWithFile(logFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize logger with file: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to initialize logger with file")
|
||||
defer Close()
|
||||
|
||||
// Log an event
|
||||
@@ -163,33 +133,20 @@ func TestInitializeWithFile(t *testing.T) {
|
||||
}
|
||||
|
||||
err = LogEvent(event)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to log event: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to log event")
|
||||
|
||||
// Verify the custom log file was created and contains the event
|
||||
if _, err := os.Stat(logFile); os.IsNotExist(err) {
|
||||
t.Errorf("Custom log file was not created: %s", logFile)
|
||||
}
|
||||
_, err = os.Stat(logFile)
|
||||
assert.False(t, os.IsNotExist(err), "Custom log file was not created: %s", logFile)
|
||||
|
||||
data, err := os.ReadFile(logFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read custom log file: %v", err)
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
t.Error("Custom log file is empty")
|
||||
}
|
||||
assert.NoError(t, err, "Failed to read custom log file")
|
||||
assert.NotEmpty(t, data, "Custom log file is empty")
|
||||
|
||||
var loggedEvent Event
|
||||
err = json.Unmarshal(data, &loggedEvent)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse logged event: %v", err)
|
||||
}
|
||||
|
||||
if loggedEvent.PackageName != "test-package" {
|
||||
t.Errorf("Expected package 'test-package', got '%s'", loggedEvent.PackageName)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to parse logged event")
|
||||
assert.Equal(t, "test-package", loggedEvent.PackageName)
|
||||
}
|
||||
|
||||
func TestCleanupOldLogs(t *testing.T) {
|
||||
@@ -197,38 +154,28 @@ func TestCleanupOldLogs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
logDir := filepath.Join(tmpDir, ".pmg", "logs")
|
||||
err := os.MkdirAll(logDir, 0755)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create log directory: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to create log directory")
|
||||
|
||||
// Create old log files
|
||||
oldDate := time.Now().AddDate(0, 0, -10)
|
||||
oldLogFile := filepath.Join(logDir, oldDate.Format("20060102")+"-pmg.log")
|
||||
err = os.WriteFile(oldLogFile, []byte("old log"), 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create old log file: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to create old log file")
|
||||
|
||||
// Change the modification time to make it appear old
|
||||
oldTime := time.Now().AddDate(0, 0, -10)
|
||||
err = os.Chtimes(oldLogFile, oldTime, oldTime)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to change file time: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to change file time")
|
||||
|
||||
// Create a recent log file
|
||||
recentLogFile := filepath.Join(logDir, time.Now().Format("20060102")+"-pmg.log")
|
||||
err = os.WriteFile(recentLogFile, []byte("recent log"), 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create recent log file: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to create recent log file")
|
||||
|
||||
// Initialize logger (which triggers cleanup)
|
||||
logger := &fileWithRotationLogger{}
|
||||
err = logger.init(logDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
assert.NoError(t, err, "Failed to initialize logger")
|
||||
|
||||
defer logger.Close()
|
||||
|
||||
@@ -236,12 +183,10 @@ func TestCleanupOldLogs(t *testing.T) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Check that old file was deleted
|
||||
if _, err := os.Stat(oldLogFile); !os.IsNotExist(err) {
|
||||
t.Error("Old log file should have been deleted")
|
||||
}
|
||||
_, err = os.Stat(oldLogFile)
|
||||
assert.True(t, os.IsNotExist(err), "Old log file should have been deleted")
|
||||
|
||||
// Check that recent file still exists
|
||||
if _, err := os.Stat(recentLogFile); os.IsNotExist(err) {
|
||||
t.Error("Recent log file should still exist")
|
||||
}
|
||||
_, err = os.Stat(recentLogFile)
|
||||
assert.False(t, os.IsNotExist(err), "Recent log file should still exist")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package flows
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func platformPauseProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := cmd.Process.Signal(syscall.SIGSTOP); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func platformResumeProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := cmd.Process.Signal(syscall.SIGCONT); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package flows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var (
|
||||
modntdll = windows.NewLazySystemDLL("ntdll.dll")
|
||||
procNtSuspendProcess = modntdll.NewProc("NtSuspendProcess")
|
||||
procNtResumeProcess = modntdll.NewProc("NtResumeProcess")
|
||||
)
|
||||
|
||||
// platformPauseProcess suspends the process using Windows NT API.
|
||||
//
|
||||
// Known limitations:
|
||||
// - Race condition: threads created during suspension are not suspended
|
||||
// - Remote thread injection still possible (very rare)
|
||||
//
|
||||
// For PMG's use case (brief suspension during user prompts), these limitations
|
||||
// are acceptable.
|
||||
//
|
||||
// References:
|
||||
// - gopsutil: https://github.com/shirou/gopsutil/blob/master/process/process_windows.go
|
||||
// - Analysis: https://github.com/diversenok/Suspending-Techniques
|
||||
func platformPauseProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
handle, err := windows.OpenProcess(
|
||||
windows.PROCESS_SUSPEND_RESUME,
|
||||
false,
|
||||
uint32(cmd.Process.Pid),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open process for suspension: %w", err)
|
||||
}
|
||||
|
||||
defer windows.CloseHandle(handle)
|
||||
|
||||
r1, _, _ := procNtSuspendProcess.Call(uintptr(handle))
|
||||
if r1 != 0 {
|
||||
return fmt.Errorf("NtSuspendProcess failed with NTSTATUS=0x%.8X", r1)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// platformResumeProcess resumes a suspended process using Windows NT API.
|
||||
func platformResumeProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
handle, err := windows.OpenProcess(
|
||||
windows.PROCESS_SUSPEND_RESUME,
|
||||
false,
|
||||
uint32(cmd.Process.Pid),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open process for resumption: %w", err)
|
||||
}
|
||||
|
||||
defer windows.CloseHandle(handle)
|
||||
|
||||
r1, _, _ := procNtResumeProcess.Call(uintptr(handle))
|
||||
if r1 != 0 {
|
||||
return fmt.Errorf("NtResumeProcess failed with NTSTATUS=0x%.8X", r1)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package flows
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPlatformPauseResumeProcess(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("Windows-only test")
|
||||
}
|
||||
|
||||
cmd := exec.Command("ping", "127.0.0.1", "-n", "60")
|
||||
err := cmd.Start()
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer cmd.Process.Kill()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
err = platformPauseProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
err = platformResumeProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformPauseProcessNil(t *testing.T) {
|
||||
err := platformPauseProcess(nil)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformResumeProcessNil(t *testing.T) {
|
||||
err := platformResumeProcess(nil)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformPauseProcessNilProcess(t *testing.T) {
|
||||
cmd := exec.Command("ping", "127.0.0.1")
|
||||
err := platformPauseProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformResumeProcessNilProcess(t *testing.T) {
|
||||
cmd := exec.Command("ping", "127.0.0.1")
|
||||
|
||||
err := platformResumeProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformPauseProcessExited(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("Windows-only test")
|
||||
}
|
||||
|
||||
cmd := exec.Command("cmd", "/c", "exit 0")
|
||||
err := cmd.Start()
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer cmd.Process.Kill()
|
||||
|
||||
err = platformPauseProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformResumeProcessExited(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("Windows-only test")
|
||||
}
|
||||
|
||||
cmd := exec.Command("cmd", "/c", "exit 0")
|
||||
err := cmd.Start()
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer cmd.Process.Kill()
|
||||
|
||||
err = platformResumeProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPlatformPauseResumeMultipleTimes(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("Windows-only test")
|
||||
}
|
||||
|
||||
cmd := exec.Command("ping", "127.0.0.1", "-n", "60")
|
||||
err := cmd.Start()
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer cmd.Process.Kill()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
err = platformPauseProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
err = platformResumeProcess(cmd)
|
||||
assert.NoError(t, err)
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package flows
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/safedep/dry/log"
|
||||
"github.com/safedep/pmg/analyzer"
|
||||
"github.com/safedep/pmg/config"
|
||||
"github.com/safedep/pmg/guard"
|
||||
"github.com/safedep/pmg/internal/ui"
|
||||
"github.com/safedep/pmg/packagemanager"
|
||||
"github.com/safedep/pmg/proxy"
|
||||
"github.com/safedep/pmg/proxy/certmanager"
|
||||
"github.com/safedep/pmg/proxy/interceptors"
|
||||
)
|
||||
|
||||
type proxyFlow struct {
|
||||
pm packagemanager.PackageManager
|
||||
packageResolver packagemanager.PackageResolver
|
||||
}
|
||||
|
||||
// ProxyFlow creates a new proxy-based flow for package manager protection
|
||||
func ProxyFlow(pm packagemanager.PackageManager, packageResolver packagemanager.PackageResolver) *proxyFlow {
|
||||
return &proxyFlow{
|
||||
pm: pm,
|
||||
packageResolver: packageResolver,
|
||||
}
|
||||
}
|
||||
|
||||
// Run executes the proxy-based flow
|
||||
func (f *proxyFlow) Run(ctx context.Context, args []string, parsedCmd *packagemanager.ParsedCommand) error {
|
||||
cfg := config.Get()
|
||||
|
||||
// Check if dry-run mode is enabled
|
||||
if cfg.DryRun {
|
||||
ui.SetStatus("Running in dry-run mode (proxy mode)")
|
||||
log.Infof("Dry-run mode: Would execute %s with experimental proxy protection", f.pm.Name())
|
||||
log.Infof("Dry-run mode: Command would be: %s %v", parsedCmd.Command.Exe, parsedCmd.Command.Args)
|
||||
ui.ClearStatus()
|
||||
return nil
|
||||
}
|
||||
|
||||
ui.SetStatus("Initializing experimental proxy mode...")
|
||||
|
||||
// Setup CA certificate for MITM
|
||||
caCert, caCertPath, err := f.setupCACertificate()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to setup CA certificate for proxy mode: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// Clean up temporary CA certificate file
|
||||
if caCertPath != "" {
|
||||
if err := os.Remove(caCertPath); err != nil {
|
||||
log.Errorf("Failed to remove CA certificate file: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Create certificate manager
|
||||
certMgr, err := f.createCertificateManager(caCert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create certificate manager: %w", err)
|
||||
}
|
||||
|
||||
// Create analyzer
|
||||
malysisAnalyzer, err := f.createAnalyzer()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create analyzer: %w", err)
|
||||
}
|
||||
|
||||
// Create analysis cache
|
||||
cache := interceptors.NewInMemoryAnalysisCache()
|
||||
|
||||
// Create confirmation channel and start confirmation handler
|
||||
confirmationChan := make(chan *interceptors.ConfirmationRequest, 10)
|
||||
defer close(confirmationChan)
|
||||
|
||||
// Create interaction callbacks for user prompts
|
||||
interaction := guard.PackageManagerGuardInteraction{
|
||||
SetStatus: ui.SetStatus,
|
||||
ClearStatus: ui.ClearStatus,
|
||||
ShowWarning: ui.ShowWarning,
|
||||
GetConfirmationOnMalware: ui.GetConfirmationOnMalware,
|
||||
Block: ui.Block,
|
||||
}
|
||||
|
||||
// Get the ecosystem from the package manager
|
||||
ecosystem := f.pm.Ecosystem()
|
||||
|
||||
// Check if proxy mode is supported for this ecosystem
|
||||
if !interceptors.IsSupported(ecosystem) {
|
||||
return fmt.Errorf("proxy mode is not supported for %s", ecosystem.String())
|
||||
}
|
||||
|
||||
// Create ecosystem-specific interceptor using factory
|
||||
factory := interceptors.NewInterceptorFactory(malysisAnalyzer, cache, confirmationChan, interaction)
|
||||
interceptor, err := factory.CreateInterceptor(ecosystem)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create interceptor for %s: %w", ecosystem.String(), err)
|
||||
}
|
||||
|
||||
log.Debugf("Created %s interceptor for ecosystem %s", interceptor.Name(), ecosystem.String())
|
||||
|
||||
// Create and start proxy server
|
||||
proxyServer, proxyAddr, err := f.createAndStartProxyServer(certMgr, interceptor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to start proxy server: %w", err)
|
||||
}
|
||||
|
||||
// Ensure proxy is stopped on exit
|
||||
defer func() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := proxyServer.Stop(shutdownCtx); err != nil {
|
||||
log.Errorf("Failed to stop proxy server: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
ui.ClearStatus()
|
||||
log.Infof("Proxy server started on %s", proxyAddr)
|
||||
log.Infof("Running %s with proxy protection enabled", f.pm.Name())
|
||||
|
||||
// Execute the package manager command with proxy environment variables
|
||||
return f.executeWithProxy(ctx, parsedCmd, proxyAddr, caCertPath, confirmationChan, interaction)
|
||||
}
|
||||
|
||||
// setupCACertificate generates or loads a CA certificate for MITM
|
||||
func (f *proxyFlow) setupCACertificate() (*certmanager.Certificate, string, error) {
|
||||
log.Debugf("Generating CA certificate for proxy MITM")
|
||||
|
||||
// Generate CA certificate
|
||||
caConfig := certmanager.DefaultCertManagerConfig()
|
||||
caCert, err := certmanager.GenerateCA(caConfig)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to generate CA certificate: %w", err)
|
||||
}
|
||||
|
||||
// Write CA certificate to temporary file for package managers to trust
|
||||
tempDir := os.TempDir()
|
||||
caCertPath := filepath.Join(tempDir, fmt.Sprintf("pmg-ca-cert-%d.pem", os.Getpid()))
|
||||
|
||||
if err := os.WriteFile(caCertPath, caCert.Certificate, 0600); err != nil {
|
||||
return nil, "", fmt.Errorf("failed to write CA certificate to %s: %w", caCertPath, err)
|
||||
}
|
||||
|
||||
log.Debugf("CA certificate written to %s", caCertPath)
|
||||
|
||||
return caCert, caCertPath, nil
|
||||
}
|
||||
|
||||
// createCertificateManager creates a certificate manager with the given CA certificate
|
||||
func (f *proxyFlow) createCertificateManager(caCert *certmanager.Certificate) (certmanager.CertificateManager, error) {
|
||||
caConfig := certmanager.DefaultCertManagerConfig()
|
||||
certMgr, err := certmanager.NewCertificateManagerWithCA(caCert, caConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create certificate manager: %w", err)
|
||||
}
|
||||
|
||||
return certMgr, nil
|
||||
}
|
||||
|
||||
// createAnalyzer creates the malysis query analyzer
|
||||
func (f *proxyFlow) createAnalyzer() (analyzer.PackageVersionAnalyzer, error) {
|
||||
cfg := config.Get()
|
||||
|
||||
// Use paranoid mode (active scan) if enabled, otherwise use query mode
|
||||
if cfg.Config.Paranoid {
|
||||
log.Debugf("Creating malysis active scan analyzer (paranoid mode)")
|
||||
return analyzer.NewMalysisActiveScanAnalyzer(analyzer.DefaultMalysisActiveScanAnalyzerConfig())
|
||||
}
|
||||
|
||||
log.Debugf("Creating malysis query analyzer")
|
||||
return analyzer.NewMalysisQueryAnalyzer(analyzer.MalysisQueryAnalyzerConfig{})
|
||||
}
|
||||
|
||||
// createAndStartProxyServer creates and starts the proxy server with the given interceptor
|
||||
func (f *proxyFlow) createAndStartProxyServer(
|
||||
certMgr certmanager.CertificateManager,
|
||||
interceptor proxy.Interceptor,
|
||||
) (proxy.ProxyServer, string, error) {
|
||||
proxyConfig := &proxy.ProxyConfig{
|
||||
ListenAddr: "127.0.0.1:0",
|
||||
CertManager: certMgr,
|
||||
EnableMITM: true,
|
||||
Interceptors: []proxy.Interceptor{interceptor},
|
||||
ConnectTimeout: 30 * time.Second,
|
||||
RequestTimeout: 5 * time.Minute,
|
||||
}
|
||||
|
||||
proxyServer, err := proxy.NewProxyServer(proxyConfig)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to create proxy server: %w", err)
|
||||
}
|
||||
|
||||
if err := proxyServer.Start(); err != nil {
|
||||
return nil, "", fmt.Errorf("failed to start proxy server: %w", err)
|
||||
}
|
||||
|
||||
proxyAddr := proxyServer.Address()
|
||||
if proxyAddr == "" {
|
||||
return nil, "", fmt.Errorf("proxy server started but address is empty")
|
||||
}
|
||||
|
||||
return proxyServer, proxyAddr, nil
|
||||
}
|
||||
|
||||
// executeWithProxy executes the package manager command with proxy environment variables
|
||||
func (f *proxyFlow) executeWithProxy(ctx context.Context, parsedCmd *packagemanager.ParsedCommand,
|
||||
proxyAddr, caCertPath string, confirmationChan chan *interceptors.ConfirmationRequest,
|
||||
interaction guard.PackageManagerGuardInteraction,
|
||||
) error {
|
||||
// Build proxy URL
|
||||
proxyURL := fmt.Sprintf("http://%s", proxyAddr)
|
||||
|
||||
// Create command
|
||||
cmd := exec.CommandContext(ctx, parsedCmd.Command.Exe, parsedCmd.Command.Args...)
|
||||
|
||||
// Set proxy environment variables. This is what tells the executed command to use the proxy for communication.
|
||||
// However, every package manager has its nuances and may require additional environment variables to be set.
|
||||
cmd.Env = os.Environ()
|
||||
cmd.Env = append(cmd.Env,
|
||||
fmt.Sprintf("HTTP_PROXY=%s", proxyURL),
|
||||
fmt.Sprintf("HTTPS_PROXY=%s", proxyURL),
|
||||
fmt.Sprintf("NODE_EXTRA_CA_CERTS=%s", caCertPath),
|
||||
fmt.Sprintf("http_proxy=%s", proxyURL),
|
||||
fmt.Sprintf("https_proxy=%s", proxyURL),
|
||||
fmt.Sprintf("SSL_CERT_FILE=%s", caCertPath),
|
||||
fmt.Sprintf("REQUESTS_CA_BUNDLE=%s", caCertPath),
|
||||
fmt.Sprintf("PIP_CERT=%s", caCertPath),
|
||||
fmt.Sprintf("PIP_PROXY=%s", proxyURL),
|
||||
"NPM_CONFIG_PROGRESS=false",
|
||||
)
|
||||
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
log.Debugf("Executing command: %s %v", parsedCmd.Command.Exe, parsedCmd.Command.Args)
|
||||
log.Debugf("Proxy environment: HTTP_PROXY=%s, HTTPS_PROXY=%s, NODE_EXTRA_CA_CERTS=%s", proxyURL, proxyURL, caCertPath)
|
||||
|
||||
// Start confirmation handler in goroutine. Use confirmation hooks to pause and resume the executed
|
||||
// process to prevent stdout and stderr from being mixed up. Pause / resume is on a best effort basis.
|
||||
// We do not consider it a critical error if pause / resume fails.
|
||||
go interceptors.HandleConfirmationRequests(confirmationChan, interaction, &interceptors.ConfirmationHook{
|
||||
BeforeInteraction: func([]*analyzer.PackageVersionAnalysisResult) error {
|
||||
if err := platformPauseProcess(cmd); err != nil {
|
||||
log.Warnf("Failed to pause process for user interaction: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
AfterInteraction: func([]*analyzer.PackageVersionAnalysisResult, bool) error {
|
||||
if err := platformResumeProcess(cmd); err != nil {
|
||||
log.Warnf("Failed to resume process after user interaction: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
os.Exit(exitErr.ExitCode())
|
||||
}
|
||||
|
||||
return fmt.Errorf("failed to execute %s: %w", f.pm.Name(), err)
|
||||
}
|
||||
|
||||
log.Debugf("Command completed successfully")
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user