Exploit database

GH-e76a3d3d0be61d55e6620c59c6a75b15

cumakurt/php2shell-scan

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

412 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3
cumakurt/php2shell-scanRevision 7f4ea41c2e62

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

internal/httpx/httpx.go

Go · 11,139 bytes
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Cuma KURT <[email protected]>
//
// php2shell-scan is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version. It is distributed WITHOUT ANY WARRANTY; see the LICENSE file
// for the full text.

// Package httpx provides the HTTP client shared by every scanner module.
//
// Safety and reliability properties enforced here:
//   - every request has a timeout,
//   - response bodies are bounded,
//   - redirects are capped and cannot leave the authorised host,
//   - requests are rate limited,
//   - only idempotent requests are retried,
//   - a per-run request budget prevents runaway scanning,
//   - the scanner identifies itself in the User-Agent.
package httpx

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

// DefaultUserAgent identifies the scanner to target operators.
const DefaultUserAgent = "php2shell-scan/1.0 (+authorized security assessment)"

// ErrRequestBudget is returned when the configured request budget is exhausted.
var ErrRequestBudget = errors.New("request budget for the target or run is exhausted")

// Options configures a Client.
type Options struct {
	Timeout           time.Duration
	MaxBodyBytes      int64
	RequestsPerSecond float64
	UserAgent         string

	// Headers are added to every request (for example bearer tokens).
	Headers map[string]string
	// BasicAuthUser and BasicAuthPassword enable HTTP basic authentication.
	BasicAuthUser     string
	BasicAuthPassword string

	// ProxyURL routes requests through an HTTP/SOCKS5 proxy.
	ProxyURL string
	// CACertFile replaces the system trust store with the given PEM bundle.
	CACertFile string
	// InsecureSkipVerify disables TLS verification. It is opt-in and always
	// reported as a limitation by the caller.
	InsecureSkipVerify bool

	// MaxAttempts is the total number of attempts for idempotent requests.
	// Values below 1 are treated as 1 (no retry).
	MaxAttempts int
	// RetryBaseDelay is the first backoff delay; it doubles per attempt.
	RetryBaseDelay time.Duration
	// MaxRequests caps the total number of HTTP attempts in this run.
	// Zero means unlimited.
	MaxRequests int64
}

// Response is a bounded, already-read HTTP response.
type Response struct {
	URL         string
	Status      int
	Header      http.Header
	Body        []byte
	Latency     time.Duration
	Truncated   bool
	ContentType string
	Attempts    int
}

// BodyText returns the body as a trimmed string.
func (r *Response) BodyText() string { return strings.TrimSpace(string(r.Body)) }

// HeaderValue returns the first value of a header (case-insensitive).
func (r *Response) HeaderValue(name string) string { return r.Header.Get(name) }

// Client is a rate-limited, budgeted HTTP client.
type Client struct {
	hc   *http.Client
	opts Options

	mu       sync.Mutex
	nextSlot time.Time

	requests int64
}

