flawopen.com/ssrf/Go
How http.Get in Go allows internal network traversal, and how to build safe http.Client transports with DialContext.
사무실 배달원에게 일반 상점에서 소포를 찾아오라고 하면서, 사장실 안의 잠긴 금고 주소를 적어주는 상황을 상상해 보세요. 배달원은 사내 출입증을 소지하고 있으므로 경비원을 통과해 금고를 열고 회사 기밀을 넘겨주게 됩니다.
Web Application SecurityCWE-918.CWE-918CWE-918): Standard Common Weakness Enumeration classification for ssrf-go.Defense-in-Depth애플리케이션이 웹훅 전송, 이미지 미리보기 등을 위해 사용자가 제출한 URL을 수신합니다.
공격자가 루프백 주소나 클라우드 메타데이터 URL(예: http://169.254.169.254/latest/meta-data/)을 지정합니다.
서버의 HTTP 클라이언트가 사설 VPC 내부에서 IP 범위 검증 없이 요청을 전송합니다.
내부 메타데이터 서비스가 요청을 신뢰하여 임시 IAM 보안 자격 증명 및 관리자 데이터를 반환합니다.
// VULNERABLE: Default http.Get allows internal network calls
package main
import (
"io"
"net/http"
)
func proxyHandler(w http.ResponseWriter, r *http.Request) {
targetURL := r.URL.Query().Get("url")
// Attacker passes: http://169.254.169.254/latest/meta-data/
resp, err := http.Get(targetURL)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
io.Copy(w, resp.Body)
}
// HARDENED: Custom DialContext checking net.IP.IsPrivate and IsLoopback
package main
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/url"
"time"
)
func isSafeIP(ip net.IP) bool {
return !ip.IsLoopback() &&
!ip.IsPrivate() &&
!ip.IsLinkLocalUnicast() &&
!ip.IsLinkLocalMulticast() &&
!ip.IsUnspecified()
}
func newSafeHTTPClient() *http.Client {
dialer := &net.Dialer{
Timeout: 3 * time.Second,
}
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
// Resolve all IP addresses
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
if err != nil {
return nil, err
}
for _, ip := range ips {
if !isSafeIP(ip) {
return nil, errors.New("SSRF Blocked: connection to private/internal IP rejected")
}
}
// Connect to the first validated IP
targetAddr := net.JoinHostPort(ips[0].String(), port)
return dialer.DialContext(ctx, network, targetAddr)
},
}
return &http.Client{
Transport: transport,
Timeout: 5 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return errors.New("redirects are disabled to prevent SSRF bypass")
},
}
}
func proxyHandler(w http.ResponseWriter, r *http.Request) {
targetURL := r.URL.Query().Get("url")
parsed, err := url.Parse(targetURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
http.Error(w, "Invalid URL scheme", http.StatusBadRequest)
return
}
client := newSafeHTTPClient()
resp, err := client.Get(targetURL)
if err != nil {
http.Error(w, "Request failed: "+err.Error(), http.StatusForbidden)
return
}
defer resp.Body.Close()
io.Copy(w, resp.Body)
}
ip.IsPrivate() && !ip.IsLoopback()을(를) 철저히 검증하십시오.