Compare commits

...
Author SHA1 Message Date
moloch-- fb573bb122 Correctly convert request path 2021-12-23 08:54:39 -06:00
moloch-- f780f70318 Fix various build-time errors 2021-12-23 08:36:36 -06:00
moloch-- 12c6a57362 implemented configurable http drivers per platform 2021-12-23 08:03:48 -06:00
moloch-- afc8ccd61d initial winhttp support 2021-12-23 07:33:53 -06:00
moloch-- 5b3f1eeb7b wip: Initial winhttp support 2021-12-22 16:38:55 -06:00
9 changed files with 1668 additions and 113 deletions

No files matched your search

@@ -0,0 +1,42 @@
//go:build !windows
package httpclient
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
// {{if .Config.Debug}}
"log"
// {{end}}
)
// GetHTTPDriver - Get an instance of the specified HTTP driver
func GetHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
switch opts.Driver {
case goHTTPDriver:
return GoHTTPDriver(origin, secure, opts)
default:
// {{if .Config.Debug}}
log.Printf("WARNING: unknown HTTP driver: %s", opts.Driver)
// {{end}}
return GoHTTPDriver(origin, secure, opts)
}
}
@@ -0,0 +1,67 @@
package httpclient
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"net/url"
// {{if .Config.Debug}}
"log"
// {{end}}
"github.com/bishopfox/sliver/implant/sliver/transports/httpclient/winhttp"
)
// GetHTTPDriver - Get an instance of the specified HTTP driver
func GetHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
switch opts.Driver {
case goHTTPDriver:
// {{if .Config.Debug}}
log.Printf("Using go http driver")
// {{end}}
return GoHTTPDriver(origin, secure, opts)
case winHTTPDriver:
// {{if .Config.Debug}}
log.Printf("Using winhttp driver")
// {{end}}
return WinHTTPDriver(origin, secure, opts)
default:
// {{if .Config.Debug}}
log.Printf("WARNING: unknown HTTP driver: %s", opts.Driver)
// {{end}}
return GoHTTPDriver(origin, secure, opts)
}
}
// WinHTTPDriver - Initialize a WinHTTP driver (Windows only)
func WinHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
port := uint16(80)
if secure {
port = uint16(80)
}
c2URL, err := url.Parse(origin)
if err != nil {
return nil, err
}
driver := winhttp.NewWinHTTPClient(c2URL.Host, port)
return driver, nil
}
@@ -0,0 +1,134 @@
package httpclient
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"sync"
// {{if .Config.Debug}}
"log"
// {{end}}
"github.com/bishopfox/sliver/implant/sliver/proxy"
)
// GoHTTPDriver - Pure Go HTTP driver
func GoHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
var transport *http.Transport
if !secure {
transport = &http.Transport{
Dial: proxy.Direct.Dial,
TLSHandshakeTimeout: opts.TlsTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
}
} else {
transport = &http.Transport{
Dial: (&net.Dialer{
Timeout: opts.NetTimeout,
}).Dial,
TLSHandshakeTimeout: opts.TlsTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
}
}
client := &http.Client{
Jar: cookieJar(),
Timeout: opts.NetTimeout,
Transport: transport,
}
parseProxyConfig(origin, transport, opts.ProxyConfig)
return client, nil
}
func parseProxyConfig(origin string, transport *http.Transport, proxyConfig string) {
switch proxyConfig {
case "never":
break
case "":
fallthrough
case "auto":
p := proxy.NewProvider("").GetHTTPSProxy(origin)
if p != nil {
// {{if .Config.Debug}}
log.Printf("Found proxy %#v\n", p)
// {{end}}
proxyURL := p.URL()
if proxyURL.Scheme == "" {
proxyURL.Scheme = "https"
}
// {{if .Config.Debug}}
log.Printf("Proxy URL = '%s'\n", proxyURL)
// {{end}}
transport.Proxy = http.ProxyURL(proxyURL)
}
default:
// {{if .Config.Debug}}
log.Printf("Force proxy %#v\n", proxyConfig)
// {{end}}
proxyURL, err := url.Parse(proxyConfig)
if err != nil {
break
}
if proxyURL.Scheme == "" {
proxyURL.Scheme = "https"
}
// {{if .Config.Debug}}
log.Printf("Proxy URL = '%s'\n", proxyURL)
// {{end}}
transport.Proxy = http.ProxyURL(proxyURL)
}
}
// Jar - CookieJar implementation that ignores domains/origins
type Jar struct {
lk sync.Mutex
cookies []*http.Cookie
}
func cookieJar() *Jar {
return &Jar{
lk: sync.Mutex{},
cookies: []*http.Cookie{},
}
}
// NewJar - Get a new instance of a cookie jar
func NewJar() *Jar {
jar := new(Jar)
jar.cookies = make([]*http.Cookie, 0)
return jar
}
// SetCookies handles the receipt of the cookies in a reply for the
// given URL (which is ignored).
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.lk.Lock()
jar.cookies = append(jar.cookies, cookies...)
jar.lk.Unlock()
}
// Cookies returns the cookies to send in a request for the given URL.
// It is up to the implementation to honor the standard cookie use
// restrictions such as in RFC 6265 (which we do not).
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
return jar.cookies
}
@@ -23,13 +23,11 @@ package httpclient
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
insecureRand "math/rand"
"net"
"net/http"
"net/url"
"strconv"
@@ -44,12 +42,14 @@ import (
"github.com/bishopfox/sliver/implant/sliver/cryptography"
"github.com/bishopfox/sliver/implant/sliver/encoders"
"github.com/bishopfox/sliver/implant/sliver/proxy"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
"google.golang.org/protobuf/proto"
)
const (
goHTTPDriver = "go"
winHTTPDriver = "winhttp"
userAgent = "{{GenerateUserAgent}}"
nonceQueryArgs = "abcdefghijklmnopqrstuvwxyz_"
acceptHeaderValue = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
@@ -62,6 +62,7 @@ var (
// HTTPOptions - c2 specific configuration options
type HTTPOptions struct {
Driver string
NetTimeout time.Duration
TlsTimeout time.Duration
PollTimeout time.Duration
@@ -90,7 +91,13 @@ func ParseHTTPOptions(c2URI *url.URL) *HTTPOptions {
if err != nil || maxErrors < 0 {
maxErrors = 10
}
driverName := strings.TrimSpace(strings.ToLower(c2URI.Query().Get("driver")))
if driverName == "" {
driverName = goHTTPDriver
}
return &HTTPOptions{
Driver: driverName,
NetTimeout: netTimeout,
TlsTimeout: tlsTimeout,
PollTimeout: pollTimeout,
@@ -105,7 +112,7 @@ func ParseHTTPOptions(c2URI *url.URL) *HTTPOptions {
// HTTPStartSession - Attempts to start a session with a given address
func HTTPStartSession(address string, pathPrefix string, opts *HTTPOptions) (*SliverHTTPClient, error) {
var client *SliverHTTPClient
client = httpsClient(address, opts.NetTimeout, opts.TlsTimeout, opts.ProxyConfig)
client = httpsClient(address, opts)
client.pollTimeout = opts.PollTimeout
client.PathPrefix = pathPrefix
err := client.SessionInit()
@@ -114,7 +121,7 @@ func HTTPStartSession(address string, pathPrefix string, opts *HTTPOptions) (*Sl
if strings.HasSuffix(address, ":443") {
address = fmt.Sprintf("%s:80", address[:len(address)-4])
}
client = httpClient(address, opts.NetTimeout, opts.TlsTimeout, opts.ProxyConfig) // Fallback to insecure HTTP
client = httpClient(address, opts) // Fallback to insecure HTTP
err = client.SessionInit()
if err != nil {
return nil, err
@@ -123,11 +130,16 @@ func HTTPStartSession(address string, pathPrefix string, opts *HTTPOptions) (*Sl
return client, nil
}
// HTTPDriver - The interface to send/recv HTTP data
type HTTPDriver interface {
Do(req *http.Request) (*http.Response, error)
}
// SliverHTTPClient - Helper struct to keep everything together
type SliverHTTPClient struct {
Origin string
PathPrefix string
Client *http.Client
driver HTTPDriver
ProxyURL string
SessionCtx *cryptography.CipherContext
SessionID string
@@ -223,7 +235,7 @@ func (s *SliverHTTPClient) DoPoll(req *http.Request) (*http.Response, []byte, er
var data []byte
var err error
go func() {
resp, err = s.Client.Do(req.WithContext(ctx))
resp, err = s.driver.Do(req.WithContext(ctx))
select {
case <-ctx.Done():
done <- ctx.Err()
@@ -264,7 +276,7 @@ func (s *SliverHTTPClient) establishSessionID(sessionInit []byte) error {
log.Printf("[http] POST -> %s (%d bytes)", uri, len(sessionInit))
// {{end}}
resp, err := s.Client.Do(req)
resp, err := s.driver.Do(req)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[http] http response error: %s", err)
@@ -399,7 +411,7 @@ func (s *SliverHTTPClient) WriteEnvelope(envelope *pb.Envelope) error {
// {{end}}
req := s.newHTTPRequest(http.MethodPost, uri, reader)
resp, err := s.Client.Do(req)
resp, err := s.driver.Do(req)
// {{if .Config.Debug}}
log.Printf("[http] POST request completed")
// {{end}}
@@ -443,7 +455,7 @@ func (s *SliverHTTPClient) CloseSession() error {
// {{if .Config.Debug}}
log.Printf("[http] GET -> %s", uri)
// {{end}}
resp, err := s.Client.Do(req)
resp, err := s.driver.Do(req)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[http] GET failed %v", err)
@@ -553,122 +565,40 @@ func (s *SliverHTTPClient) randomPath(segments []string, filenames []string, ext
// [ HTTP(S) Clients ] ------------------------------------------------------------
func httpClient(address string, netTimeout time.Duration, tlsTimeout time.Duration, proxyConfig string) *SliverHTTPClient {
transport := &http.Transport{
Dial: proxy.Direct.Dial,
TLSHandshakeTimeout: tlsTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
func httpClient(address string, opts *HTTPOptions) *SliverHTTPClient {
origin := fmt.Sprintf("http://%s", address)
driver, err := GetHTTPDriver(origin, false, opts)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[http] failed to initialize driver: %v", err)
// {{end}}
return nil
}
client := &SliverHTTPClient{
Origin: fmt.Sprintf("http://%s", address),
Client: &http.Client{
Jar: cookieJar(),
Timeout: netTimeout,
Transport: transport,
},
Origin: origin,
driver: driver,
pollMutex: &sync.Mutex{},
Closed: false,
}
parseProxyConfig(client, transport, proxyConfig)
return client
}
func httpsClient(address string, netTimeout time.Duration, tlsTimeout time.Duration, proxyConfig string) *SliverHTTPClient {
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: netTimeout,
}).Dial,
TLSHandshakeTimeout: tlsTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
func httpsClient(address string, opts *HTTPOptions) *SliverHTTPClient {
origin := fmt.Sprintf("https://%s", address)
driver, err := GetHTTPDriver(origin, true, opts)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[http] failed to initialize driver: %v", err)
// {{end}}
return nil
}
client := &SliverHTTPClient{
Origin: fmt.Sprintf("https://%s", address),
Client: &http.Client{
Jar: cookieJar(),
Timeout: netTimeout,
Transport: transport,
},
Origin: origin,
driver: driver,
pollMutex: &sync.Mutex{},
Closed: false,
}
parseProxyConfig(client, transport, proxyConfig)
return client
}
func parseProxyConfig(client *SliverHTTPClient, transport *http.Transport, proxyConfig string) {
switch proxyConfig {
case "never":
break
case "":
fallthrough
case "auto":
p := proxy.NewProvider("").GetHTTPSProxy(client.Origin)
if p != nil {
// {{if .Config.Debug}}
log.Printf("Found proxy %#v\n", p)
// {{end}}
proxyURL := p.URL()
if proxyURL.Scheme == "" {
proxyURL.Scheme = "https"
}
// {{if .Config.Debug}}
log.Printf("Proxy URL = '%s'\n", proxyURL)
// {{end}}
transport.Proxy = http.ProxyURL(proxyURL)
client.ProxyURL = proxyURL.String()
}
default:
// {{if .Config.Debug}}
log.Printf("Force proxy %#v\n", proxyConfig)
// {{end}}
proxyURL, err := url.Parse(proxyConfig)
if err != nil {
break
}
if proxyURL.Scheme == "" {
proxyURL.Scheme = "https"
}
// {{if .Config.Debug}}
log.Printf("Proxy URL = '%s'\n", proxyURL)
// {{end}}
transport.Proxy = http.ProxyURL(proxyURL)
client.ProxyURL = proxyURL.String()
}
}
// Jar - CookieJar implementation that ignores domains/origins
type Jar struct {
lk sync.Mutex
cookies []*http.Cookie
}
func cookieJar() *Jar {
return &Jar{
lk: sync.Mutex{},
cookies: []*http.Cookie{},
}
}
// NewJar - Get a new instance of a cookie jar
func NewJar() *Jar {
jar := new(Jar)
jar.cookies = make([]*http.Cookie, 0)
return jar
}
// SetCookies handles the receipt of the cookies in a reply for the
// given URL (which is ignored).
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.lk.Lock()
jar.cookies = append(jar.cookies, cookies...)
jar.lk.Unlock()
}
// Cookies returns the cookies to send in a request for the given URL.
// It is up to the implementation to honor the standard cookie use
// restrictions such as in RFC 6265 (which we do not).
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
return jar.cookies
}
// {{end}} -HTTPc2Enabled
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
@@ -0,0 +1,222 @@
//go:build windows
package winhttp
/*
Sliver Implant Framework
Copyright (C) 2021 Bishop Fox
This program 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"syscall"
"unsafe"
// {{if .Config.Debug}}
"log"
// {{end}}
)
// NewWinHTTPClient - Init a new WinHTTPClient
func NewWinHTTPClient(hostname string, port uint16) *WinHTTPClient {
return &WinHTTPClient{
hostname: hostname,
port: port,
}
}
// WinHTTPClient - A WinHTTP driver
type WinHTTPClient struct {
port uint16
hostname string
hSession HInternet
referrer string
acceptTypes []string
}
// Do - Execute an HTTP request
func (w *WinHTTPClient) Do(req *http.Request) (*http.Response, error) {
var err error
if w.hSession == 0 {
// {{if .Config.Debug}}
log.Printf("[winhttp] starting new session ...")
// {{end}}
w.hSession, err = Open(
req.Header.Get("User-Agent"),
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
"",
"",
0,
)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] open failed: %s", err)
// {{end}}
return nil, err
}
}
hConnect, err := Connect(w.hSession, w.hostname, int(w.port))
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] connect failed: %s", err)
// {{end}}
return nil, err
}
openReqFlags := uint32(0)
reqPath := fmt.Sprintf("%s?%s", req.URL.Path, req.URL.RawQuery)
// {{if .Config.Debug}}
log.Printf("[winhttp] req -> %s", reqPath)
// {{end}}
hRequest, err := OpenRequest(hConnect, req.Method, reqPath, "", w.referrer, w.acceptTypes, openReqFlags)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] open request failed: %s", err)
// {{end}}
return nil, err
}
dwFlags := uint32(SECURITY_FLAG_IGNORE_UNKNOWN_CA)
err = SetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, uintptr(unsafe.Pointer(&dwFlags)), unsafe.Sizeof(dwFlags))
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] set option failed: %s", err)
// {{end}}
return nil, err
}
sendReqContext := uint32(0)
if req.Body != nil {
var body []byte
body, err = io.ReadAll(req.Body)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] io read body failed: %s", err)
// {{end}}
return nil, err
}
err = SendRequest(hRequest, "", &body[0], len(body), len(body), &sendReqContext)
} else {
err = SendRequest(hRequest, "", nil, 0, 0, &sendReqContext)
}
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] send request failed: %s", err)
// {{end}}
return nil, err
}
err = ReceiveResponse(hRequest)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] recv response failed: %s", err)
// {{end}}
return nil, err
}
utf16StatusCode := make([]uint16, 16)
statusCodeSize := uint32(unsafe.Sizeof(uint16(0)) * 16)
err = QueryHeaders(
hRequest,
WINHTTP_QUERY_STATUS_CODE,
"",
&utf16StatusCode[0],
&statusCodeSize,
nil,
)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] query headers failed: %s", err)
// {{end}}
return nil, err
}
statusCode, err := strconv.Atoi(syscall.UTF16ToString(utf16StatusCode[:]))
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] failed to parse utf16 status code: %s", err)
// {{end}}
return nil, err
}
utf16Status := make([]uint16, 16)
statusSize := uint32(unsafe.Sizeof(uint16(0)) * 16)
err = QueryHeaders(
hRequest,
WINHTTP_QUERY_STATUS_TEXT,
"",
&utf16Status[0],
&statusSize,
nil,
)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[winhttp] query headers failed: %s", err)
// {{end}}
return nil, err
}
status := syscall.UTF16ToString(utf16Status[:])
// {{if .Config.Debug}}
log.Printf("[winhttp] status code: %d", statusCode)
// {{end}}
var dataSize uint
dataSize, err = QueryDataAvailable(hRequest)
if err != nil {
return nil, err
}
// {{if .Config.Debug}}
log.Printf("[winhttp] data size: %v", dataSize)
// {{end}}
dataBuf := make([]byte, dataSize)
var bytesRead int
bytesRead, err = ReadData(
hRequest,
dataBuf,
)
if err != nil {
return nil, err
}
// {{if .Config.Debug}}
log.Printf("[winhttp] bytesRead: %v", bytesRead)
log.Printf("[winhttp] data: %v\n", string(dataBuf))
// {{else}}
bytesRead++
bytesRead--
// {{end}}
resp := &http.Response{
Status: status,
StatusCode: statusCode,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: ioutil.NopCloser(bytes.NewReader(dataBuf)),
ContentLength: int64(dataSize),
Request: req,
Header: make(http.Header),
}
return resp, nil
}
@@ -0,0 +1,301 @@
//go:build windows
package winhttp
// Implements flags necessary for working with WinHTTP.
import (
"syscall"
)
const (
/* WinHTTP error codes */
WINHTTP_ERROR_BASE = 12000
ERROR_WINHTTP_OUT_OF_HANDLES = syscall.Errno(WINHTTP_ERROR_BASE + 1)
ERROR_WINHTTP_TIMEOUT = syscall.Errno(WINHTTP_ERROR_BASE + 2)
ERROR_WINHTTP_INTERNAL_ERROR = syscall.Errno(WINHTTP_ERROR_BASE + 4)
ERROR_WINHTTP_INVALID_URL = syscall.Errno(WINHTTP_ERROR_BASE + 5)
ERROR_WINHTTP_UNRECOGNIZED_SCHEME = syscall.Errno(WINHTTP_ERROR_BASE + 6)
ERROR_WINHTTP_NAME_NOT_RESOLVED = syscall.Errno(WINHTTP_ERROR_BASE + 7)
ERROR_WINHTTP_INVALID_OPTION = syscall.Errno(WINHTTP_ERROR_BASE + 9)
ERROR_WINHTTP_OPTION_NOT_SETTABLE = syscall.Errno(WINHTTP_ERROR_BASE + 11)
ERROR_WINHTTP_SHUTDOWN = syscall.Errno(WINHTTP_ERROR_BASE + 12)
ERROR_WINHTTP_LOGIN_FAILURE = syscall.Errno(WINHTTP_ERROR_BASE + 15)
ERROR_WINHTTP_OPERATION_CANCELLED = syscall.Errno(WINHTTP_ERROR_BASE + 17)
ERROR_WINHTTP_INCORRECT_HANDLE_TYPE = syscall.Errno(WINHTTP_ERROR_BASE + 18)
ERROR_WINHTTP_INCORRECT_HANDLE_STATE = syscall.Errno(WINHTTP_ERROR_BASE + 19)
ERROR_WINHTTP_CANNOT_CONNECT = syscall.Errno(WINHTTP_ERROR_BASE + 29)
ERROR_WINHTTP_CONNECTION_ERROR = syscall.Errno(WINHTTP_ERROR_BASE + 30)
ERROR_WINHTTP_RESEND_REQUEST = syscall.Errno(WINHTTP_ERROR_BASE + 32)
ERROR_WINHTTP_SECURE_CERT_DATE_INVALID = syscall.Errno(WINHTTP_ERROR_BASE + 37)
ERROR_WINHTTP_SECURE_CERT_CN_INVALID = syscall.Errno(WINHTTP_ERROR_BASE + 38)
ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = syscall.Errno(WINHTTP_ERROR_BASE + 44)
ERROR_WINHTTP_SECURE_INVALID_CA = syscall.Errno(WINHTTP_ERROR_BASE + 45)
ERROR_WINHTTP_SECURE_CERT_REV_FAILED = syscall.Errno(WINHTTP_ERROR_BASE + 57)
ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN = syscall.Errno(WINHTTP_ERROR_BASE + 100)
ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND = syscall.Errno(WINHTTP_ERROR_BASE + 101)
ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND = syscall.Errno(WINHTTP_ERROR_BASE + 102)
ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN = syscall.Errno(WINHTTP_ERROR_BASE + 103)
ERROR_WINHTTP_HEADER_NOT_FOUND = syscall.Errno(WINHTTP_ERROR_BASE + 150)
ERROR_WINHTTP_INVALID_SERVER_RESPONSE = syscall.Errno(WINHTTP_ERROR_BASE + 152)
ERROR_WINHTTP_INVALID_HEADER = syscall.Errno(WINHTTP_ERROR_BASE + 153)
ERROR_WINHTTP_INVALID_QUERY_REQUEST = syscall.Errno(WINHTTP_ERROR_BASE + 154)
ERROR_WINHTTP_HEADER_ALREADY_EXISTS = syscall.Errno(WINHTTP_ERROR_BASE + 155)
ERROR_WINHTTP_REDIRECT_FAILED = syscall.Errno(WINHTTP_ERROR_BASE + 156)
ERROR_WINHTTP_SECURE_CHANNEL_ERROR = syscall.Errno(WINHTTP_ERROR_BASE + 157)
ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT = syscall.Errno(WINHTTP_ERROR_BASE + 166)
ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = syscall.Errno(WINHTTP_ERROR_BASE + 167)
ERROR_WINHTTP_SECURE_INVALID_CERT = syscall.Errno(WINHTTP_ERROR_BASE + 169)
ERROR_WINHTTP_SECURE_CERT_REVOKED = syscall.Errno(WINHTTP_ERROR_BASE + 170)
ERROR_WINHTTP_NOT_INITIALIZED = syscall.Errno(WINHTTP_ERROR_BASE + 172)
ERROR_WINHTTP_SECURE_FAILURE = syscall.Errno(WINHTTP_ERROR_BASE + 175)
ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR = syscall.Errno(WINHTTP_ERROR_BASE + 178)
ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE = syscall.Errno(WINHTTP_ERROR_BASE + 179)
ERROR_WINHTTP_AUTODETECTION_FAILED = syscall.Errno(WINHTTP_ERROR_BASE + 180)
ERROR_WINHTTP_HEADER_COUNT_EXCEEDED = syscall.Errno(WINHTTP_ERROR_BASE + 181)
ERROR_WINHTTP_HEADER_SIZE_OVERFLOW = syscall.Errno(WINHTTP_ERROR_BASE + 182)
ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW = syscall.Errno(WINHTTP_ERROR_BASE + 183)
ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW = syscall.Errno(WINHTTP_ERROR_BASE + 184)
ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY = syscall.Errno(WINHTTP_ERROR_BASE + 185)
ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY = syscall.Errno(WINHTTP_ERROR_BASE + 186)
WINHTTP_ERROR_LAST = (WINHTTP_ERROR_BASE + 186)
)
const (
SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000
SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = 0x00000200
SECURITY_FLAG_SECURE = 0x00000001
SECURITY_FLAG_STRENGTH_WEAK = 0x10000000
SECURITY_FLAG_STRENGTH_MEDIUM = 0x40000000
SECURITY_FLAG_STRENGTH_STRONG = 0x20000000
)
const (
INTERNET_DEFAULT_PORT = 0
INTERNET_DEFAULT_HTTP_PORT = 80
INTERNET_DEFAULT_HTTPS_PORT = 443
WINHTTP_FLAG_ASYNC = 0x10000000
WINHTTP_FLAG_SECURE = 0x00800000
WINHTTP_FLAG_ESCAPE_PERCENT = 0x00000004
WINHTTP_FLAG_NULL_CODEPAGE = 0x00000008
WINHTTP_FLAG_BYPASS_PROXY_CACHE = 0x00000100
WINHTTP_FLAG_REFRESH = 0x00000100
WINHTTP_FLAG_ESCAPE_DISABLE = 0x00000040
WINHTTP_FLAG_ESCAPE_DISABLE_QUERY = 0x00000080
WINHTTP_AUTOPROXY_AUTO_DETECT = 0x00000001
WINHTTP_AUTOPROXY_CONFIG_URL = 0x00000002
WINHTTP_AUTOPROXY_HOST_KEEPCASE = 0x00000004
WINHTTP_AUTOPROXY_HOST_LOWERCASE = 0x00000008
WINHTTP_AUTOPROXY_RUN_INPROCESS = 0x00010000
WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = 0x00020000
WINHTTP_AUTOPROXY_NO_DIRECTACCESS = 0x00040000
WINHTTP_AUTOPROXY_NO_CACHE_CLIENT = 0x00080000
WINHTTP_AUTOPROXY_NO_CACHE_SVC = 0x00100000
WINHTTP_AUTOPROXY_SORT_RESULTS = 0x00400000
WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001
WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0
WINHTTP_ACCESS_TYPE_NO_PROXY = 1
WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3
WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = 4
WINHTTP_NO_PROXY_NAME = 0
WINHTTP_NO_PROXY_BYPASS = 0
WINHTTP_NO_ADDITIONAL_HEADERS = 0
WINHTTP_NO_REQUEST_DATA = 0
WINHTTP_QUERY_MIME_VERSION = 0
WINHTTP_QUERY_CONTENT_TYPE = 1
WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2
WINHTTP_QUERY_CONTENT_ID = 3
WINHTTP_QUERY_CONTENT_DESCRIPTION = 4
WINHTTP_QUERY_CONTENT_LENGTH = 5
WINHTTP_QUERY_CONTENT_LANGUAGE = 6
WINHTTP_QUERY_ALLOW = 7
WINHTTP_QUERY_PUBLIC = 8
WINHTTP_QUERY_DATE = 9
WINHTTP_QUERY_EXPIRES = 10
WINHTTP_QUERY_LAST_MODIFIED = 11
WINHTTP_QUERY_MESSAGE_ID = 12
WINHTTP_QUERY_URI = 13
WINHTTP_QUERY_DERIVED_FROM = 14
WINHTTP_QUERY_COST = 15
WINHTTP_QUERY_LINK = 16
WINHTTP_QUERY_PRAGMA = 17
WINHTTP_QUERY_VERSION = 18 // special: part of status line
WINHTTP_QUERY_STATUS_CODE = 19 // special: part of status line
WINHTTP_QUERY_STATUS_TEXT = 20 // special: part of status line
WINHTTP_QUERY_RAW_HEADERS = 21 // special: all headers as ASCIIZ
WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 // special: all headers
WINHTTP_QUERY_CONNECTION = 23
WINHTTP_QUERY_ACCEPT = 24
WINHTTP_QUERY_ACCEPT_CHARSET = 25
WINHTTP_QUERY_ACCEPT_ENCODING = 26
WINHTTP_QUERY_ACCEPT_LANGUAGE = 27
WINHTTP_QUERY_AUTHORIZATION = 28
WINHTTP_QUERY_CONTENT_ENCODING = 29
WINHTTP_QUERY_FORWARDED = 30
WINHTTP_QUERY_FROM = 31
WINHTTP_QUERY_IF_MODIFIED_SINCE = 32
WINHTTP_QUERY_LOCATION = 33
WINHTTP_QUERY_ORIG_URI = 34
WINHTTP_QUERY_REFERER = 35
WINHTTP_QUERY_RETRY_AFTER = 36
WINHTTP_QUERY_SERVER = 37
WINHTTP_QUERY_TITLE = 38
WINHTTP_QUERY_USER_AGENT = 39
WINHTTP_QUERY_WWW_AUTHENTICATE = 40
WINHTTP_QUERY_PROXY_AUTHENTICATE = 41
WINHTTP_QUERY_ACCEPT_RANGES = 42
WINHTTP_QUERY_SET_COOKIE = 43
WINHTTP_QUERY_COOKIE = 44
WINHTTP_QUERY_REQUEST_METHOD = 45 // special: GET/POST etc.
WINHTTP_QUERY_REFRESH = 46
WINHTTP_QUERY_CONTENT_DISPOSITION = 47
//
// HTTP 1.1 defined headers
//
WINHTTP_QUERY_AGE = 48
WINHTTP_QUERY_CACHE_CONTROL = 49
WINHTTP_QUERY_CONTENT_BASE = 50
WINHTTP_QUERY_CONTENT_LOCATION = 51
WINHTTP_QUERY_CONTENT_MD5 = 52
WINHTTP_QUERY_CONTENT_RANGE = 53
WINHTTP_QUERY_ETAG = 54
WINHTTP_QUERY_HOST = 55
WINHTTP_QUERY_IF_MATCH = 56
WINHTTP_QUERY_IF_NONE_MATCH = 57
WINHTTP_QUERY_IF_RANGE = 58
WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59
WINHTTP_QUERY_MAX_FORWARDS = 60
WINHTTP_QUERY_PROXY_AUTHORIZATION = 61
WINHTTP_QUERY_RANGE = 62
WINHTTP_QUERY_TRANSFER_ENCODING = 63
WINHTTP_QUERY_UPGRADE = 64
WINHTTP_QUERY_VARY = 65
WINHTTP_QUERY_VIA = 66
WINHTTP_QUERY_WARNING = 67
WINHTTP_QUERY_EXPECT = 68
WINHTTP_QUERY_PROXY_CONNECTION = 69
WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70
WINHTTP_HEADER_NAME_BY_INDEX = ""
WINHTTP_NO_OUTPUT_BUFFER = 0
WINHTTP_NO_HEADER_INDEX = 0
WINHTTP_OPTION_CALLBACK = 1
WINHTTP_OPTION_RESOLVE_TIMEOUT = 2
WINHTTP_OPTION_CONNECT_TIMEOUT = 3
WINHTTP_OPTION_CONNECT_RETRIES = 4
WINHTTP_OPTION_SEND_TIMEOUT = 5
WINHTTP_OPTION_RECEIVE_TIMEOUT = 6
WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT = 7
WINHTTP_OPTION_HANDLE_TYPE = 9
WINHTTP_OPTION_READ_BUFFER_SIZE = 12
WINHTTP_OPTION_WRITE_BUFFER_SIZE = 13
WINHTTP_OPTION_PARENT_HANDLE = 21
WINHTTP_OPTION_EXTENDED_ERROR = 24
WINHTTP_OPTION_SECURITY_FLAGS = 31
WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT = 32
WINHTTP_OPTION_URL = 34
WINHTTP_OPTION_SECURITY_KEY_BITNESS = 36
WINHTTP_OPTION_PROXY = 38
WINHTTP_OPTION_USER_AGENT = 41
WINHTTP_OPTION_CONTEXT_VALUE = 45
WINHTTP_OPTION_CLIENT_CERT_CONTEXT = 47
WINHTTP_OPTION_REQUEST_PRIORITY = 58
WINHTTP_OPTION_HTTP_VERSION = 59
WINHTTP_OPTION_DISABLE_FEATURE = 63
WINHTTP_OPTION_CODEPAGE = 68
WINHTTP_OPTION_MAX_CONNS_PER_SERVER = 73
WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER = 74
WINHTTP_OPTION_AUTOLOGON_POLICY = 77
WINHTTP_OPTION_SERVER_CERT_CONTEXT = 78
WINHTTP_OPTION_ENABLE_FEATURE = 79
WINHTTP_OPTION_WORKER_THREAD_COUNT = 80
WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT = 81
WINHTTP_OPTION_PASSPORT_COBRANDING_URL = 82
WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH = 83
WINHTTP_OPTION_SECURE_PROTOCOLS = 84
WINHTTP_OPTION_ENABLETRACING = 85
WINHTTP_OPTION_PASSPORT_SIGN_OUT = 86
WINHTTP_OPTION_PASSPORT_RETURN_URL = 87
WINHTTP_OPTION_REDIRECT_POLICY = 88
WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS = 89
WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE = 90
WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE = 91
WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE = 92
WINHTTP_OPTION_CONNECTION_INFO = 93
WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST = 94
WINHTTP_OPTION_SPN = 96
WINHTTP_OPTION_GLOBAL_PROXY_CREDS = 97
WINHTTP_OPTION_GLOBAL_SERVER_CREDS = 98
WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT = 99
WINHTTP_OPTION_REJECT_USERPWD_IN_URL = 100
WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS = 101
WINHTTP_LAST_OPTION = WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS
WINHTTP_OPTION_USERNAME = 0x1000
WINHTTP_OPTION_PASSWORD = 0x1001
WINHTTP_OPTION_PROXY_USERNAME = 0x1002
WINHTTP_OPTION_PROXY_PASSWORD = 0x1003
WINHTTP_ADDREQ_INDEX_MASK = 0x0000FFFF
WINHTTP_ADDREQ_FLAGS_MASK = 0xFFFF0000
WINHTTP_ADDREQ_FLAG_ADD_IF_NEW = 0x10000000
WINHTTP_ADDREQ_FLAG_ADD = 0x20000000
WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = 0x40000000
WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = 0x01000000
WINHTTP_ADDREQ_FLAG_COALESCE = WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
WINHTTP_ADDREQ_FLAG_REPLACE = 0x80000000
WINHTTP_CALLBACK_STATUS_RESOLVING_NAME = 0x00000001
WINHTTP_CALLBACK_STATUS_NAME_RESOLVED = 0x00000002
WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER = 0x00000004
WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER = 0x00000008
WINHTTP_CALLBACK_STATUS_SENDING_REQUEST = 0x00000010
WINHTTP_CALLBACK_STATUS_REQUEST_SENT = 0x00000020
WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE = 0x00000040
WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED = 0x00000080
WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION = 0x00000100
WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED = 0x00000200
WINHTTP_CALLBACK_STATUS_HANDLE_CREATED = 0x00000400
WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING = 0x00000800
WINHTTP_CALLBACK_STATUS_DETECTING_PROXY = 0x00001000
WINHTTP_CALLBACK_STATUS_REDIRECT = 0x00004000
WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE = 0x00008000
WINHTTP_CALLBACK_STATUS_SECURE_FAILURE = 0x00010000
WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE = 0x00020000
WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE = 0x00040000
WINHTTP_CALLBACK_STATUS_READ_COMPLETE = 0x00080000
WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE = 0x00100000
WINHTTP_CALLBACK_STATUS_REQUEST_ERROR = 0x00200000
WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE = 0x00400000
WINHTTP_CALLBACK_FLAG_RESOLVE_NAME = WINHTTP_CALLBACK_STATUS_RESOLVING_NAME | WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER = WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER | WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
)
const (
WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED = 0x00000001
WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT = 0x00000002
WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED = 0x00000004
WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA = 0x00000008
WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID = 0x00000010
WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID = 0x00000020
WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE = 0x00000040
WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR = 0x80000000
)
// Constants we're missing from the Windows syscall package.
const (
ERROR_INVALID_PARAMETER syscall.Errno = 0x00000057
)
@@ -0,0 +1,486 @@
//go:build windows
package winhttp
// Package winhttp provides a Golang-ish interface to the WinHTTP
// API. Because WinHTTP has a somewhat consistent pattern of use that
// contrasts with what ideomatic Golang expects, there will still be
// some rough edges (see GetOption and SetOption for examples), but
// this package should enable someone with basic understanding of
// WinHTTP and knowledge of Go to be able to use it to produce
// software making use of winhttp.dll.
//
// Some notes:
// - Error handling may look a little weird. As per
// https://godoc.org/golang.org/x/sys/windows#LazyProc.Call , we
// *must* check the primary return value to see if the error is
// valid. To be more Golang-y, we do that here and return nil for
// errors when we don't have an error condition.
// - We currently do not support WinHTTP in async operation.
// - To avoid constantly looking up procs, we cache them here in
// private globals.
// - To help mesh one's understanding of what's going on here against
// MSDN documentation, we're using field and argument names from MSDN.
// - Arguments and struct fields marked as reserved in MSDN are either
// not present in function arguments here or not exported in struct
// types. We have to include them in structs to preserve memory
// layouts that Windows will expect.
import (
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
// HInternet is an internet handle given to us by WinHttp.
type HInternet uintptr
var wh = windows.NewLazySystemDLL("winhttp.dll")
var k32 = windows.NewLazySystemDLL("kernel32.dll")
var gF = k32.NewProc("GlobalFree")
func globalFree(ptr *uint16) {
if ptr != nil {
gF.Call(uintptr(unsafe.Pointer(ptr)))
}
}
type WinHttpCurrentUserIeProxyConfig struct {
FAutoDetect bool
LpszAutoConfigUrl *uint16
LpszProxy *uint16
LpszProxyBypass *uint16
}
func FreeWinHttpCurrentUserIeProxyConfig(cfg *WinHttpCurrentUserIeProxyConfig) {
globalFree(cfg.LpszAutoConfigUrl)
globalFree(cfg.LpszProxy)
globalFree(cfg.LpszProxyBypass)
}
type WinHttpAutoproxyOptions struct {
DwFlags uint32
DwAutoDetectFlags uint32
LpszAutoConfigUrl *uint16
lpvReserved uintptr
dwReserved uint32
FAutoLogonIfChallenged bool
}
type WinHttpProxyInfo struct {
DwAccessType uint32
LpszProxy *uint16
LpszProxyBypass *uint16
}
func FreeWinHttpProxyInfo(cfg *WinHttpProxyInfo) {
globalFree(cfg.LpszProxy)
globalFree(cfg.LpszProxyBypass)
}
var closeHandle = wh.NewProc("WinHttpCloseHandle")
// CloseHandle will close an hInternet handle. It is OK if the handle
// is already NULL.
func CloseHandle(hInternet HInternet) {
if hInternet != 0 {
closeHandle.Call(uintptr(hInternet))
}
}
var winHttpOpen = wh.NewProc("WinHttpOpen")
// Open creates a new WinHTTP Session for us.
func Open(userAgent string, accessType uint32, proxyName string, proxyBypass string, flags uint32) (HInternet, error) {
var pname *uint16
var pbypass *uint16
if proxyName != "" {
pname = windows.StringToUTF16Ptr(proxyName)
}
if proxyBypass != "" {
pbypass = windows.StringToUTF16Ptr(proxyBypass)
}
h, _, err := winHttpOpen.Call(
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(userAgent))),
uintptr(accessType),
uintptr(unsafe.Pointer(pname)),
uintptr(unsafe.Pointer(pbypass)),
uintptr(flags),
)
if h != 0 {
err = nil
}
return HInternet(h), err
}
var queryOption = wh.NewProc("WinHttpQueryOption")
//go:uintptrescapes
// QueryOption queries an option on the specified handle.
//
// Note that because we don't know what type of data we'll be getting
// via buffer, this function is tagged with a pragma to behave
// properly when using the form uintptr(unsafe.Pointer(&obj)) in its
// function call, similar to the wired-in compiler tricks for
// syscall.Syscall(). See the documentation to unsafe.Pointer
// (https://golang.org/pkg/unsafe/#Pointer) for more information.
func QueryOption(hInternet HInternet, option uint32, buffer uintptr, bufferLength *uint32) error {
r, _, err := queryOption.Call(
uintptr(hInternet),
uintptr(option),
buffer,
uintptr(unsafe.Pointer(bufferLength)),
)
if r != 1 {
return err
}
return nil
}
var setOption = wh.NewProc("WinHttpSetOption")
//go:uintptrescapes
// SetOption sets an option on the specified handle.
//
// Note that because we don't know what type of data we'll be getting
// via buffer, this function is tagged with a pragma to behave
// properly when using the form uintptr(unsafe.Pointer(&obj)) in its
// function call, similar to the wired-in compiler tricks for
// syscall.Syscall(). See the documentation to unsafe.Pointer
// (https://golang.org/pkg/unsafe/#Pointer) for more information.
func SetOption(
hInternet HInternet,
option uint32,
buffer uintptr,
bufferLength uintptr,
) error {
r, _, err := setOption.Call(
uintptr(hInternet),
uintptr(option),
buffer,
bufferLength,
)
if r != 1 {
return err
}
return nil
}
var setStatusCallback = wh.NewProc("WinHttpSetStatusCallback")
// SetStatusCallback sets a callback for status events from WinHTTP.
//
// See documentation on the callback function signature at
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa383917(v=vs.85).aspx
func SetStatusCallback(
hInternet HInternet,
internetCallback interface{},
notificationFlags uint32,
) error {
r, _, err := setStatusCallback.Call(
uintptr(hInternet),
syscall.NewCallback(internetCallback),
uintptr(notificationFlags),
0,
)
// WinHttpSetStatusCallback returns a uintptr representing a
// pointer to the previous callback or a value of -1 in the
// case of error. For those playing along at home, we can't do
// much with the uintptr to a function, nor can we represent
// -1 as valid uintptr. So, we do the below to return true or
// false for success instead.
if r == ^uintptr(0) {
return err
}
return nil
}
var sendRequest = wh.NewProc("WinHttpSendRequest")
// SendRequest sends the given hRequest across the network, with
// optionally setting additional headers or body data.
func SendRequest(
hRequest HInternet,
headers string,
optional *byte,
optionalLength int,
totalLength int,
context *uint32,
) error {
var r uintptr
var err error
if headers != "" {
r, _, err = sendRequest.Call(
uintptr(hRequest),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(headers))),
^uintptr(0),
uintptr(unsafe.Pointer(optional)),
uintptr(optionalLength),
uintptr(totalLength),
uintptr(unsafe.Pointer(context)),
)
} else {
r, _, err = sendRequest.Call(
uintptr(hRequest),
uintptr(WINHTTP_NO_ADDITIONAL_HEADERS),
uintptr(0),
uintptr(unsafe.Pointer(optional)),
uintptr(optionalLength),
uintptr(totalLength),
uintptr(unsafe.Pointer(context)),
)
}
if r != 1 {
return err
}
return nil
}
var receiveResponse = wh.NewProc("WinHttpReceiveResponse")
// ReceiveResponse waits to receive the response to an HTTP request
// sent by SendRequest.
func ReceiveResponse(hRequest HInternet) error {
if r, _, err := receiveResponse.Call(uintptr(hRequest), 0); r != 1 {
return err
}
return nil
}
var connect = wh.NewProc("WinHttpConnect")
// Connect creates an hConnect handle pointing to a specified server.
func Connect(
hSession HInternet,
serverName string,
port int,
) (HInternet, error) {
r, _, err := connect.Call(
uintptr(hSession),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(serverName))),
uintptr(port),
0,
)
if r != 0 {
err = nil
}
return HInternet(r), err
}
var openRequest = wh.NewProc("WinHttpOpenRequest")
// OpenRequest creates a new request for a given hConnect.
func OpenRequest(
hConnect HInternet,
verb string,
objectName string,
version string,
referrer string,
acceptTypes []string,
flags uint32,
) (HInternet, error) {
var verbptr *uint16
if verb != "" {
verbptr = windows.StringToUTF16Ptr(verb)
}
var objptr *uint16
if objectName != "" {
objptr = windows.StringToUTF16Ptr(objectName)
}
var verptr *uint16
if version != "" {
verptr = windows.StringToUTF16Ptr(version)
}
var refptr *uint16
if referrer != "" {
refptr = windows.StringToUTF16Ptr(referrer)
}
r, _, err := openRequest.Call(
uintptr(hConnect),
uintptr(unsafe.Pointer(verbptr)),
uintptr(unsafe.Pointer(objptr)),
uintptr(unsafe.Pointer(verptr)),
uintptr(unsafe.Pointer(refptr)),
0, // Not implementing ppwszAcceptTypes at this time.
uintptr(flags),
)
if r != 0 {
err = nil
}
return HInternet(r), err
}
var addRequestHeaders = wh.NewProc("WinHttpAddRequestHeaders")
// AddRequestHeaders adds HTTP headers to the specified Request.
func AddRequestHeaders(
hRequest HInternet,
header string,
modifiers uint32,
) error {
r, _, err := addRequestHeaders.Call(
uintptr(hRequest),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(header))),
^uintptr(0),
uintptr(modifiers),
)
if r != 1 {
return err
}
return nil
}
var queryHeaders = wh.NewProc("WinHttpQueryHeaders")
// QueryHeaders retreives information from the headers of the
// specified Request.
func QueryHeaders(
hRequest HInternet,
infoLevel uint32,
name string,
buffer *uint16,
bufferLength *uint32,
index *uint32,
) error {
var nameptr *uint16
if name != "" {
nameptr = windows.StringToUTF16Ptr(name)
}
r, _, err := queryHeaders.Call(
uintptr(hRequest),
uintptr(infoLevel),
uintptr(unsafe.Pointer(nameptr)),
uintptr(unsafe.Pointer(buffer)),
uintptr(unsafe.Pointer(bufferLength)),
uintptr(unsafe.Pointer(index)),
)
if r != 1 {
return err
}
return nil
}
var queryDataAvailable = wh.NewProc("WinHttpQueryDataAvailable")
// QueryDataAvailable returns if we have data available to read.
func QueryDataAvailable(
hRequest HInternet,
) (uint, error) {
var d uint32
r, _, err := queryDataAvailable.Call(
uintptr(hRequest),
uintptr(unsafe.Pointer(&d)),
)
if r != 1 {
return 0, err
}
return uint(d), nil
}
var readData = wh.NewProc("WinHttpReadData")
// ReadData reads data from the Request into buffer.
func ReadData(
hRequest HInternet,
buffer []byte,
) (int, error) {
if len(buffer) > 0 {
var b uint32
r, _, err := readData.Call(
uintptr(hRequest),
uintptr(unsafe.Pointer(&buffer[0])),
uintptr(len(buffer)),
uintptr(unsafe.Pointer(&b)),
)
if r != 1 {
return 0, err
}
return int(b), nil
} else {
return 0, nil
}
}
var getProxyForUrl = wh.NewProc("WinHttpGetProxyForUrl")
func GetProxyForUrl(
hSession HInternet,
url string,
autoProxyOptions *WinHttpAutoproxyOptions,
) (*WinHttpProxyInfo, error) {
p := new(WinHttpProxyInfo)
r, _, err := getProxyForUrl.Call(
uintptr(hSession),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(url))),
uintptr(unsafe.Pointer(autoProxyOptions)),
uintptr(unsafe.Pointer(p)),
)
if r != 1 {
return nil, err
}
return p, nil
}
var getIEProxyConfigForCurrentUser = wh.NewProc("WinHttpGetIEProxyConfigForCurrentUser")
func GetIEProxyConfigForCurrentUser() (*WinHttpCurrentUserIeProxyConfig, error) {
i := new(WinHttpCurrentUserIeProxyConfig)
r, _, err := getIEProxyConfigForCurrentUser.Call(
uintptr(unsafe.Pointer(i)),
)
if r != 1 {
return nil, err
}
return i, nil
}
var setTimeouts = wh.NewProc("WinHttpSetTimeouts")
func SetTimeouts(
hInternet HInternet,
resolveTimeout int,
connectTimeout int,
sendTimeout int,
receiveTimeout int,
) error {
r, _, err := setTimeouts.Call(
uintptr(hInternet),
uintptr(resolveTimeout),
uintptr(connectTimeout),
uintptr(sendTimeout),
uintptr(receiveTimeout),
)
if r != 1 {
return err
}
return nil
}
+1 -1
View File
@@ -1,4 +1,4 @@
// +build windows
//go:build windows
// Copyright (C) 2018, Rapid7 LLC, Boston, MA, USA.
// All rights reserved. This material contains unpublished, copyrighted