Example #1
0
// dnsRoundTripUDP implements the dnsRoundTrip interface for RFC 1035's
// "UDP usage" transport mechanism. c should be a packet-oriented connection,
// such as a *UDPConn.
func dnsRoundTripUDP(c io.ReadWriter, query *dnsMsg) (*dnsMsg, error) {
	b, ok := query.Pack()
	if !ok {
		return nil, errors.New("cannot marshal DNS message")
	}
	if _, err := c.Write(b); err != nil {
		return nil, err
	}

	b = make([]byte, 512) // see RFC 1035
	for {
		n, err := c.Read(b)
		if err != nil {
			return nil, err
		}
		resp := &dnsMsg{}
		if !resp.Unpack(b[:n]) || !resp.IsResponseTo(query) {
			// Ignore invalid responses as they may be malicious
			// forgery attempts. Instead continue waiting until
			// timeout. See golang.org/issue/13281.
			continue
		}
		return resp, nil
	}
}
Example #2
0
func negotiateMethod(c Context, rw io.ReadWriter) {
	rw.Write(methodRequest(proxy.MethodNoPassword))
	if _, err := rw.Read(make([]byte, 3)); err != nil {
		c.Error(err)
	}
	return
}
Example #3
0
// dnsRoundTripTCP implements the dnsRoundTrip interface for RFC 1035's
// "TCP usage" transport mechanism. c should be a stream-oriented connection,
// such as a *TCPConn.
func dnsRoundTripTCP(c io.ReadWriter, query *dnsMsg) (*dnsMsg, error) {
	b, ok := query.Pack()
	if !ok {
		return nil, errors.New("cannot marshal DNS message")
	}
	l := len(b)
	b = append([]byte{byte(l >> 8), byte(l)}, b...)
	if _, err := c.Write(b); err != nil {
		return nil, err
	}

	b = make([]byte, 1280) // 1280 is a reasonable initial size for IP over Ethernet, see RFC 4035
	if _, err := io.ReadFull(c, b[:2]); err != nil {
		return nil, err
	}
	l = int(b[0])<<8 | int(b[1])
	if l > len(b) {
		b = make([]byte, l)
	}
	n, err := io.ReadFull(c, b[:l])
	if err != nil {
		return nil, err
	}
	resp := &dnsMsg{}
	if !resp.Unpack(b[:n]) {
		return nil, errors.New("cannot unmarshal DNS message")
	}
	if !resp.IsResponseTo(query) {
		return nil, errors.New("invalid DNS response")
	}
	return resp, nil
}
Example #4
0
func (r *Receiver) handleTransfer(conn io.ReadWriter) (
	transfer.TransferResults, error,
) {
	if _, err := conn.Write([]byte("ok")); err != nil {
		return transfer.TransferResults{}, err
	}

	res := transfer.TransferResults{}
	buffer := make([]byte, 1024)

	startTime := time.Now()
	for {
		n, err := conn.Read(buffer)
		if err != nil { // done reading
			break
		}

		res.BytesSent += uint32(n)
		res.Checksum = crc32.Update(res.Checksum, crc32.IEEETable, buffer)
	}
	endTime := time.Now()

	res.Duration = endTime.Sub(startTime)

	return res, nil
}
Example #5
0
// receiverEncHandshake negotiates a session token on conn.
// it should be called on the listening side of the connection.
//
// prv is the local client's private key.
// token is the token from a previous session with this node.
func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
	authMsg := new(authMsgV4)
	authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
	if err != nil {
		return s, err
	}
	h := new(encHandshake)
	if err := h.handleAuthMsg(authMsg, prv); err != nil {
		return s, err
	}

	authRespMsg, err := h.makeAuthResp()
	if err != nil {
		return s, err
	}
	var authRespPacket []byte
	if authMsg.gotPlain {
		authRespPacket, err = authRespMsg.sealPlain(h)
	} else {
		authRespPacket, err = sealEIP8(authRespMsg, h)
	}
	if err != nil {
		return s, err
	}
	if _, err = conn.Write(authRespPacket); err != nil {
		return s, err
	}
	return h.secrets(authPacket, authRespPacket)
}
Example #6
0
File: actions.go Project: wwek/ncgo
//throwBytes chucks bytes at the remote server then listens for a response
func throwBytes(conn io.ReadWriter, count uint64) error {
	var writeBytes uint64
	var b []byte
	buff := make([]byte, 128)
	for writeBytes < count {
		if (count - writeBytes) >= uint64(len(dataBlock)) {
			b = dataBlock
		} else {
			b = dataBlock[0:(count - writeBytes)]
		}
		n, err := conn.Write(b)
		if err != nil {
			return err
		}
		writeBytes += uint64(n)
	}
	//read the response
	n, err := conn.Read(buff)
	if err != nil {
		return err
	}
	if n == 0 {
		return fmt.Errorf("Failed to get OK on upload")
	}
	if !strings.HasPrefix(string(buff[0:n]), "OK ") {
		return fmt.Errorf("Failed to get OK on upload")
	}
	return nil
}
Example #7
0
func handShake(rw io.ReadWriter) error {
	// version(1)+numMethods(1)+[256]methods
	buff := make([]byte, 258)
	n, err := io.ReadAtLeast(rw, buff, 2)
	if err != nil {
		return err
	}

	// version
	if buff[0] != 5 {
		return errors.New("socks unsuported version")
	}

	// numMethods
	numMethod := int(buff[1])

	// methods
	numMethod += 2
	if n <= numMethod {
		if _, err = io.ReadFull(rw, buff[n:numMethod]); err != nil {
			return err
		}
	}
	fmt.Println("Socks5: Step 1 -> ", buff[:numMethod])

	// return data
	buff[1] = 0 // no authentication
	if _, err := rw.Write(buff[:2]); err != nil {
		return err
	}
	fmt.Println("Socks5: Step 1 <- ", buff[:2])

	return nil
}
Example #8
0
// swapKeys generates a public/private key pair and swaps the public key with
// a corresponding call to swapKeys over the given ReadWriter.
//
// swapKeys returns the private key generated locally and the public key of it's
// counterpart.
func swapKeys(rw io.ReadWriter) (priv, peer *[32]byte, err error) {
	// Always return nil for the keys if there is an error
	defer func() {
		if err != nil {
			priv, peer = nil, nil
		}
	}()
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return
	}

	// Write our public key
	werr := make(chan error)
	go func() {
		_, err := rw.Write(pub[:])
		werr <- err
	}()
	defer func() {
		if err == nil {
			err = <-werr
		}
	}()

	// Read their public key
	peer = new([32]byte)
	_, err = io.ReadFull(rw, peer[:])
	return
}
Example #9
0
func performConnect(backend string, frontconn io.ReadWriter) {
	log.Printf("trying to connect to %s...\n", backend)
	backconn, err := net.Dial("tcp", backend)
	if err != nil {
		log.Printf("failed to connect to %s: %s\n", backend, err)
		frontconn.Write(errorReplyConnect(0x05))
		return
	}

	backaddr := backconn.RemoteAddr().String()
	log.Println("CONNECTED backend", backconn, backaddr)
	defer func() {
		backconn.Close()
		log.Println("DISCONNECTED backend", backconn, backaddr)
	}()

	// reply to the CONNECT command
	buf := make([]byte, 10)
	copy(buf, []byte{0x05, 0x00, 0x00, 0x01})
	packNetAddr(backconn.RemoteAddr(), buf[4:])
	frontconn.Write(buf)

	// bridge connection
	shutdown := make(chan bool, 2)
	go common.IOBridge(frontconn, backconn, shutdown)
	go common.IOBridge(backconn, frontconn, shutdown)

	<-shutdown
}
Example #10
0
// Query writes a question to rw and waits for an answer.  It will pass the
// answer into the verify function.  Verify should check the answer for
// validity, returning a failure reason as a string, or an empty string if the
// answer is valid.
func QueryVerify(
	rw io.ReadWriter,
	question []byte,
	verify func(string) (string, error),
) (answer string, err error) {
	scanner := bufio.NewScanner(rw)
	for {
		_, err = rw.Write(question)
		if err != nil {
			return "", err
		}

		if !scanner.Scan() {
			if err = scanner.Err(); err != nil {
				return "", err
			}
			return "", fmt.Errorf("Connection closed")
		}
		answer = scanner.Text()
		failure, err := verify(answer)
		if err != nil {
			return "", err
		}
		if failure == "" {
			return answer, nil
		}
		_, err = fmt.Fprintln(rw, failure)
		if err != nil {
			return "", err
		}
	}
}
Example #11
0
// initiatorEncHandshake negotiates a session token on conn.
// it should be called on the dialing side of the connection.
//
// prv is the local client's private key.
func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
	h := &encHandshake{initiator: true, remoteID: remoteID}
	authMsg, err := h.makeAuthMsg(prv, token)
	if err != nil {
		return s, err
	}
	var authPacket []byte
	if configSendEIP {
		authPacket, err = sealEIP8(authMsg, h)
	} else {
		authPacket, err = authMsg.sealPlain(h)
	}
	if err != nil {
		return s, err
	}
	if _, err = conn.Write(authPacket); err != nil {
		return s, err
	}

	authRespMsg := new(authRespV4)
	authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
	if err != nil {
		return s, err
	}
	if err := h.handleAuthResp(authRespMsg); err != nil {
		return s, err
	}
	return h.secrets(authPacket, authRespPacket)
}
Example #12
0
// ServeAgent serves the agent protocol on the given connection. It
// returns when an I/O error occurs.
func ServeAgent(agent Agent, c io.ReadWriter) error {
	s := &server{agent}

	var length [4]byte
	for {
		if _, err := io.ReadFull(c, length[:]); err != nil {
			return err
		}
		l := binary.BigEndian.Uint32(length[:])
		if l > maxAgentResponseBytes {
			// We also cap requests.
			return fmt.Errorf("agent: request too large: %d", l)
		}

		req := make([]byte, l)
		if _, err := io.ReadFull(c, req); err != nil {
			return err
		}

		repData := s.processRequestBytes(req)
		if len(repData) > maxAgentResponseBytes {
			return fmt.Errorf("agent: reply too large: %d bytes", len(repData))
		}

		binary.BigEndian.PutUint32(length[:], uint32(len(repData)))
		if _, err := c.Write(length[:]); err != nil {
			return err
		}
		if _, err := c.Write(repData); err != nil {
			return err
		}
	}
}
Example #13
0
//从io接口中读取指定结束符数据
func WriteAndReadWithTer(rw io.ReadWriter, writedata []byte, ter []byte, timeout int) ([]byte, error) {
	p := []byte(writedata)
	_, err := rw.Write(p)
	if err != nil {
		return nil, err
	}
	return ReadWithTer(rw, ter, timeout)
}
Example #14
0
func (r *Receiver) handleBusy(conn io.ReadWriter) error {
	r.logger.Debugf("Server is busy!")
	if _, err := conn.Write([]byte("i-am-busy")); err != nil {
		return err
	}

	return nil
}
Example #15
0
//从io接口中读取指定长度数据
func WriteAndReadLen(rw io.ReadWriter, writedata []byte, readlen int, timeout int) ([]byte, error) {
	p := []byte(writedata)
	_, err := rw.Write(p)
	if err != nil {
		return nil, err
	}
	return ReadWithLen(rw, readlen, timeout)
}
Example #16
0
func echoOnce(rw io.ReadWriter) error {
	buf := make([]byte, 256)
	n, err := rw.Read(buf)
	if err != nil {
		return err
	}
	_, err = rw.Write(buf[:n])
	return err
}
Example #17
0
// exchangeKeys performs a key exchange with a remote peer
// and returns peer's public key after successfull exchange.
func exchangeKeys(conn io.ReadWriter, pub *[32]byte) (*[32]byte, error) {
	var ppub [32]byte
	if _, err := conn.Write(pub[:]); err != nil {
		return nil, err
	}
	if _, err := conn.Read(ppub[:]); err != nil {
		return nil, err
	}
	return &ppub, nil
}
Example #18
0
func (p *Proxy) pipe(src, dst io.ReadWriter) {
	islocal := src == p.lconn

	var dataDirection string
	if islocal {
		dataDirection = ">>> %d bytes sent%s"
	} else {
		dataDirection = "<<< %d bytes recieved%s"
	}

	var byteFormat string
	if p.OutputHex {
		byteFormat = "%x"
	} else {
		byteFormat = "%s"
	}

	//directional copy (64k buffer)
	buff := make([]byte, 0xffff)
	for {
		n, err := src.Read(buff)
		if err != nil {
			p.err("Read failed '%s'\n", err)
			return
		}
		b := buff[:n]

		//execute match
		if p.Matcher != nil {
			p.Matcher(b)
		}

		//execute replace
		if p.Replacer != nil {
			b = p.Replacer(b)
		}

		//show output
		p.Log.Debug(dataDirection, n, "")
		p.Log.Trace(byteFormat, b)

		//write out result
		n, err = dst.Write(b)
		if err != nil {
			p.err("Write failed '%s'\n", err)
			return
		}
		if islocal {
			p.sentBytes += uint64(n)
		} else {
			p.receivedBytes += uint64(n)
		}
	}
}
Example #19
0
func (s SimpleAuth) Connect(rw io.ReadWriter) (io.ReadWriter, error) {
	out := []byte(s.User)
	out = append(out, 0)
	out = append(out, s.Pass...)

	if _, err := rw.Write(out); err != nil {
		return nil, err
	}

	return nil, nil
}
Example #20
0
// exchangeKeys performs the exchange of the keys
// by writing the public key into the data stream first and
// then reading the shared key from the data stream.
func exchangeKeys(pub, peerPub *[32]byte, rw io.ReadWriter) error {
	if _, err := rw.Write(pub[:]); err != nil {
		return err
	}

	if _, err := rw.Read(peerPub[:]); err != nil {
		return err
	}

	return nil
}
Example #21
0
// CopyToWebsocket copies pipe data to/from a websocket.  It blocks.
func (p *pipe) CopyToWebsocket(end io.ReadWriter, conn *websocket.Conn) error {
	p.mtx.Lock()
	if p.closed {
		p.mtx.Unlock()
		return nil
	}
	p.wg.Add(1)
	p.mtx.Unlock()
	defer p.wg.Done()

	errors := make(chan error, 1)

	// Read-from-UI loop
	go func() {
		for {
			_, buf, err := conn.ReadMessage() // TODO type should be binary message
			if err != nil {
				errors <- err
				return
			}

			if _, err := end.Write(buf); err != nil {
				errors <- err
				return
			}
		}
	}()

	// Write-to-UI loop
	go func() {
		buf := make([]byte, 1024)
		for {
			n, err := end.Read(buf)
			if err != nil {
				errors <- err
				return
			}

			if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {
				errors <- err
				return
			}
		}
	}()

	// block until one of the goroutines exits
	// this convoluted mechanism is to ensure we only close the websocket once.
	select {
	case err := <-errors:
		return err
	case <-p.quit:
		return nil
	}
}
Example #22
0
func (us *UnixSock) processBuffer(fd io.ReadWriter) {
	var buf [1024]byte

	for {
		n, err := fd.Read(buf[0:])
		if err != nil || n == 0 {
			break
		}
		us.data <- pipe.NewSimpleChunk(buf[0:n])
	}
}
Example #23
0
func fsm_msg(conn io.ReadWriter, log io.Writer, args string) (next transition, rest string, err error) {
	if !strings.HasSuffix(args, "\n") {
		args = args + "\n"
	}
	_, err = fmt.Fprintf(log, "Message: %s", args)
	if err == nil {
		conn.Write(TEXT_message_logged)
	} else {
		conn.Write(TEXT_message_failed)
	}
	return fsm_start, "", err
}
Example #24
0
func (r *Receiver) handleTransfer(conn io.ReadWriter) (
	transfer.TransferResults, error,
) {
	msg := fmt.Sprintf("ok - %d", r.iperfPort)
	if _, err := conn.Write([]byte(msg)); err != nil {
		return transfer.TransferResults{}, err
	}

	return runner.ListenAndServe(runner.ServerConfig{
		ListenPort: r.iperfPort,
	})
}
Example #25
0
func runEcho(fd io.ReadWriter, done chan<- int) {
	var buf [1024]byte;

	for {
		n, err := fd.Read(&buf);
		if err != nil || n == 0 {
			break
		}
		fd.Write(buf[0:n]);
	}
	done <- 1;
}
Example #26
0
// handshake sends our public key and returns the peer public key.
// The key exchange is done in plain text as allowed by the exercise.
func handshake(rw io.ReadWriter, pub *[32]byte) (*[32]byte, error) {
	// send our public key
	if _, err := rw.Write(pub[:]); err != nil {
		return nil, err
	}
	// receive peer public key
	var peerpub [32]byte
	if _, err := io.ReadFull(rw, peerpub[:]); err != nil {
		return nil, err
	}
	return &peerpub, nil
}
Example #27
0
func runEcho(fd io.ReadWriter, done chan<- int) {
	var buf [1024]byte

	for {
		n, err := fd.Read(buf[0:])
		if err != nil || n == 0 || string(buf[:n]) == "END" {
			break
		}
		fd.Write(buf[0:n])
	}
	done <- 1
}
Example #28
0
func exchangeKeys(pub *[32]byte, conn io.ReadWriter) (*[32]byte, error) {
	_, err := conn.Write(pub[:])
	if err != nil {
		return nil, err
	}

	otherPub := [32]byte{}
	_, err = conn.Read(otherPub[:])
	if err != nil {
		return nil, err
	}
	return &otherPub, nil
}
Example #29
0
func exchangeKeys(conn io.ReadWriter, publicKey []byte) (*[32]byte, error) {
	var peerPublicKey [32]byte

	if _, err := conn.Write(publicKey); err != nil {
		return nil, err
	}

	if _, err := io.ReadFull(conn, peerPublicKey[:]); err != nil {
		return nil, err
	}

	return &peerPublicKey, nil
}
Example #30
0
// submitTPMRequest sends a structure to the TPM device file and gets results
// back, interpreting them as a new provided structure.
func submitTPMRequest(rw io.ReadWriter, tag uint16, ord uint32, in []interface{}, out []interface{}) (uint32, error) {
	if rw == nil {
		return 0, errors.New("nil TPM handle")
	}

	ch := commandHeader{tag, 0, ord}
	inb, err := packWithHeader(ch, in)
	if err != nil {
		return 0, err
	}

	if _, err := rw.Write(inb); err != nil {
		return 0, err
	}

	// Try to read the whole thing, but handle the case where it's just a
	// ResponseHeader and not the body, since that's what happens in the error
	// case.
	var rh responseHeader
	rhSize := binary.Size(rh)
	outb := make([]byte, maxTPMResponse)
	outlen, err := rw.Read(outb)
	if err != nil {
		return 0, err
	}

	// Resize the buffer to match the amount read from the TPM.
	outb = outb[:outlen]
	if err := unpack(outb[:rhSize], []interface{}{&rh}); err != nil {
		return 0, err
	}

	// Check success before trying to read the rest of the result.
	// Note that the command tag and its associated response tag differ by 3,
	// e.g., tagRQUCommand == 0x00C1, and tagRSPCommand == 0x00C4.
	if rh.Res != 0 {
		return rh.Res, tpmError(rh.Res)
	}

	if rh.Tag != ch.Tag+3 {
		return 0, errors.New("inconsistent tag returned by TPM. Expected " + strconv.Itoa(int(ch.Tag+3)) + " but got " + strconv.Itoa(int(rh.Tag)))
	}

	if rh.Size > uint32(rhSize) {
		if err := unpack(outb[rhSize:], out); err != nil {
			return 0, err
		}
	}

	return rh.Res, nil
}