// New builds a Client. A non-positive body limit falls back to 1 MiB.
func New(opts Options) *Client {
	if opts.Timeout <= 0 {
		opts.Timeout = 10 * time.Second
	}
	if opts.MaxBodyBytes <= 0 {
		opts.MaxBodyBytes = 1 << 20
	}
	if opts.UserAgent == "" {
		opts.UserAgent = DefaultUserAgent
	}
	if opts.MaxAttempts < 1 {
		opts.MaxAttempts = 1
	}
	if opts.RetryBaseDelay <= 0 {
		opts.RetryBaseDelay = 250 * time.Millisecond
	}

	tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12}
	if opts.InsecureSkipVerify {
		tlsConfig.InsecureSkipVerify = true
	}
	if opts.CACertFile != "" {
		if pool, err := loadCertPool(opts.CACertFile); err == nil {
			tlsConfig.RootCAs = pool
		}
	}

	proxy := http.ProxyFromEnvironment
	if opts.ProxyURL != "" {
		if parsed, err := url.Parse(opts.ProxyURL); err == nil {
			proxy = http.ProxyURL(parsed)
		}
	}

	transport := &http.Transport{
		Proxy:                 proxy,
		TLSClientConfig:       tlsConfig,
		TLSHandshakeTimeout:   opts.Timeout,
		ResponseHeaderTimeout: opts.Timeout,
		ExpectContinueTimeout: 1 * time.Second,
		MaxIdleConns:          32,
		MaxIdleConnsPerHost:   4,
		IdleConnTimeout:       30 * time.Second,
		DisableCompression:    false,
	}

	hc := &http.Client{
		Timeout:   opts.Timeout,
		Transport: transport,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) >= 5 {
				return errors.New("stopped after 5 redirects")
			}
			origin := via[0].URL
			if !strings.EqualFold(req.URL.Host, origin.Host) {
				return fmt.Errorf("blocked cross-host redirect to %q", req.URL.Host)
			}
			return nil
		},
	}

	return &Client{hc: hc, opts: opts}
}

func loadCertPool(path string) (*x509.CertPool, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read CA bundle: %w", err)
	}
	pool := x509.NewCertPool()
	if !pool.AppendCertsFromPEM(data) {
		return nil, errors.New("CA bundle contains no valid PEM certificates")
	}
	return pool, nil
}

// Requests returns the number of HTTP attempts issued so far.
func (c *Client) Requests() int64 { return atomic.LoadInt64(&c.requests) }

// Get performs a GET request.
func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) {
	return c.do(ctx, http.MethodGet, rawURL, "", nil)
}

// Head performs a HEAD request.
func (c *Client) Head(ctx context.Context, rawURL string) (*Response, error) {
	return c.do(ctx, http.MethodHead, rawURL, "", nil)
}

// Options performs an OPTIONS request. The method is safe and idempotent, so
// it is suitable for checking which verbs a handler advertises.
func (c *Client) Options(ctx context.Context, rawURL string) (*Response, error) {
	return c.do(ctx, http.MethodOptions, rawURL, "", nil)
}

// PostForm performs an application/x-www-form-urlencoded POST. POST is never
// retried because it may not be idempotent.
func (c *Client) PostForm(ctx context.Context, rawURL string, values url.Values) (*Response, error) {
	return c.do(ctx, http.MethodPost, rawURL, "application/x-www-form-urlencoded", strings.NewReader(values.Encode()))
}

func (c *Client) do(ctx context.Context, method, rawURL, contentType string, body io.Reader) (*Response, error) {
	// A body reader cannot be replayed, so POST gets exactly one attempt.
	attempts := 1
	if isIdempotent(method) {
		attempts = c.opts.MaxAttempts
	}
	if body != nil && attempts > 1 {
		attempts = 1
	}

	var lastErr error
	for attempt := 1; attempt <= attempts; attempt++ {
		if attempt > 1 {
			if err := sleepBackoff(ctx, c.opts.RetryBaseDelay, attempt-1); err != nil {
				return nil, err
			}
		}

		resp, err := c.once(ctx, method, rawURL, contentType, body)
		if err == nil && !shouldRetryStatus(resp.Status) {
			return resp, nil
		}
		if err == nil {
			// Retryable status: remember it in case this was the last attempt.
			lastErr = fmt.Errorf("target returned retryable status %d", resp.Status)
			if attempt == attempts {
				resp.Attempts = attempt
				return resp, nil
			}
			continue
		}
		lastErr = err
		if !isTransient(err) || attempt == attempts {
			return nil, err
		}
	}
	return nil, lastErr
}

