package server import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io" "mime" "net" "net/http" "net/netip" "net/url" "path" "strings" "syscall" "time" "git.a-wan.net/alan/pipelines/internal/chattools" "git.a-wan.net/alan/pipelines/internal/protocol" ) // show_image downloads a web image on the server, so the operator's device // never has to fetch a cross-origin address (which many hosts refuse), and // keeps the bytes as the item's snapshot. The download is SSRF-safe: https // only, every connection (redirects included) to a public unicast address // checked after DNS resolution, no proxy, no credentials, a timeout, at most // chattools.MaxFetchedImageBytes, and only raster image types whose bytes // agree with the declared type. const shownImageFetchTimeout = 20 * time.Second // shownImageTypes are the image types fetched, by extension. SVG is refused: // served from the app's origin it could carry script. var shownImageTypes = map[string]string{ "image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp", "image/avif": ".avif", "image/bmp": ".bmp", } // shownImageFetcher downloads web images. allowed decides which resolved // addresses may be dialed; tlsConfig is for tests. type shownImageFetcher struct { allowed func(netip.Addr) bool tlsConfig *tls.Config } // publicAddress admits only global unicast addresses that are not private, // loopback, link-local, shared (CGNAT), documentation or otherwise special. func publicAddress(addr netip.Addr) bool { addr = addr.Unmap() if !addr.IsValid() || !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() || addr.IsMulticast() || addr.IsUnspecified() { return false } for _, prefix := range shownBlockedPrefixes { if prefix.Contains(addr) { return false } } return true } var shownBlockedPrefixes = []netip.Prefix{ netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("192.0.2.0/24"), netip.MustParsePrefix("198.18.0.0/15"), netip.MustParsePrefix("198.51.100.0/24"), netip.MustParsePrefix("203.0.113.0/24"), netip.MustParsePrefix("240.0.0.0/4"), netip.MustParsePrefix("64:ff9b::/96"), netip.MustParsePrefix("64:ff9b:1::/48"), netip.MustParsePrefix("2001::/23"), netip.MustParsePrefix("2001:db8::/32"), netip.MustParsePrefix("2002::/16"), } var errShownAddressRefused = errors.New("the image host resolves to a private or local address, which Pipelines does not fetch from") func (f shownImageFetcher) client() *http.Client { allowed := f.allowed if allowed == nil { allowed = publicAddress } dialer := &net.Dialer{Timeout: 10 * time.Second, Control: func(_, address string, _ syscall.RawConn) error { host, _, err := net.SplitHostPort(address) if err != nil { return err } addr, err := netip.ParseAddr(host) if err != nil || !allowed(addr) { return errShownAddressRefused } return nil }} transport := &http.Transport{ Proxy: nil, DialContext: dialer.DialContext, TLSClientConfig: f.tlsConfig, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 15 * time.Second, MaxIdleConns: 1, DisableKeepAlives: true, } return &http.Client{Transport: transport, Timeout: shownImageFetchTimeout, CheckRedirect: func(request *http.Request, via []*http.Request) error { if len(via) >= 5 { return errors.New("the image URL redirects too many times") } if request.URL.Scheme != "https" { return fmt.Errorf("the image URL redirects to a non-https address (%s)", request.URL.Redacted()) } return nil }} } // fetchShownImage downloads the https image at raw and records it as a // snapshot image item (id is the item's id). func (s *chatToolService) fetchShownImage(ctx context.Context, sessionID, id, raw string) (protocol.ChatShownItem, error) { address, err := shownImageURL(raw) if err != nil { return protocol.ChatShownItem{}, err } data, mediaType, err := s.fetch.get(ctx, address) if err != nil { return protocol.ChatShownItem{}, err } name := shownImageName(address, shownImageTypes[mediaType]) path, size, err := s.writeSnapshot(sessionID, id, name, bytes.NewReader(data)) if err != nil { return protocol.ChatShownItem{}, fmt.Errorf("Pipelines downloaded the image but could not keep it: %v", err) } return protocol.ChatShownItem{Kind: protocol.ChatShownImage, Path: path, Name: name, Size: size, Mime: mediaType, Snapshot: true, URL: address}, nil } // get downloads one image and returns its bytes and media type. func (f shownImageFetcher) get(ctx context.Context, address string) ([]byte, string, error) { ctx, cancel := context.WithTimeout(ctx, shownImageFetchTimeout) defer cancel() request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) if err != nil { return nil, "", errors.New("the image URL is not valid") } request.Header.Set("Accept", "image/png,image/jpeg,image/gif,image/webp,image/avif,image/bmp;q=0.9") request.Header.Set("User-Agent", "Pipelines-image-fetch/1") response, err := f.client().Do(request) if err != nil { if errors.Is(err, errShownAddressRefused) { return nil, "", errShownAddressRefused } var redirect *url.Error if errors.As(err, &redirect) && redirect.Err != nil && strings.Contains(redirect.Err.Error(), "redirect") { return nil, "", redirect.Err } return nil, "", fmt.Errorf("the image could not be downloaded: %v", shownFetchError(err)) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return nil, "", fmt.Errorf("the image host answered %s", response.Status) } mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type")) if _, ok := shownImageTypes[mediaType]; !ok { if mediaType == "" { mediaType = "no content type" } return nil, "", fmt.Errorf("the URL is %s, not a PNG, JPEG, GIF, WebP, AVIF or BMP image", mediaType) } if response.ContentLength > chattools.MaxFetchedImageBytes { return nil, "", fmt.Errorf("the image is %s; the limit is 10 MiB", humanBytes(response.ContentLength)) } data, err := io.ReadAll(io.LimitReader(response.Body, chattools.MaxFetchedImageBytes+1)) if err != nil { return nil, "", fmt.Errorf("the image download failed: %v", shownFetchError(err)) } if len(data) > chattools.MaxFetchedImageBytes { return nil, "", errors.New("the image is larger than the 10 MiB limit") } if len(data) == 0 { return nil, "", errors.New("the image is empty") } if sniffed := http.DetectContentType(data); strings.HasPrefix(sniffed, "text/") || sniffed == "application/octet-stream" && mediaType != "image/avif" { return nil, "", fmt.Errorf("the URL says it is %s but its content is not an image", mediaType) } return data, mediaType, nil } func shownFetchError(err error) error { var urlErr *url.Error if errors.As(err, &urlErr) { return urlErr.Err } return err } // shownImageName is the image's file name from its URL path, with the // extension of its type. func shownImageName(address, extension string) string { base := "image" if parsed, err := url.Parse(address); err == nil { if name := path.Base(parsed.Path); name != "." && name != "/" && name != "" { base = strings.TrimSuffix(name, path.Ext(name)) } } base = safeSnapshotName(base) if len(base) > 120 { base = truncateUTF8(base, 120) } return base + extension }