Documentation
¶
Index ¶
- Constants
- Variables
- func CookiesToString(cookies []*http.Cookie) string
- func Fingerprint(c *x509.Certificate) string
- func GetCookiesMap(cookies []*http.Cookie) map[string]string
- func GetLastChromeVersion() *tls.ClientHelloSpec
- func GetLastIosVersion() *tls.ClientHelloSpec
- func ReadSetCookies(h http.Header) []*http.Cookie
- func RedirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)
- func RefererForURL(lastReq, newReq *url.URL) string
- func ToBytes(b any) []byte
- func UrlEncode(obj any) string
- type Conn
- type ConnPool
- type ContextKeyHeader
- type HeaderOrder
- type OrderedHeaders
- func (oh *OrderedHeaders) Add(field string, value ...string)
- func (oh *OrderedHeaders) Clone() OrderedHeaders
- func (oh *OrderedHeaders) Del(field string) OrderedHeaders
- func (oh *OrderedHeaders) Get(field string) string
- func (oh *OrderedHeaders) Remove(field string) OrderedHeaders
- func (oh *OrderedHeaders) Set(field string, value ...string)
- type PHeader
- type PinManager
- type Request
- type Response
- type Session
- func (s *Session) AddPins(u *url.URL, pins []string) error
- func (s *Session) ApplyHTTP2(fp string) error
- func (s *Session) ApplyJa3(ja3, navigator string) error
- func (s *Session) ApplyJa3WithSpecifications(ja3 string, specifications TlsSpecifications, navigator string) error
- func (s *Session) ClearPins(u *url.URL) error
- func (s *Session) ClearProxy()
- func (s *Session) Close()
- func (s *Session) Connect(u string) error
- func (s *Session) Delete(url string, args ...any) (*Response, error)
- func (s *Session) DisableDump()
- func (s *Session) DisableLog()
- func (s *Session) Do(request *Request, args ...any) (*Response, error)
- func (s *Session) Dump(dir string, uris ...string) error
- func (s *Session) DumpAndLog(dir string, uris ...string) error
- func (s *Session) DumpIgnore(uri string) bool
- func (s *Session) EnableDump()
- func (s *Session) EnableLog()
- func (s *Session) EnableVerbose(path string, ignoreHost []string) errordeprecated
- func (s *Session) Get(url string, args ...any) (*Response, error)
- func (s *Session) Head(url string, args ...any) (*Response, error)
- func (s *Session) Ip() (ip string, err error)
- func (s *Session) Log(ignore ...string)
- func (s *Session) NewWebsocket(req *Request, args ...any) (*Websocket, error)
- func (s *Session) NewWebsocketWithContext(ctx context.Context, req *Request, args ...any) (*Websocket, error)
- func (s *Session) Options(url string, args ...any) (*Response, error)
- func (s *Session) Patch(url string, data any, args ...any) (*Response, error)
- func (s *Session) Post(url string, data any, args ...any) (*Response, error)
- func (s *Session) Put(url string, data any, args ...any) (*Response, error)
- func (s *Session) SetContext(ctx context.Context)
- func (s *Session) SetProxy(proxy string) error
- func (s *Session) SetTimeout(timeout time.Duration)
- type TlsSpecifications
- type Websocket
Examples ¶
Constants ¶
const ( Chrome = "chrome" Firefox = "firefox" Opera = "opera" Safari = "safari" Edge = "edge" Ios = "ios" Android = "android" //deprecated )
const ( Path = ":path" Method = ":method" Authority = ":authority" Scheme = ":scheme" )
const ( SchemeHttp = "http" SchemeHttps = "https" SchemeWs = "ws" SchemeWss = "wss" Socks5 = "socks5" Socks5H = "socks5h" )
Variables ¶
var (
ErrNilRequest = errors.New("request is nil")
)
Functions ¶
func CookiesToString ¶ added in v1.2.5
func Fingerprint ¶ added in v1.2.0
func Fingerprint(c *x509.Certificate) string
Fingerprint computes the SHA256 Fingerprint of a given certificate's RawSubjectPublicKeyInfo. This is useful for obtaining a consistent identifier for a certificate's public key. The result is then base64-encoded to give a string representation which can be conveniently stored or compared.
func GetLastChromeVersion ¶
func GetLastChromeVersion() *tls.ClientHelloSpec
GetLastChromeVersion apply the latest Chrome version Current Chrome version : 121
func GetLastIosVersion ¶
func GetLastIosVersion() *tls.ClientHelloSpec
func RedirectBehavior ¶ added in v1.2.5
func RedirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)
RedirectBehavior describes what should happen when the client encounters a 3xx status code from the server
func RefererForURL ¶ added in v1.2.5
RefererForURL returns a referer without any authentication info or an empty string if lastReq scheme is https and newReq scheme is http.
func ToBytes ¶ added in v1.2.5
ToBytes converts any type to []byte, it supports string, []byte, io.Reader, strings.Builder and any other type that can be marshaled to json
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
fmt.Println(string(azuretls.ToBytes("test1")))
fmt.Println(string(azuretls.ToBytes([]byte("test2"))))
buf := bytes.NewBufferString("test3")
fmt.Println(string(azuretls.ToBytes(buf)))
type s struct {
A string
B int
}
fmt.Println(string(azuretls.ToBytes(s{"test4", 4})))
}
Output: test1 test2 test3 {"A":"test4","B":4}
func UrlEncode ¶ added in v1.2.3
UrlEncode encodes a map[string]string to url encoded string If you want to encode a struct, you will use the `url` tag
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
var food = map[string]string{
"an": "url encoded map",
"i": "am",
}
fmt.Println(azuretls.UrlEncode(food))
type Foo struct {
Bar string `url:"bar"`
Baz string `url:"baz"`
Omit string `url:"-"`
OmitEmpty string `url:"no,omitempty"`
}
fmt.Println(azuretls.UrlEncode(Foo{
Bar: "bar",
Baz: "baz baz baz",
Omit: "omit",
OmitEmpty: "",
}))
}
Output: an=url+encoded+map&i=am bar=bar&baz=baz+baz+baz
Types ¶
type Conn ¶ added in v1.1.3
type Conn struct {
TLS *tls.UConn // tls connection
HTTP2 *http2.ClientConn // http2 connection
Conn net.Conn // Tcp connection
Proto string // http protocol
PinManager *PinManager // pin manager
TimeOut time.Duration
InsecureSkipVerify bool
ClientHelloSpec func() *tls.ClientHelloSpec
// contains filtered or unexported fields
}
func NewConnWithContext ¶ added in v1.2.0
func (*Conn) GetContext ¶ added in v1.2.5
func (*Conn) SetContext ¶ added in v1.1.3
type ConnPool ¶ added in v1.1.3
type ConnPool struct {
// contains filtered or unexported fields
}
func NewRequestConnPool ¶ added in v1.1.0
NewRequestConnPool creates a new connection pool
func (*ConnPool) Close ¶ added in v1.1.3
func (cp *ConnPool) Close()
Close closes all connections in the pool
func (*ConnPool) SetContext ¶ added in v1.1.3
SetContext sets the given context for the pool
type ContextKeyHeader ¶
type ContextKeyHeader struct{}
type OrderedHeaders ¶
type OrderedHeaders [][]string
OrderedHeaders is a slice of headers.
func (*OrderedHeaders) Add ¶
func (oh *OrderedHeaders) Add(field string, value ...string)
Add adds the value to the field. It appends to any existing values associated with the field.
func (*OrderedHeaders) Clone ¶
func (oh *OrderedHeaders) Clone() OrderedHeaders
Clone returns a copy of the header.
func (*OrderedHeaders) Del ¶
func (oh *OrderedHeaders) Del(field string) OrderedHeaders
Del removes the first instance of the field from the header. If the field is not present, it does nothing.
func (*OrderedHeaders) Get ¶
func (oh *OrderedHeaders) Get(field string) string
Get returns the first value associated with the given field. If the field is not present, it returns an empty string.
func (*OrderedHeaders) Remove ¶
func (oh *OrderedHeaders) Remove(field string) OrderedHeaders
Remove removes the first instance of the field from the header. If the field is not present, it does nothing. Deprecated: Use Del instead.
func (*OrderedHeaders) Set ¶
func (oh *OrderedHeaders) Set(field string, value ...string)
Set sets the field to the given value. It replaces any existing values associated with the field.
type PHeader ¶
type PHeader []string
PHeader is a slice of pseudo headers.
func GetDefaultPseudoHeaders ¶ added in v1.2.9
func GetDefaultPseudoHeaders() PHeader
GetDefaultPseudoHeaders returns the default pseudo headers.
type PinManager ¶ added in v1.1.0
type PinManager struct {
// contains filtered or unexported fields
}
PinManager is a concurrency-safe struct designed to manage and verify public key pinning for SSL/TLS certificates. Public key pinning is a security feature which can be used to specify a set of valid public keys for a particular web service, thus preventing man-in-the-middle attacks due to rogue certificates.
func NewPinManager ¶ added in v1.1.0
func NewPinManager() *PinManager
NewPinManager initializes a new instance of PinManager with an empty set of pins. This is the entry point to begin using the pinning functionality.
func (*PinManager) AddPin ¶ added in v1.1.0
func (p *PinManager) AddPin(pin string)
AddPin safely adds a new pin (Fingerprint) to the PinManager. If a service's certificate changes (e.g., due to renewal), new pins should be added to continue trusting the service.
func (*PinManager) GetPins ¶ added in v1.2.5
func (p *PinManager) GetPins() []string
func (*PinManager) New ¶ added in v1.1.0
func (p *PinManager) New(addr string) (err error)
New establishes a connection to the provided address, retrieves its SSL/TLS certificates, and pins their public keys in the PinManager. This can be used initially to populate the PinManager with pins from a trusted service.
func (*PinManager) Verify ¶ added in v1.1.0
func (p *PinManager) Verify(c *x509.Certificate) bool
Verify checks whether a given certificate's public key is currently pinned in the PinManager. This method should be used during the SSL/TLS handshake to ensure the remote service's certificate matches a previously pinned public key.
type Request ¶
type Request struct {
HttpRequest *http.Request
Response *Response
Method string // HTTP method, e.g., GET, POST.
Url string
Body any
PHeader PHeader
OrderedHeaders OrderedHeaders
Header http.Header // Headers for the request. Deprecated: Use OrderedHeaders instead.
HeaderOrder HeaderOrder // Order of headers for the request.
DisableRedirects bool // If true, redirects won't be followed.
MaxRedirects uint // Maximum number of redirects to follow.
NoCookie bool // If true, cookies won't be included in the request.
TimeOut time.Duration // Maximum time to wait for request to complete.
IsRedirected bool // Indicates if the current request is a result of a redirection.
InsecureSkipVerify bool // If true, server's certificate is not verified.
IgnoreBody bool // If true, the body of the response is not read.
Proto string
ContentLength int64 // Length of content in the request.
// contains filtered or unexported fields
}
Request represents the details and configuration for an individual HTTP(S) request. It encompasses URL, headers, method, body, proxy settings, timeouts, and other configurations necessary for customizing the request and its execution.
func (*Request) SetContext ¶
type Response ¶
type Response struct {
StatusCode int // HTTP status code, e.g., 200, 404.
Body []byte // Byte representation of the response body.
RawBody io.ReadCloser // Raw body stream.
Header http.Header // Response headers.
Cookies map[string]string // Parsed cookies from the response.
Url string // URL from which the response was received.
IgnoreBody bool // Indicates if the body of the response was ignored.
HttpResponse *http.Response // The underlying HTTP response.
Request *Request // Reference to the associated request.
ContentLength int64 // Length of content in the response.
}
Response encapsulates the received data and metadata from an HTTP(S) request. This includes status code, body, headers, cookies, associated request details, TLS connection state, etc.
type Session ¶
type Session struct {
PHeader PHeader
OrderedHeaders OrderedHeaders
Header http.Header // Default headers for all requests. Deprecated: Use OrderedHeaders instead.
HeaderOrder HeaderOrder // Order of headers for all requests.
CookieJar *cookiejar.Jar // Stores cookies across session requests.
Browser string // Name or identifier of the browser used in the session.
Connections *ConnPool // Pool of persistent connections to manage concurrent requests.
HTTP2Transport *http2.Transport
Transport *http.Transport
GetClientHelloSpec func() *tls.ClientHelloSpec // Function to provide custom TLS handshake details.
Proxy string // Proxy address.
H2Proxy bool // If true, use HTTP2 for proxy connections.
ProxyDialer *proxyDialer
Verbose bool // If true, print detailed logs or debugging information. Deprecated: Use Dump instead.
VerbosePath string // Path for logging verbose information. Deprecated: Use Log instead.
VerboseIgnoreHost []string // List of hosts to ignore when logging verbose info. Deprecated: Use Log instead.
VerboseFunc func(request *Request, response *Response, err error) // Custom function to handle verbose logging. Deprecated: Use Log instead.
MaxRedirects uint // Maximum number of redirects to follow.
TimeOut time.Duration // Maximum time to wait for request to complete.
PreHook func(request *Request) error // Function called before sending request.
Callback func(request *Request, response *Response, err error) // Function called after receiving a response.
// Deprecated: This field is ignored as pin verification is always true.
// To disable pin verification, use InsecureSkipVerify.
VerifyPins bool
InsecureSkipVerify bool // If true, server's certificate is not verified (insecure: this may facilitate attack from middleman).
UserAgent string // Headers for User-Agent and Sec-Ch-Ua, respectively.
// contains filtered or unexported fields
}
Session represents the core structure for managing and conducting HTTP(S) sessions. It holds configuration settings, headers, cookie storage, connection pool, and other attributes necessary to perform and customize requests.
func NewSession ¶
func NewSession() *Session
NewSession creates a new session It is a shortcut for NewSessionWithContext(context.Background())
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
resp, err := session.Get("https://www.google.com")
if err != nil {
panic(err)
}
fmt.Println(resp.StatusCode)
}
Output: 200
func NewSessionWithContext ¶
NewSessionWithContext creates a new session with context It is recommended to use this function to create a new session instead of creating a new Session struct
func (*Session) AddPins ¶ added in v1.1.0
AddPins associates a set of certificate pins with a given URL within a session. This allows for URL-specific pinning, useful in scenarios where different services (URLs) are trusted with different certificates.
func (*Session) ApplyHTTP2 ¶
ApplyHTTP2 applies HTTP2 settings to the session from a fingerprint. The fingerprint is in the format:
<SETTINGS>|<WINDOW_UPDATE>|<PRIORITY>|<PSEUDO_HEADER>
egs :
1:65536,2:0,3:1000,4:6291456,6:262144|15663105|0|m,s,a,p
Any 0 value will be ignored.
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
"strings"
)
func main() {
session := azuretls.NewSession()
preset := "1:65536,2:0,3:1000,4:6291456,6:262144|15663105|0|m,s,a,p"
if err := session.ApplyHTTP2(preset); err != nil {
panic(err)
}
resp, err := session.Get("https://tls.peet.ws/api/all")
if err != nil {
panic(err)
}
fmt.Println(strings.Contains(string(resp.Body), preset))
}
Output: true
func (*Session) ApplyJa3 ¶
ApplyJa3 applies JA3 settings to the session from a fingerprint. JA3 is a method for creating fingerprints from SSL/TLS client hellos, which can be used for client identification or detection. The fingerprint is constructed from an MD5 hash of string representations of various handshake parameters, specifically:
<SSL Version>|<Accepted Ciphers>|<List of Extensions>|<Elliptic Curves>|<Elliptic Curve Formats>
e.g.,
769,4865-4866-4867-49196-49195-52393-49200-49199-49172...|0-5-10-11-...|23-24-25|0
This string is then MD5-hashed to produce a 32-character representation, which is the JA3 fingerprint.
Any absent field in the client hello will raise an error.
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
"strings"
)
func main() {
session := azuretls.NewSession()
ja3 := "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,45-13-43-0-16-65281-51-18-11-27-35-23-10-5-17513-21,29-23-24,0"
if err := session.ApplyJa3(ja3, azuretls.Chrome); err != nil {
panic(err)
}
resp, err := session.Get("https://tls.peet.ws/api/all")
if err != nil {
panic(err)
}
fmt.Println(strings.Contains(string(resp.Body), ja3))
}
Output: true
func (*Session) ApplyJa3WithSpecifications ¶
func (s *Session) ApplyJa3WithSpecifications(ja3 string, specifications TlsSpecifications, navigator string) error
ApplyJa3WithSpecifications applies JA3 settings to the session from a fingerprint. JA3 is a method for creating fingerprints from SSL/TLS client hellos, which can be used for client identification or detection. The fingerprint is constructed from an MD5 hash of string representations of various handshake parameters, specifically:
<SSL Version>|<Accepted Ciphers>|<List of Extensions>|<Elliptic Curves>|<Elliptic Curve Formats>
e.g.,
769,4865-4866-4867-49196-49195-52393-49200-49199-49172...|0-5-10-11-...|23-24-25|0
This string is then MD5-hashed to produce a 32-character representation, which is the JA3 fingerprint.
Any absent field in the client hello will raise an error.
func (*Session) ClearPins ¶ added in v1.1.0
ClearPins removes all pinned certificates associated with a specific URL in the session. This can be used to reset trust settings or in scenarios where a service's certificate is no longer deemed trustworthy.
func (*Session) ClearProxy ¶ added in v1.2.3
func (s *Session) ClearProxy()
ClearProxy removes the proxy from the session
func (*Session) Close ¶
func (s *Session) Close()
Close closes the session and all its connections. It is recommended to call this function when the session is no longer needed.
After calling this function, the session is no longer usable.
func (*Session) Connect ¶ added in v1.2.3
Connect initiates a connection to the specified URL
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
"github.com/Noooste/fhttp/http2"
"net/url"
)
func main() {
session := azuretls.NewSession()
err := session.Connect("https://www.google.com")
if err != nil {
return
}
connection := session.Connections.Get(&url.URL{
Scheme: azuretls.SchemeHttps,
Host: "www.google.com",
})
fmt.Println(connection != nil)
fmt.Println(connection.PinManager.GetPins() != nil)
fmt.Println(connection.TLS.ConnectionState().NegotiatedProtocol == http2.NextProtoTLS)
}
Output: true true true
func (*Session) DisableDump ¶ added in v1.2.9
func (s *Session) DisableDump()
DisableDump will disable requests and responses dumping
func (*Session) DisableLog ¶ added in v1.2.9
func (s *Session) DisableLog()
DisableLog will disable request and response logging
func (*Session) Dump ¶ added in v1.2.9
Dump will activate requests and responses dumping to the specified directory
dir is the directory to save the logs
ignore (optional) is a list of uri to ignore, if ignore is empty, all uri will be logged
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
"os"
"time"
)
func main() {
session := azuretls.NewSession()
session.Dump("./logs", "*.httpbin.org")
session.Get("https://www.google.com", azuretls.OrderedHeaders{
{"User-Agent", "Mozilla/5.0"},
{"Accept", "text/html"},
})
session.Get("https://httpbin.org/get")
time.Sleep(1 * time.Second)
f, _ := os.ReadDir("./logs")
fmt.Println(len(f))
}
Output: 1
func (*Session) DumpAndLog ¶ added in v1.2.9
DumpAndLog will activate requests and responses dumping to the specified directory and log the requests and responses
func (*Session) DumpIgnore ¶ added in v1.2.9
DumpIgnore will check if the given uri is ignored from dumping
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
if err := session.Dump("./logs", "*.google.com"); err != nil {
panic(err)
}
fmt.Println(session.DumpIgnore("https://www.google.com"))
fmt.Println(session.DumpIgnore("https://google.com/search"))
fmt.Println(session.DumpIgnore("https://www.google.com/search"))
if err := session.Dump("./logs", "/get"); err != nil {
panic(err)
}
fmt.Println(session.DumpIgnore("https://www.google.com"))
fmt.Println(session.DumpIgnore("https://google.com/search"))
fmt.Println(session.DumpIgnore("https://www.google.com/get/the/thing"))
}
Output: true true true false false true
func (*Session) EnableDump ¶ added in v1.2.9
func (s *Session) EnableDump()
EnableDump will enable requests and responses dumping
func (*Session) EnableLog ¶ added in v1.2.9
func (s *Session) EnableLog()
EnableLog will enable request and response logging
func (*Session) EnableVerbose
deprecated
func (*Session) Get ¶
Get provides shortcut for sending GET request
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
resp, err := session.Get("https://www.google.com")
if err != nil {
panic(err)
}
fmt.Println(resp.StatusCode)
}
Output: 200
func (*Session) Log ¶ added in v1.2.9
Log will print the request and response to the console
ignore (optional) is a list of uris to ignore, if ignore is empty, all uris will be logged
Example ¶
package main
import (
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
session.Log("/any/path/to/ignore", "can.ignore.this", "*.all.subdomains")
session.Get("https://www.google.com")
}
Output:
func (*Session) NewWebsocket ¶ added in v1.2.1
func (*Session) NewWebsocketWithContext ¶ added in v1.2.1
func (*Session) Post ¶
Post provides shortcut for sending POST request
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
resp, err := session.Post("https://httpbin.org/post", `post me`)
if err != nil {
panic(err)
}
fmt.Println(resp.StatusCode)
fmt.Println(bytes.Contains(resp.Body, []byte("post me")))
}
Output: 200 true
func (*Session) SetContext ¶ added in v1.1.0
SetContext sets the given context for the session
func (*Session) SetProxy ¶
SetProxy sets the proxy for the session
Example ¶
package main
import (
"fmt"
"github.com/Noooste/azuretls-client"
)
func main() {
session := azuretls.NewSession()
err := session.SetProxy("http://username:password@proxy:8080")
if err != nil {
panic(err)
}
fmt.Println(session.Proxy)
}
Output: http://username:password@proxy:8080
func (*Session) SetTimeout ¶
SetTimeout sets timeout for the session
type TlsSpecifications ¶
type TlsSpecifications struct {
AlpnProtocols []string
SignatureAlgorithms []tls.SignatureScheme
SupportedVersions []uint16
CertCompressionAlgos []tls.CertCompressionAlgo
DelegatedCredentialsAlgorithmSignatures []tls.SignatureScheme
PSKKeyExchangeModes []uint8
SignatureAlgorithmsCert []tls.SignatureScheme
ApplicationSettingsProtocols []string
RenegotiationSupport tls.RenegotiationSupport
}
TlsSpecifications struct contains various fields representing TLS handshake settings.
func DefaultTlsSpecifications ¶
func DefaultTlsSpecifications() TlsSpecifications