func (c *Client) once(ctx context.Context, method, rawURL, contentType string, body io.Reader) (*Response, error) {
	if err := c.reserve(); err != nil {
		return nil, err
	}
	if err := c.wait(ctx); err != nil {
		return nil, err
	}

	req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
	if err != nil {
		return nil, fmt.Errorf("build request: %w", err)
	}
	req.Header.Set("User-Agent", c.opts.UserAgent)
	req.Header.Set("Accept", "*/*")
	if contentType != "" {
		req.Header.Set("Content-Type", contentType)
	}
	for name, value := range c.opts.Headers {
		req.Header.Set(name, value)
	}
	if c.opts.BasicAuthUser != "" || c.opts.BasicAuthPassword != "" {
		req.SetBasicAuth(c.opts.BasicAuthUser, c.opts.BasicAuthPassword)
	}

	start := time.Now()
	resp, err := c.hc.Do(req)
	if err != nil {
		return nil, err
	}
	defer func() {
		_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
		resp.Body.Close()
	}()

	limit := c.opts.MaxBodyBytes
	data, readErr := io.ReadAll(io.LimitReader(resp.Body, limit+1))
	if readErr != nil && len(data) == 0 {
		return nil, fmt.Errorf("read response body: %w", readErr)
	}

	truncated := int64(len(data)) > limit
	if truncated {
		data = data[:limit]
	}

	return &Response{
		URL:         resp.Request.URL.String(),
		Status:      resp.StatusCode,
		Header:      resp.Header,
		Body:        data,
		Latency:     time.Since(start),
		Truncated:   truncated,
		ContentType: resp.Header.Get("Content-Type"),
		Attempts:    1,
	}, nil
}

func isIdempotent(method string) bool {
	switch method {
	case http.MethodGet, http.MethodHead, http.MethodOptions:
		return true
	default:
		return false
	}
}

func shouldRetryStatus(status int) bool {
	switch status {
	case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
		return true
	default:
		return false
	}
}

func isTransient(err error) bool {
	if err == nil {
		return false
	}
	if errors.Is(err, context.Canceled) || errors.Is(err, ErrRequestBudget) {
		return false
	}
	msg := strings.ToLower(err.Error())
	// DNS failures and refused connections are permanent: retrying them only
	// slows the scan and cannot succeed.
	for _, permanent := range []string{"no such host", "connection refused", "certificate", "unsupported protocol"} {
		if strings.Contains(msg, permanent) {
			return false
		}
	}
	for _, token := range []string{
		"timeout", "temporarily unavailable", "connection reset",
		"broken pipe", "eof", "i/o timeout", "tls handshake",
	} {
		if strings.Contains(msg, token) {
			return true
		}
	}
	return false
}

// reserve consumes one unit of the request budget.
func (c *Client) reserve() error {
	if c.opts.MaxRequests <= 0 {
		atomic.AddInt64(&c.requests, 1)
		return nil
	}
	if atomic.AddInt64(&c.requests, 1) > c.opts.MaxRequests {
		return ErrRequestBudget
	}
	return nil
}

// wait implements a simple token-spacing limiter. A non-positive rate disables
// throttling (useful in tests).
func (c *Client) wait(ctx context.Context) error {
	if c.opts.RequestsPerSecond <= 0 {
		return nil
	}
	interval := time.Duration(float64(time.Second) / c.opts.RequestsPerSecond)

	c.mu.Lock()
	now := time.Now()
	slot := c.nextSlot
	if slot.Before(now) {
		slot = now
	}
	c.nextSlot = slot.Add(interval)
	c.mu.Unlock()

	delay := time.Until(slot)
	if delay <= 0 {
		return nil
	}
	return sleepBackoff(ctx, delay, 1)
}

// sleepBackoff waits for delay*2^(step-1) plus jitter, honouring cancellation.
func sleepBackoff(ctx context.Context, delay time.Duration, step int) error {
	if delay <= 0 {
		return nil
	}
	wait := delay * time.Duration(1<<uint(step-1))
	if wait > 5*time.Second {
		wait = 5 * time.Second
	}
	if jitter := time.Duration(rand.Int63n(int64(wait/2) + 1)); jitter > 0 {
		wait += jitter
	}
	timer := time.NewTimer(wait)
	defer timer.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-timer.C:
		return nil
	}
}