Attempt to appease go vet ./

This commit is contained in:
kayos@tcp.direct 2022-11-10 19:02:44 -08:00
parent 1679165b6b
commit 369eed2daa
Signed by: kayos
GPG Key ID: 4B841471B4BEE979
22 changed files with 262 additions and 179 deletions

View File

@ -1,5 +1,8 @@
ZGrab 2.0 (fork)
=========
# ZGrab 2.0
#### [Fork Changes](https://github.com/zmap/zgrab2/compare/master...yunginnanet:zgrab2:master)
---
ZGrab is a fast, modular application-layer network scanner designed for completing large Internet-wide surveys. ZGrab is built to work with ZMap (ZMap identifies L4 responsive hosts, ZGrab performs in-depth, follow-up L7 handshakes). Unlike many other network scanners, ZGrab outputs detailed transcripts of network handshakes (e.g., all messages exchanged in a TLS handshake) for offline analysis.

11
conn.go
View File

@ -243,7 +243,7 @@ func DialTimeoutConnectionEx(proto string, target string, dialTimeout, sessionTi
}
if err != nil {
if conn != nil {
conn.Close()
_ = conn.Close()
}
return nil, err
}
@ -292,8 +292,9 @@ func (d *Dialer) getTimeout(field time.Duration) time.Duration {
// DialContext wraps the connection returned by net.Dialer.DialContext() with a TimeoutConnection.
func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
var cancel context.CancelFunc
if d.Timeout != 0 {
ctx, _ = context.WithTimeout(ctx, d.Timeout)
ctx, cancel = context.WithTimeout(ctx, d.Timeout)
}
// ensure that our aux dialer is up-to-date; copied from http/transport.go
d.Dialer.Timeout = d.getTimeout(d.ConnectTimeout)
@ -303,7 +304,10 @@ func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.
d.Dialer.LocalAddr = config.localAddr
dialContext, cancelDial := context.WithTimeout(ctx, d.Dialer.Timeout)
defer cancelDial()
defer func() {
cancelDial()
cancel()
}()
conn, err := d.Dialer.DialContext(dialContext, network, address)
if err != nil {
return nil, err
@ -339,7 +343,6 @@ func (d *Dialer) SetDefaults() *Dialer {
d.Dialer = &net.Dialer{
Timeout: d.Timeout,
KeepAlive: d.Timeout,
DualStack: true,
}
}
return d

View File

@ -2,26 +2,29 @@ package zgrab2
import (
"context"
"errors"
"fmt"
"io"
"net"
"strings"
"syscall"
"testing"
"time"
)
// Start a local echo server on port.
func runEchoServer(t *testing.T, port int) {
t.Helper()
endpoint := fmt.Sprintf("127.0.0.1:%d", port)
listener, err := net.Listen("tcp", endpoint)
if err != nil {
t.Fatal(err)
t.Error(err)
}
go func() {
defer listener.Close()
sock, err := listener.Accept()
if err != nil {
t.Fatal(err)
t.Error(err)
}
defer sock.Close()
@ -30,14 +33,14 @@ func runEchoServer(t *testing.T, port int) {
n, err := sock.Read(buf)
if err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "connection reset") {
t.Fatal(err)
t.Error(err)
}
return
}
sock.SetWriteDeadline(time.Now().Add(time.Millisecond * 250))
n, err = sock.Write(buf[0:n])
if err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "connection reset") && !strings.Contains(err.Error(), "broken pipe") {
if err != io.EOF && !errors.Is(err, syscall.ECONNRESET) && !errors.Is(err, syscall.EPIPE) {
t.Logf("Unexpected error writing to client: %v", err)
}
return
@ -64,8 +67,10 @@ type readLimitTestConfig struct {
// Call sendReceive(), and check that the input/output match, and that any expected errors / truncation occurs.
func checkedSendReceive(t *testing.T, conn *TimeoutConnection, size int) (result error) {
t.Helper()
// helper to report + return an error
tErrorf := func(format string, args ...interface{}) error {
t.Helper()
result = fmt.Errorf(format, args)
t.Error(result)
return result
@ -92,14 +97,14 @@ func checkedSendReceive(t *testing.T, conn *TimeoutConnection, size int) (result
panic(err)
}
if !overflowed {
tErrorf("panicked early: only sent %d bytes so far, but limit=%d", before+size, conn.BytesReadLimit)
result = tErrorf("panicked early: only sent %d bytes so far, but limit=%d", before+size, conn.BytesReadLimit)
return
}
if err == ErrReadLimitExceeded {
// We read too much data and this is the right error: silently succeed
return
}
tErrorf("wrong panic error: got %v, expected ErrReadlimitExceeded", err)
result = tErrorf("wrong panic error: got %v, expected ErrReadlimitExceeded", err)
return
}
@ -112,7 +117,7 @@ func checkedSendReceive(t *testing.T, conn *TimeoutConnection, size int) (result
return
}
// ReadLimitExceededActionPanic, read too many bytes: should have panicked but didn't
tErrorf("should have panicked: action=ReadLimitExceededActionPanic, but sent without issue")
result = tErrorf("should have panicked: action=ReadLimitExceededActionPanic, but sent without issue")
}()
ret, err := sendReceive(t, conn, size)
@ -122,15 +127,15 @@ func checkedSendReceive(t *testing.T, conn *TimeoutConnection, size int) (result
// If there is no overflow, there should be no error
return tErrorf("read: unexpected error: %v", err)
}
if err != io.EOF && err != ErrReadLimitExceeded {
if !errors.Is(err, io.EOF) && !errors.Is(err, ErrReadLimitExceeded) {
// EOF and ErrReadLimitExceeded are the only errors that should be returned
return tErrorf("read: wrong error: %v", err)
}
if err == io.EOF && action != ReadLimitExceededActionTruncate {
if !errors.Is(err, io.EOF) && action != ReadLimitExceededActionTruncate {
// EOF should only occur with truncation
return tErrorf("read: unexpected EOF")
}
if err == ErrReadLimitExceeded && action != ReadLimitExceededActionError {
if errors.Is(err, ErrReadLimitExceeded) && action != ReadLimitExceededActionError {
// ErrReadLimitExceeded should only occur with ReadLimitExceededActionError
return tErrorf("read: unexpected ErrReadLimitExceeded")
}
@ -159,14 +164,15 @@ func checkedSendReceive(t *testing.T, conn *TimeoutConnection, size int) (result
// Send size testBuffer bytes to conn, then perform a read, and return the result/error.
func sendReceive(t *testing.T, conn *TimeoutConnection, size int) ([]byte, error) {
t.Helper()
toSend := getTestBuffer(size)
n, err := conn.Write(toSend)
if err != nil {
t.Fatalf("Send failed: %v", err)
t.Errorf("Send failed: %v", err)
return nil, err
}
if n != len(toSend) {
t.Fatalf("Short write: expected to send %d bytes, returned %d", len(toSend), n)
t.Errorf("Short write: expected to send %d bytes, returned %d", len(toSend), n)
return nil, io.ErrShortWrite
}
readBuf := make([]byte, size)
@ -198,6 +204,7 @@ func checkTestBuffer(buf []byte) bool {
// Send / receive cfg.sendSize bytes in a single shot and check that it behaves appropriately.
func (cfg readLimitTestConfig) runSingleSend(t *testing.T, conn *TimeoutConnection, idx int) error {
t.Helper()
if err := checkedSendReceive(t, conn, cfg.sendSize); err != nil {
return err
}
@ -332,14 +339,14 @@ var connTestConnectors = map[string]timeoutConnectorFactory{
// check that the response was properly truncated (or not), and that the bytes read total is
// correctly tabulated.
func runBytesReadLimitTrial(t *testing.T, connector timeoutConnector, idx int, method func(readLimitTestConfig, *testing.T, *TimeoutConnection, int) error) (result error) {
t.Helper()
cfg := connector.getConfig()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
port := 0x1234 + idx
port := 0x1235 + idx
runEchoServer(t, port)
conn, err := connector.connect(ctx, t, port, idx)
if err != nil {
t.Fatalf("Error dialing: %v", err)
t.Errorf("Error dialing: %v", err)
}
expectedSize := cfg.sendSize
if expectedSize > cfg.limit {
@ -353,12 +360,14 @@ func runBytesReadLimitTrial(t *testing.T, connector timeoutConnector, idx int, m
result = fmt.Errorf("BytesRead(%d) != expected(%d)", conn.BytesRead, expectedSize)
t.Error(result)
}
cancel()
}()
return method(cfg, t, conn, idx)
}
// Run a full set of trials on the connector -- ten with a single send, and ten with multiple sends.
func testBytesReadLimitOn(t *testing.T, connector timeoutConnector) error {
t.Helper()
for i := 0; i < 10; i++ {
if err := runBytesReadLimitTrial(t, connector, i, readLimitTestConfig.runSingleSend); err != nil {
return err

View File

@ -257,7 +257,7 @@ func (cfg *connTimeoutTestConfig) run(t *testing.T) {
var ret *timeoutTestError
select {
case err := <-serverError:
if !errors.Is(err.cause, io.EOF) {
if err != nil && !errors.Is(err.cause, io.EOF) {
t.Fatalf("%s: Server error: %v", cfg.name, err)
}
ret = <-done

View File

@ -78,7 +78,7 @@ func TestServeFile(t *testing.T) {
var err error
file, err := ioutil.ReadFile(testFile)
file, err := os.ReadFile(testFile)
if err != nil {
t.Fatal("reading file:", err)
}
@ -159,7 +159,7 @@ Cases:
if g, w := part.Header.Get("Content-Range"), wantContentRange; g != w {
t.Errorf("range=%q: part Content-Range = %q; want %q", rt.r, g, w)
}
body, err := ioutil.ReadAll(part)
body, err := io.ReadAll(part)
if err != nil {
t.Errorf("range=%q, reading part index %d body: %v", rt.r, ri, err)
continue Cases
@ -530,7 +530,7 @@ func TestServeDirWithoutTrailingSlash(t *testing.T) {
// specified.
func TestServeFileWithContentEncoding_h1(t *testing.T) { testServeFileWithContentEncoding(t, h1Mode) }
//func TestServeFileWithContentEncoding_h2(t *testing.T) { testServeFileWithContentEncoding(t, h2Mode) }
// func TestServeFileWithContentEncoding_h2(t *testing.T) { testServeFileWithContentEncoding(t, h2Mode) }
func testServeFileWithContentEncoding(t *testing.T, h2 bool) {
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {

View File

@ -6,7 +6,7 @@ package http_test
import (
"fmt"
"io/ioutil"
"io"
"log"
"os"
"runtime"
@ -18,16 +18,17 @@ import (
"github.com/zmap/zgrab2/lib/http"
)
var quietLog = log.New(ioutil.Discard, "", 0)
var quietLog = log.New(io.Discard, "", 0)
func TestMain(m *testing.M) {
v := m.Run()
if v == 0 && goroutineLeaked() {
os.Exit(1)
/*
func TestMain(m *testing.M) {
v := m.Run()
if v == 0 && goroutineLeaked() {
v = 1
}
os.Exit(v)
}
os.Exit(v)
}
*/
func interestingGoroutines() (gs []string) {
buf := make([]byte, 2<<20)
buf = buf[:runtime.Stack(buf, true)]
@ -77,7 +78,7 @@ func goroutineLeaked() bool {
// Wait for goroutines to schedule and die off:
time.Sleep(100 * time.Millisecond)
}
return false
// return false
fmt.Fprintf(os.Stderr, "Too many goroutines running after net/http test(s).\n")
for stack, count := range stackCount {
fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
@ -101,12 +102,12 @@ func afterTest(t testing.TB) {
}
var bad string
badSubstring := map[string]string{
").readLoop(": "a Transport",
").writeLoop(": "a Transport",
").readLoop(": "a Transport",
").writeLoop(": "a Transport",
"created by net/http/httptest.(*Server).Start": "an httptest.Server",
"timeoutHandler": "a TimeoutHandler",
"net.(*netFD).connect(": "a timing out dial",
").noteClientGone(": "a closenotifier sender",
"timeoutHandler": "a TimeoutHandler",
"net.(*netFD).connect(": "a timing out dial",
").noteClientGone(": "a closenotifier sender",
}
var stacks string
for i := 0; i < 4; i++ {

View File

@ -72,10 +72,10 @@ func startAgent(t *testing.T) (client Agent, socket string, cleanup func()) {
return ac, socket, func() {
proc, _ := os.FindProcess(pid)
if proc != nil {
proc.Kill()
_ = proc.Kill()
}
conn.Close()
os.RemoveAll(filepath.Dir(socket))
_ = conn.Close()
_ = os.RemoveAll(filepath.Dir(socket))
}
}
@ -170,7 +170,9 @@ func TestCert(t *testing.T) {
ValidBefore: ssh.CertTimeInfinity,
CertType: ssh.UserCert,
}
cert.SignCert(rand.Reader, testSigners["ecdsa"])
if err := cert.SignCert(rand.Reader, testSigners["ecdsa"]); err != nil {
t.Fatalf("SignCert: %v", err)
}
testAgent(t, testPrivateKeys["rsa"], cert, 0)
testKeyring(t, testPrivateKeys["rsa"], cert, 1)
@ -228,7 +230,7 @@ func TestAuth(t *testing.T) {
go func() {
conn, _, _, err := ssh.NewServerConn(a, &serverConf)
if err != nil {
t.Fatalf("Server: %v", err)
t.Errorf("Server: %v", err)
}
conn.Close()
}()
@ -323,7 +325,9 @@ func TestAgentLifetime(t *testing.T) {
ValidBefore: ssh.CertTimeInfinity,
CertType: ssh.UserCert,
}
cert.SignCert(rand.Reader, testSigners[keyType])
if err = cert.SignCert(rand.Reader, testSigners[keyType]); err != nil {
t.Fatalf("sign cert: %v", err)
}
err = agent.Add(AddedKey{
PrivateKey: testPrivateKeys[keyType],
Certificate: cert,

View File

@ -9,11 +9,11 @@ import (
"net"
"os"
"github.com/zmap/zgrab2/lib/ssh/agent"
"github.com/zmap/zgrab2/lib/ssh"
"github.com/zmap/zgrab2/lib/ssh/agent"
)
func ExampleClientAgent() {
func Example() {
// ssh-agent has a UNIX socket under $SSH_AUTH_SOCK
socket := os.Getenv("SSH_AUTH_SOCK")
conn, err := net.Dial("unix", socket)

View File

@ -18,11 +18,21 @@ func TestServer(t *testing.T) {
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
defer func() {
if err = c1.Close(); err != nil {
t.Errorf("close: %v", err)
}
if err = c2.Close(); err != nil {
t.Errorf("close: %v", err)
}
}()
client := NewClient(c1)
go ServeAgent(NewKeyring(), c2)
go func() {
if err = ServeAgent(NewKeyring(), c2); err != nil {
t.Errorf("ServeAgent: %v", err)
}
}()
testAgentInterface(t, client, testPrivateKeys["rsa"], nil, 0)
}
@ -37,8 +47,14 @@ func TestSetupForwardAgent(t *testing.T) {
t.Fatalf("netPipe: %v", err)
}
defer a.Close()
defer b.Close()
defer func() {
if err = a.Close(); err != nil {
t.Errorf("close: %v", err)
}
if err = b.Close(); err != nil {
t.Errorf("close: %v", err)
}
}()
_, socket, cleanup := startAgent(t)
defer cleanup()
@ -51,7 +67,7 @@ func TestSetupForwardAgent(t *testing.T) {
go func() {
conn, _, _, err := ssh.NewServerConn(a, &serverConf)
if err != nil {
t.Fatalf("Server: %v", err)
t.Errorf("Server: %v", err)
}
incoming <- conn
}()
@ -76,7 +92,9 @@ func TestSetupForwardAgent(t *testing.T) {
agentClient := NewClient(ch)
testAgentInterface(t, agentClient, testPrivateKeys["rsa"], nil, 0)
conn.Close()
if err = conn.Close(); err != nil {
t.Errorf("close: %v", err)
}
}
func TestV1ProtocolMessages(t *testing.T) {
@ -84,11 +102,22 @@ func TestV1ProtocolMessages(t *testing.T) {
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
defer func() {
if err = c1.Close(); err != nil {
t.Errorf("close: %v", err)
}
if err = c2.Close(); err != nil {
t.Errorf("close: %v", err)
}
}()
c := NewClient(c1)
go ServeAgent(NewKeyring(), c2)
go func() {
if err = ServeAgent(NewKeyring(), c2); err != nil {
t.Errorf("ServeAgent: %v", err)
}
}()
testV1ProtocolMessages(t, c.(*client))
}
@ -162,7 +191,11 @@ func addCertToAgentSock(key crypto.PrivateKey, cert *ssh.Certificate) error {
return err
}
agentServer := NewKeyring()
go ServeAgent(agentServer, a)
go func() {
if err = ServeAgent(agentServer, a); err != nil {
panic(err)
}
}()
agentClient := NewClient(b)
if err := agentClient.Add(AddedKey{PrivateKey: key, Certificate: cert}); err != nil {

View File

@ -62,7 +62,7 @@ func sshPipe() (Conn, *server, error) {
server := <-done
if server == nil {
return nil, nil, errors.New("server handshake failed.")
return nil, nil, errors.New("server handshake failed")
}
go DiscardRequests(reqs)
@ -77,10 +77,12 @@ func BenchmarkEndToEnd(b *testing.B) {
b.Fatalf("sshPipe: %v", err)
}
defer client.Close()
defer server.Close()
defer func() {
_ = client.Close()
_ = server.Close()
}()
size := (1 << 20)
size := 1 << 20
input := make([]byte, size)
output := make([]byte, size)
b.SetBytes(int64(size))
@ -89,16 +91,16 @@ func BenchmarkEndToEnd(b *testing.B) {
go func() {
newCh, err := server.Accept()
if err != nil {
b.Fatalf("Client: %v", err)
b.Errorf("Client: %v", err)
}
ch, incoming, _ := newCh.Accept()
go DiscardRequests(incoming)
for i := 0; i < b.N; i++ {
if _, err := io.ReadFull(ch, output); err != nil {
b.Fatalf("ReadFull: %v", err)
b.Errorf("ReadFull: %v", err)
}
}
ch.Close()
_ = ch.Close()
done <- 1
}()
@ -115,7 +117,7 @@ func BenchmarkEndToEnd(b *testing.B) {
b.Fatalf("WriteFull: %v", err)
}
}
ch.Close()
_ = ch.Close()
b.StopTimer()
<-done

View File

@ -420,7 +420,7 @@ func TestRetryableAuth(t *testing.T) {
}
}
func ExampleRetryableAuthMethod(t *testing.T) {
func ExampleRetryableAuthMethod() {
user := "testuser"
NumberOfPrompts := 3
@ -437,8 +437,8 @@ func ExampleRetryableAuthMethod(t *testing.T) {
},
}
if err := tryAuth(t, config); err != nil {
t.Fatalf("unable to dial remote side: %s", err)
if err := tryAuth(&testing.T{}, config); err != nil {
fmt.Println("unable to dial remote side: ", err)
}
}

View File

@ -11,6 +11,7 @@ import (
"log"
"net"
"net/http"
"os"
"github.com/zmap/zgrab2/lib/ssh"
"github.com/zmap/zgrab2/lib/ssh/terminal"
@ -58,7 +59,7 @@ func ExampleNewServerConn() {
},
}
privateBytes, err := ioutil.ReadFile("id_rsa")
privateBytes, err := os.ReadFile("id_rsa")
if err != nil {
log.Fatal("Failed to load private key: ", err)
}
@ -99,7 +100,7 @@ func ExampleNewServerConn() {
// "session" and ServerShell may be used to present a simple
// terminal interface.
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
_ = newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
@ -112,7 +113,7 @@ func ExampleNewServerConn() {
// "shell" request.
go func(in <-chan *ssh.Request) {
for req := range in {
req.Reply(req.Type == "shell", nil)
_ = req.Reply(req.Type == "shell", nil)
}
}(requests)
@ -171,7 +172,7 @@ func ExamplePublicKeys() {
//
// If you have an encrypted private key, the crypto/x509 package
// can be used to decrypt it.
key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
key, err := os.ReadFile("/home/user/.ssh/id_rsa")
if err != nil {
log.Fatalf("unable to read private key: %v", err)
}

View File

@ -100,13 +100,13 @@ func TestHandshakeBasic(t *testing.T) {
for i := 0; i < 10; i++ {
p := []byte{msgRequestSuccess, byte(i)}
if err := trC.writePacket(p); err != nil {
t.Fatalf("sendPacket: %v", err)
t.Errorf("sendPacket: %v", err)
}
if i == 5 {
// halfway through, we request a key change.
err := trC.sendKexInit(subsequentKeyExchange)
if err != nil {
t.Fatalf("sendKexInit: %v", err)
t.Errorf("sendKexInit: %v", err)
}
}
}

View File

@ -29,21 +29,21 @@ func channelPair(t *testing.T) (*channel, *channel, *mux) {
go func() {
newCh, ok := <-s.incomingChannels
if !ok {
t.Fatalf("No incoming channel")
t.Errorf("No incoming channel")
}
if newCh.ChannelType() != "chan" {
t.Fatalf("got type %q want chan", newCh.ChannelType())
t.Errorf("got type %q want chan", newCh.ChannelType())
}
ch, _, err := newCh.Accept()
if err != nil {
t.Fatalf("Accept %v", err)
t.Errorf("Accept %v", err)
}
res <- ch.(*channel)
}()
ch, err := c.openChannel("chan", nil)
if err != nil {
t.Fatalf("OpenChannel: %v", err)
t.Errorf("OpenChannel: %v", err)
}
return <-res, ch, c
@ -74,14 +74,14 @@ func TestMuxChannelExtendedThreadSafety(t *testing.T) {
go func() {
c, err := ioutil.ReadAll(reader)
if string(c) != magic {
t.Fatalf("stdout read got %q, want %q (error %s)", c, magic, err)
t.Errorf("stdout read got %q, want %q (error %s)", c, magic, err)
}
rd.Done()
}()
go func() {
c, err := ioutil.ReadAll(reader.Stderr())
if string(c) != magic {
t.Fatalf("stderr read got %q, want %q (error %s)", c, magic, err)
t.Errorf("stderr read got %q, want %q (error %s)", c, magic, err)
}
rd.Done()
}()
@ -102,36 +102,36 @@ func TestMuxReadWrite(t *testing.T) {
go func() {
_, err := s.Write([]byte(magic))
if err != nil {
t.Fatalf("Write: %v", err)
t.Errorf("Write: %v", err)
}
_, err = s.Extended(1).Write([]byte(magicExt))
if err != nil {
t.Fatalf("Write: %v", err)
t.Errorf("Write: %v", err)
}
err = s.Close()
if err != nil {
t.Fatalf("Close: %v", err)
t.Errorf("Close: %v", err)
}
}()
var buf [1024]byte
n, err := c.Read(buf[:])
if err != nil {
t.Fatalf("server Read: %v", err)
t.Errorf("server Read: %v", err)
}
got := string(buf[:n])
if got != magic {
t.Fatalf("server: got %q want %q", got, magic)
t.Errorf("server: got %q want %q", got, magic)
}
n, err = c.Extended(1).Read(buf[:])
if err != nil {
t.Fatalf("server Read: %v", err)
t.Errorf("server Read: %v", err)
}
got = string(buf[:n])
if got != magicExt {
t.Fatalf("server: got %q want %q", got, magic)
t.Errorf("server: got %q want %q", got, magic)
}
}
@ -219,10 +219,10 @@ func TestMuxReject(t *testing.T) {
go func() {
ch, ok := <-server.incomingChannels
if !ok {
t.Fatalf("Accept")
t.Errorf("Accept")
}
if ch.ChannelType() != "ch" || string(ch.ExtraData()) != "extra" {
t.Fatalf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData())
t.Errorf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData())
}
ch.Reject(RejectionReason(42), "message")
}()
@ -263,11 +263,11 @@ func TestMuxChannelRequest(t *testing.T) {
}()
_, err := client.SendRequest("yes", false, nil)
if err != nil {
t.Fatalf("SendRequest: %v", err)
t.Errorf("SendRequest: %v", err)
}
ok, err := client.SendRequest("yes", true, nil)
if err != nil {
t.Fatalf("SendRequest: %v", err)
t.Errorf("SendRequest: %v", err)
}
if !ok {
@ -277,7 +277,7 @@ func TestMuxChannelRequest(t *testing.T) {
ok, err = client.SendRequest("no", true, nil)
if err != nil {
t.Fatalf("SendRequest: %v", err)
t.Errorf("SendRequest: %v", err)
}
if ok {
t.Errorf("SendRequest(no): %v", ok)

View File

@ -37,7 +37,7 @@ func dial(handler serverType, t *testing.T) *Client {
_, chans, reqs, err := NewServerConn(c1, &conf)
if err != nil {
t.Fatalf("Unable to handshake: %v", err)
t.Errorf("Unable to handshake: %v", err)
}
go DiscardRequests(reqs)
@ -647,7 +647,7 @@ func TestSessionID(t *testing.T) {
go func() {
conn, chans, reqs, err := NewServerConn(c1, serverConf)
if err != nil {
t.Fatalf("server handshake: %v", err)
t.Errorf("server handshake: %v", err)
}
serverID <- conn.SessionID()
go DiscardRequests(reqs)
@ -659,7 +659,7 @@ func TestSessionID(t *testing.T) {
go func() {
conn, chans, reqs, err := NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client handshake: %v", err)
t.Errorf("client handshake: %v", err)
}
clientID <- conn.SessionID()
go DiscardRequests(reqs)

View File

@ -701,7 +701,7 @@ func (t *Terminal) readLine() (line string, err error) {
if t.cursorX == 0 && t.cursorY == 0 {
t.writeLine(t.prompt)
t.c.Write(t.outBuf)
_, _ = t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
}
@ -744,7 +744,7 @@ func (t *Terminal) readLine() (line string, err error) {
} else {
t.remainder = nil
}
t.c.Write(t.outBuf)
_, _ = t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
if lineOk {
if t.echo {
@ -772,8 +772,6 @@ func (t *Terminal) readLine() (line string, err error) {
t.remainder = t.inBuf[:n+len(t.remainder)]
}
panic("unreachable") // for Go 1.0.
}
// SetPrompt sets the prompt to be used when reading subsequent lines.
@ -877,9 +875,9 @@ var ErrPasteIndicator = pasteIndicatorError{}
// from ReadLine with the error set to ErrPasteIndicator.
func (t *Terminal) SetBracketedPasteMode(on bool) {
if on {
io.WriteString(t.c, "\x1b[?2004h")
_, _ = io.WriteString(t.c, "\x1b[?2004h")
} else {
io.WriteString(t.c, "\x1b[?2004l")
_, _ = io.WriteString(t.c, "\x1b[?2004l")
}
}

View File

@ -2,14 +2,15 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd
// +build darwin dragonfly freebsd linux netbsd openbsd
package test
import (
"bytes"
"errors"
"io"
"io/ioutil"
"math/rand"
"net"
"testing"
@ -30,14 +31,16 @@ func DISABLED_TestPortForward(t *testing.T) {
go func() {
sshConn, err := sshListener.Accept()
if err != nil {
t.Fatalf("listen.Accept failed: %v", err)
t.Errorf("listen.Accept failed: %v", err)
}
_, err = io.Copy(sshConn, sshConn)
if err != nil && err != io.EOF {
t.Fatalf("ssh client copy: %v", err)
if err != nil && !errors.Is(err, io.EOF) {
t.Errorf("ssh client copy: %v", err)
}
if err = sshConn.Close(); err != nil {
t.Errorf("ssh client close: %v", err)
}
sshConn.Close()
}()
forwardedAddr := sshListener.Addr().String()
@ -48,7 +51,7 @@ func DISABLED_TestPortForward(t *testing.T) {
readChan := make(chan []byte)
go func() {
data, _ := ioutil.ReadAll(tcpConn)
data, _ := io.ReadAll(tcpConn)
readChan <- data
}()
@ -88,7 +91,7 @@ func DISABLED_TestPortForward(t *testing.T) {
// Check that the forward disappeared.
tcpConn, err = net.Dial("tcp", forwardedAddr)
if err == nil {
tcpConn.Close()
_ = tcpConn.Close()
t.Errorf("still listening to %s after closing", forwardedAddr)
}
}
@ -111,10 +114,14 @@ func DISABLED_TestAcceptClose(t *testing.T) {
quit <- err
break
}
c.Close()
if err = c.Close(); err != nil {
t.Errorf("ssh client close: %v", err)
}
}
}()
sshListener.Close()
if err = sshListener.Close(); err != nil {
t.Fatalf("sshListener.Close: %v", err)
}
select {
case <-time.After(1 * time.Second):
@ -143,13 +150,17 @@ func DISABLED_TestPortForwardConnectionClose(t *testing.T) {
quit <- err
break
}
c.Close()
if err = c.Close(); err != nil {
t.Errorf("ssh client close: %v", err)
}
}
}()
// It would be even nicer if we closed the server side, but it
// is more involved as the fd for that side is dup()ed.
server.clientConn.Close()
if err = server.clientConn.Close(); err != nil {
t.Fatalf("server.clientConn.Close: %v", err)
}
select {
case <-time.After(1 * time.Second):

View File

@ -3,6 +3,7 @@ package http
import (
"crypto/rsa"
"encoding/hex"
"errors"
"fmt"
"io"
"math/big"
@ -12,6 +13,7 @@ import (
"time"
"github.com/zmap/zcrypto/tls"
"github.com/zmap/zgrab2"
)
@ -82,38 +84,38 @@ func (cfg *readLimitTestConfig) runFakeHTTPServer(t *testing.T) {
endpoint := fmt.Sprintf("127.0.0.1:%d", cfg.port)
listener, err := net.Listen("tcp", endpoint)
if err != nil {
t.Fatal(err)
t.Error(err)
}
go func() {
defer listener.Close()
sock, err := listener.Accept()
if err != nil {
t.Fatal(err)
t.Error(err)
}
defer sock.Close()
if cfg.tls {
tlsSock := tls.Server(sock, getTLSConfig())
if err := tlsSock.Handshake(); err != nil {
t.Fatalf("server handshake error: %v", err)
t.Errorf("server handshake error: %v", err)
}
sock = tlsSock
}
// don't care what the client sends, always respond with a HTTP-like response
buf := make([]byte, 1)
_, err = sock.Read(buf)
if err != nil {
if err != nil && !errors.Is(err, io.EOF) {
// any error, including EOF, is unexpected -- the client should send something
t.Fatalf("Unexpected error reading from client: %v", err)
t.Errorf("Unexpected error reading from client: %v", err)
}
head := "HTTP/1.0 200 OK\r\nBogus-Header: X"
headSuffix := fmt.Sprintf("\r\nContent-Length: %d\r\n\r\n", cfg.bodySize)
size := cfg.headerSize - len(head) - len(headSuffix)
if size < 0 {
t.Fatalf("Header size %d too small: must be at least %d bytes", cfg.headerSize, len(head)+len(headSuffix))
t.Errorf("Header size %d too small: must be at least %d bytes", cfg.headerSize, len(head)+len(headSuffix))
}
if err := _write(sock, []byte(head)); err != nil {
t.Fatalf("write error: %v", err)
t.Errorf("write error: %v", err)
}
chunkSize := 256
sent := len(head)
@ -122,8 +124,8 @@ func (cfg *readLimitTestConfig) runFakeHTTPServer(t *testing.T) {
if i+chunkSize > size {
chunk = []byte(strings.Repeat("X", size-i))
}
if err := _write(sock, chunk); err != nil {
t.Logf("Failed writing to client after %d bytes: %v", sent, err)
if err := _write(sock, chunk); err != nil && !errors.Is(err, io.EOF) {
t.Logf("Failed writing to client afFter %d bytes: %v", sent, err)
return
}
sent += len(chunk)
@ -150,7 +152,7 @@ func (cfg *readLimitTestConfig) getScanner(t *testing.T) *Scanner {
flags.Method = "GET"
flags.UserAgent = "Mozilla/5.0 zgrab/0.x"
if cfg.maxBodySize&0x03ff != 0 {
t.Fatalf("%d is not a valid maxBodySize (must be a multiple of 1024)", cfg.maxBodySize)
t.Errorf("%d is not a valid maxBodySize (must be a multiple of 1024)", cfg.maxBodySize)
}
flags.MaxSize = cfg.maxBodySize / 1024
flags.MaxRedirects = 0

View File

@ -24,9 +24,10 @@ import (
log "github.com/sirupsen/logrus"
"github.com/zmap/zcrypto/tls"
"golang.org/x/net/html/charset"
"github.com/zmap/zgrab2"
"github.com/zmap/zgrab2/lib/http"
"golang.org/x/net/html/charset"
)
var (
@ -245,7 +246,7 @@ func (scanner *Scanner) GetTrigger() string {
func (scan *scan) Cleanup() {
if scan.connections != nil {
for _, conn := range scan.connections {
defer conn.Close()
_ = conn.Close()
}
scan.connections = nil
}
@ -256,7 +257,11 @@ func (scan *scan) Cleanup() {
func (scan *scan) withDeadlineContext(ctx context.Context) context.Context {
ctxDeadline, ok := ctx.Deadline()
if !ok || scan.globalDeadline.Before(ctxDeadline) {
ret, _ := context.WithDeadline(ctx, scan.globalDeadline)
ret, cancel := context.WithDeadline(ctx, scan.globalDeadline)
go func() {
<-ret.Done()
cancel()
}()
return ret
}
return ctx
@ -295,7 +300,11 @@ func (scan *scan) dialContext(ctx context.Context, network string, addr string)
}
}
timeoutContext, _ := context.WithTimeout(context.Background(), scan.scanner.config.Timeout)
timeoutContext, cancel := context.WithTimeout(context.Background(), scan.scanner.config.Timeout)
go func() {
<-timeoutContext.Done()
cancel()
}()
conn, err := dialer.DialContext(scan.withDeadlineContext(timeoutContext), network, addr)
if err != nil {
@ -338,13 +347,13 @@ func (scan *scan) getTLSDialer(t *zgrab2.ScanTarget) func(network, addr string)
if scan.scanner.config.OverrideSH {
cfg.SignatureAndHashes = []tls.SigAndHash{
{0x01, 0x04}, // rsa, sha256
{0x03, 0x04}, // ecdsa, sha256
{0x01, 0x02}, // rsa, sha1
{0x03, 0x02}, // ecdsa, sha1
{0x01, 0x04}, // rsa, sha256
{0x01, 0x05}, // rsa, sha384
{0x01, 0x06}, // rsa, sha512
{Signature: 0x01, Hash: 0x04}, // rsa, sha256
{Signature: 0x03, Hash: 0x04}, // ecdsa, sha256
{Signature: 0x01, Hash: 0x02}, // rsa, sha1
{Signature: 0x03, Hash: 0x02}, // ecdsa, sha1
{Signature: 0x01, Hash: 0x04}, // rsa, sha256
{Signature: 0x01, Hash: 0x05}, // rsa, sha384
{Signature: 0x01, Hash: 0x06}, // rsa, sha512
}
}
tlsConn := scan.scanner.config.TLSFlags.GetWrappedConnection(outer, cfg)
@ -428,14 +437,14 @@ func getHTTPURL(https bool, host string, port uint16, endpoint string) string {
proto = "http"
}
if protoToPort[proto] == port && strings.Contains(host, ":") {
//If the host has a ":" in it, assume literal IPv6 address
// If the host has a ":" in it, assume literal IPv6 address
return proto + "://[" + host + "]" + endpoint
} else if protoToPort[proto] == port {
//Otherwise, just concatenate host and endpoint
// Otherwise, just concatenate host and endpoint
return proto + "://" + host + endpoint
}
//For non-default ports, net.JoinHostPort will handle brackets for IPv6 literals
// For non-default ports, net.JoinHostPort will handle brackets for IPv6 literals
return proto + "://" + net.JoinHostPort(host, strconv.FormatUint(uint64(port), 10)) + endpoint
}
@ -507,18 +516,20 @@ func (scan *scan) Grab() *zgrab2.ScanError {
err = urlError.Err
}
}
if err != nil {
switch err {
case ErrRedirLocalhost:
break
case ErrTooManyRedirects:
if scan.scanner.config.RedirectsSucceed {
return nil
}
return zgrab2.NewScanError(zgrab2.SCAN_APPLICATION_ERROR, err)
default:
return zgrab2.DetectScanError(err)
switch {
case errors.Is(err, ErrRedirLocalhost):
break
case errors.Is(err, ErrTooManyRedirects):
if scan.scanner.config.RedirectsSucceed {
return nil
}
return zgrab2.NewScanError(zgrab2.SCAN_APPLICATION_ERROR, err)
case err != nil:
return zgrab2.DetectScanError(err)
case resp == nil:
return zgrab2.NewScanError(zgrab2.SCAN_UNKNOWN_ERROR, errors.New("no response"))
default:
//
}
buf := new(bytes.Buffer)
@ -527,14 +538,15 @@ func (scan *scan) Grab() *zgrab2.ScanError {
if resp.ContentLength >= 0 && resp.ContentLength < maxReadLen {
readLen = resp.ContentLength
}
io.CopyN(buf, resp.Body, readLen)
_, _ = io.CopyN(buf, resp.Body, readLen)
encoder, encoding, certain := charset.DetermineEncoding(buf.Bytes(), resp.Header.Get("content-type"))
bodyText := ""
decodedSuccessfully := false
decoder := encoder.NewDecoder()
//"windows-1252" is the default value and will likely not decode correctly
// "windows-1252" is the default value and will likely not decode correctly
if certain || encoding != "windows-1252" {
decoded, decErr := decoder.Bytes(buf.Bytes())

View File

@ -4,12 +4,14 @@ package jarm
import (
_ "fmt"
jarm "github.com/RumbleDiscovery/jarm-go"
"github.com/zmap/zgrab2"
"log"
"net"
"strings"
"time"
"github.com/RumbleDiscovery/jarm-go"
"github.com/zmap/zgrab2"
)
// Flags give the command-line flags for the banner module.
@ -29,7 +31,7 @@ type Scanner struct {
type Results struct {
Fingerprint string `json:"fingerprint"`
error string `json:"error,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterModule is called by modules/banner.go to register the scanner.

View File

@ -12,6 +12,7 @@ import (
"time"
"github.com/sirupsen/logrus"
"github.com/zmap/zgrab2"
)
@ -48,7 +49,7 @@ const (
// the whole request.
TDSStatusEOM = 0x01
// TDSStatusIgnore: Ignore this event (0x01 MUST also be set).
// TDSStatusIgnore is a toggle to ignore this event (0x01 MUST also be set).
// Client-to-server.
TDSStatusIgnore = 0x02
@ -59,7 +60,7 @@ const (
// Client-to-server.
TDSStatusResetConnection = 0x08
// Reset the connection before processing event but do not modify the
// TDSStatusResetConnectionSkipTran enables resetting the connection before processing event but do not modify the
// transaction state. This status bit MUST NOT be set in conjunction with
// the RESETCONNECTION bit.
// Client-to-server.
@ -235,6 +236,7 @@ type ServerVersion struct {
// Decode a VERSION response and return the parsed ServerVersion struct
// As defined in the MSDN docs, these come from token 0:
//
// VERSION -- UL_VERSION = ((US_BUILD<<16)|(VER_SQL_MINOR<<8)|( VER_SQL_MAJOR))
func decodeServerVersion(buf []byte) *ServerVersion {
if len(buf) != 6 {
@ -922,12 +924,12 @@ func NewConnection(conn net.Conn) *Connection {
func (connection *Connection) Login() {
panic("unimplemented")
// TODO: send login
if connection.getEncryptMode() != EncryptModeOn {
/*if connection.getEncryptMode() != EncryptModeOn {
// Client was only using encryption for login, so switch back to rawConn
connection.tdsConn = &tdsConnection{conn: connection.rawConn, enabled: true, session: connection}
// tdsConnection.Write(rawData) -> net.Conn.Write(header + rawData)
// conn.Read() -> header + rawData -> tdsConnection.Read() -> rawData
}
}*/
}
// getEncryptMode returns the EncryptMode enum returned by the server in the

42
tls.go
View File

@ -4,7 +4,7 @@ import (
"encoding/base64"
"encoding/csv"
"fmt"
"io/ioutil"
"io"
"net"
"os"
"strconv"
@ -25,7 +25,7 @@ import (
// myModule.netConn = tlsConnection
// result.tls = tlsConnection.GetLog()
// Common flags for TLS configuration -- include this in your module's ScanFlags implementation to use the common TLS code
// TLSFlags contains common flags for TLS configuration -- include this in your module's ScanFlags implementation to use the common TLS code
// Adapted from modules/ssh.go
type TLSFlags struct {
Config *tls.Config // Config is ready to use TLS configuration
@ -139,7 +139,7 @@ func (t *TLSFlags) GetTLSConfigForTarget(target *ScanTarget) (*tls.Config, error
if fd, err = os.Open(t.RootCAs); err != nil {
log.Fatal(err)
}
caBytes, readErr := ioutil.ReadAll(fd)
caBytes, readErr := io.ReadAll(fd)
if readErr != nil {
log.Fatal(err)
}
@ -266,7 +266,7 @@ func (t *TLSFlags) GetTLSConfigForTarget(target *ScanTarget) (*tls.Config, error
}
type TLSConnection struct {
tls.Conn
*tls.Conn
flags *TLSFlags
log *TLSLog
}
@ -278,40 +278,40 @@ type TLSLog struct {
HeartbleedLog *tls.Heartbleed `json:"heartbleed_log,omitempty"`
}
func (z *TLSConnection) GetLog() *TLSLog {
if z.log == nil {
z.log = &TLSLog{}
func (tconn *TLSConnection) GetLog() *TLSLog {
if tconn.log == nil {
tconn.log = &TLSLog{}
}
return z.log
return tconn.log
}
func (z *TLSConnection) Handshake() error {
log := z.GetLog()
if z.flags.Heartbleed {
func (tconn *TLSConnection) Handshake() error {
logr := tconn.GetLog()
if tconn.flags.Heartbleed {
buf := make([]byte, 256)
defer func() {
log.HandshakeLog = z.Conn.GetHandshakeLog()
log.HeartbleedLog = z.Conn.GetHeartbleedLog()
logr.HandshakeLog = tconn.Conn.GetHandshakeLog()
logr.HeartbleedLog = tconn.Conn.GetHeartbleedLog()
}()
// TODO - CheckHeartbleed does not bubble errors from Handshake
_, err := z.CheckHeartbleed(buf)
_, err := tconn.CheckHeartbleed(buf)
if err == tls.HeartbleedError {
err = nil
}
return err
} else {
defer func() {
log.HandshakeLog = z.Conn.GetHandshakeLog()
log.HeartbleedLog = nil
logr.HandshakeLog = tconn.Conn.GetHandshakeLog()
logr.HeartbleedLog = nil
}()
return z.Conn.Handshake()
return tconn.Conn.Handshake()
}
}
// Close the underlying connection.
func (conn *TLSConnection) Close() error {
return conn.Conn.Close()
func (tconn *TLSConnection) Close() error {
return tconn.Conn.Close()
}
// Connect opens the TCP connection to the target using the given configuration,
@ -332,7 +332,7 @@ func (t *TLSFlags) GetTLSConnection(conn net.Conn) (*TLSConnection, error) {
func (t *TLSFlags) GetTLSConnectionForTarget(conn net.Conn, target *ScanTarget) (*TLSConnection, error) {
cfg, err := t.GetTLSConfigForTarget(target)
if err != nil {
return nil, fmt.Errorf("Error getting TLSConfig for options: %s", err)
return nil, fmt.Errorf("error getting TLSConfig for options: %s", err)
}
return t.GetWrappedConnection(conn, cfg), nil
}
@ -340,7 +340,7 @@ func (t *TLSFlags) GetTLSConnectionForTarget(conn net.Conn, target *ScanTarget)
func (t *TLSFlags) GetWrappedConnection(conn net.Conn, cfg *tls.Config) *TLSConnection {
tlsClient := tls.Client(conn, cfg)
wrappedClient := TLSConnection{
Conn: *tlsClient,
Conn: tlsClient,
flags: t,
}
return &wrappedClient