func run(ctx context.Context, rendID *[32]byte, seed []byte, identifiable bool) error { tr, err := torch.New(ctx, proxy.FromEnvironment()) if err != nil { return err } defer tr.Stop() rendNode := tr.WithDirectory(func(dir *directory.Directory) interface{} { shortInfos := make([]*directory.ShortNodeInfo, len(dir.Routers)) for i, r := range dir.Routers { shortInfos[i] = r.ShortNodeInfo } rendShort := nd.Pick(shortInfos, rendID) for _, r := range dir.Routers { if r.ShortNodeInfo == rendShort { return r } } panic("unreachable") }).(*directory.NodeInfo) // when we talk to a website over TOR, the website knows what the third hop // is. Therefore our converstion partner may as well. nodes := make([]*directory.NodeInfo, 0, 3) if !identifiable { nodes = append(nodes, tr.Pick(weighRelayWith, nil)) nodes = append(nodes, tr.Pick(weighRelayWith, nil)) } nodes = append(nodes, rendNode) tc1, c1, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc1.Close() tc2, c2, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc2.Close() ndc, err := nd.Handshake(ctx, c1, c2, seed) var _ fnet.FrameConn = (ndc) fmt.Printf("%#v\n", ndc.Bit) return nil }
// HTTPClient returns a net/http client that respects proxy settings from the // environmnent. Supported environmnent variables: // "http_proxy", "https_proxy", "all_proxy", and "no_proxy". func HTTPClient() *http.Client { if os.Getenv("all_proxy") != "" { return &http.Client{ Transport: &http.Transport{Dial: proxy.FromEnvironment().Dial}, } } return http.DefaultClient }
// Connect connects to the host by using the specified port or the default one if the value is <=0. func (ftp *FTP) Connect(host string, port int, socks5ProxyUrl string) (resp *Response, err error) { if len(host) == 0 { return nil, errors.New("The host must be specified") } ftp.Host = host if port <= 0 { port = DefaultFtpPort } addr := fmt.Sprintf("%s:%d", ftp.Host, ftp.Port) // use the system proxy if emtpy if socks5ProxyUrl == "" { ftp.writeInfo("using environment proxy, url: ", os.Getenv("all_proxy")) ftp.dialer = proxy.FromEnvironment() } else { ftp.dialer = proxy.Direct if u, err1 := url.Parse(socks5ProxyUrl); err1 == nil { p, err2 := proxy.FromURL(u, proxy.Direct) if err2 == nil { ftp.dialer = p } } } err = ftp.NewConn(addr) if err != nil { return } ftp.writeInfo("host:", ftp.Host, " port:", strconv.Itoa(ftp.Port), " proxy enabled:", ftp.dialer != proxy.Direct) // NOTE: this is an absolute time that needs refreshing after each READ/WRITE net operation //ftp.conn.conn.SetDeadline(getTimeoutInMsec(ftp.timeoutInMsec)) if resp, err = ftp.Read(NONE_FTP_CMD); err != nil { return } ftp.welcome = resp.Message ftp.writeInfo("Successfully connected on local address:", ftp.conn.LocalAddr()) return }
func Socks5Client(timeout time.Duration, user, password, ip string) *http.Client { // ip like that 1.1.1.1:29840 auth := &proxy.Auth{ User: user, Password: password, } forward := proxy.FromEnvironment() dailer, err := proxy.SOCKS5("tcp", ip, auth, forward) if err != nil { log.Println("proxy socks5 client error: ", err) return nil } return &http.Client{ Transport: &http.Transport{ Dial: dailer.Dial, DisableKeepAlives: false, ResponseHeaderTimeout: timeout, DisableCompression: false, }, } }
func main() { var smx, socks, body, file_location, file_name, from, from_name, marker, head, html, attachment, subject, to, to_name string var mx []*net.MX var conn net.Conn ief, _ := net.Interfaces() fmt.Printf("%s \r\n", ief[1].HardwareAddr) //ief, _ := net.InterfaceByName("eth1") addrs, _ := ief[1].Addrs() tcpAddr := &net.TCPAddr{ IP: addrs[0].(*net.IPNet).IP, } fmt.Println(tcpAddr) //set necessary variables socks = "62.109.20.93:3678" from = "*****@*****.**" from_name = "Nissan" to = "*****@*****.**" to_name = "Foryou" subject = "Check out my test email" body = "Это тестовое письмо. На него отвечать не нужно.\r\n" file_location = "/home/aagafonov/PhpstormProjects/ly/public/img/cake/" file_name = "StickAndCarrot.jpg" // ------------------------------------------------------------------------------- //s := net.Dialer{LocalAddr: addrs[0]} s, err := proxy.SOCKS5("tcp", socks, nil, proxy.FromEnvironment()) if err != nil { fmt.Printf("Socks failed: %v\r\n", err) } domain := strings.Split(to, "@")[1] fmt.Printf("Domain: %s\r\n", domain) mx, err = net.LookupMX(domain) if err != nil { fmt.Printf("LookupMX failed: %v\r\n", err) } else { for i := range mx { smx := net.JoinHostPort(mx[i].Host, "25") fmt.Printf("Connect to %v ...\r\n", smx) // Set ip (from MX records) and port mail server conn, err = s.Dial("tcp", smx) if err != nil { fmt.Printf("Dial failed: %v\r\n", err) } else { break } } } if err != nil { fmt.Printf("Connect: %v\r\n", err) } host, _, _ := net.SplitHostPort(smx) c, err := smtp.NewClient(conn, host) if err != nil { fmt.Printf("New client failed: %v\r\n", err) } myHost, _, _ := net.SplitHostPort(socks) if err := c.Hello(myHost); err != nil { fmt.Printf("Hello: %v\r\n", err) } marker = makeMarker() // Set the sender and recipient first if err := c.Mail(from); err != nil { fmt.Printf("Mail: %v\r\n", err) } if err := c.Rcpt(to); err != nil { fmt.Printf("Rcpt: %v\r\n", err) } hd := mailHead{ from, from_name, to, to_name, subject, } head = buildHead(hd, marker) //part 2 will be the body of the email (text or HTML) html = buildBody(body, marker) att := mailAttachment{ file_location, file_name, } attachment = buildAttachment(att, marker) msg := head + html + attachment //dkim.New() w, err := c.Data() if err != nil { fmt.Println("Data: %v", err) } _, err = fmt.Fprintf(w, msg) if err != nil { fmt.Println("Fprintf: %v", err) } err = w.Close() if err != nil { fmt.Println("Close: %v", err) } // Send the QUIT command and close the connection. err = c.Quit() if err != nil { fmt.Println("Quit: %v", err) } }
func run(ctx context.Context, rendID *[32]byte, seed []byte, identifiable bool, numStreams int, udpSourceListen, udpDestinationSend string) error { tr, err := torch.New(ctx, proxy.FromEnvironment()) if err != nil { return err } defer tr.Stop() rendNode := tr.WithDirectory(func(dir *directory.Directory) interface{} { shortInfos := make([]*directory.ShortNodeInfo, 0, len(dir.Routers)) for _, n := range dir.Routers { if n.Fast && n.Running && n.Stable && n.Valid && (n.Port == 443 || n.Port == 80) { shortInfos = append(shortInfos, n.ShortNodeInfo) } } rendShort := nd.Pick(shortInfos, rendID) for _, r := range dir.Routers { if r.ShortNodeInfo == rendShort { return r } } panic("unreachable") }).(*directory.NodeInfo) // when we talk to a website over TOR, the website knows what the third hop // is. Therefore our converstion partner may as well. nodes := make([]*directory.NodeInfo, 0, 3) if !identifiable { nodes = append(nodes, tr.Pick(weigh, nil)) nodes = append(nodes, tr.Pick(weigh, nil)) } nodes = append(nodes, rendNode) rr := fnet.NewRoundRobin(nd.FRAMESIZE) defer rr.Close() for i := 0; i < numStreams; i++ { seed_i := sha256.Sum256(append(append([]byte{}, seed...), byte(i))) tc1, c1, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc1.Close() tc2, c2, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc2.Close() ndc, err := nd.Handshake(ctx, c1, c2, seed_i[:]) if err != nil { return err } rr.AddConn(ndc) } udpFront, err := udp4rrtcp.Start(ctx, udpSourceListen, udpDestinationSend, rr) if err != nil { return err } defer udpFront.Stop() println("connected and running") <-ctx.Done() return nil }
func handleConnection(conn *ss.Conn) { var host string connCnt++ // this maybe not accurate, but should be enough if connCnt-nextLogConnCnt >= 0 { // XXX There's no xadd in the atomic package, so it's difficult to log // the message only once with low cost. Also note nextLogConnCnt maybe // added twice for current peak connection number level. log.Printf("Number of client connections reaches %d\n", nextLogConnCnt) nextLogConnCnt += logCntDelta } // function arguments are always evaluated, so surround debug statement // with if statement if debug { debug.Printf("new client %s->%s\n", conn.RemoteAddr().String(), conn.LocalAddr()) } closed := false defer func() { if debug { debug.Printf("closed pipe %s<->%s\n", conn.RemoteAddr(), host) } connCnt-- if !closed { conn.Close() } }() host, extra, err := getRequest(conn) if err != nil { log.Println("error getting request", conn.RemoteAddr(), conn.LocalAddr(), err) return } debug.Println("connecting", host) var dialer proxy.Dialer dialer = proxy.FromEnvironment() remote, err := dialer.Dial("tcp", host) if err != nil { if ne, ok := err.(*net.OpError); ok && (ne.Err == syscall.EMFILE || ne.Err == syscall.ENFILE) { // log too many open file error // EMFILE is process reaches open file limits, ENFILE is system limit log.Println("dial error:", err) } else { log.Println("error connecting to:", host, err) } return } defer func() { if !closed { remote.Close() } }() // write extra bytes read from if extra != nil { // debug.Println("getRequest read extra data, writing to remote, len", len(extra)) if _, err = remote.Write(extra); err != nil { debug.Println("write request extra error:", err) return } } if debug { debug.Printf("piping %s<->%s", conn.RemoteAddr(), host) } go ss.PipeThenClose(conn, remote) ss.PipeThenClose(remote, conn) closed = true return }
func dialerFromFlags() (proxy.Dialer, error) { if len(*proxyAddress) > 0 { return proxy.SOCKS5("tcp", string(*proxyAddress), nil, &proxy.Direct) } return proxy.FromEnvironment(), nil }
func run(ctx context.Context, rendID *[32]byte, seed []byte, identifiable bool, numStreams int, rnd *mathrand.Rand) error { tr, err := torch.New(ctx, proxy.FromEnvironment()) if err != nil { return err } defer tr.Stop() rendNode := tr.WithDirectory(func(dir *directory.Directory) interface{} { shortInfos := make([]*directory.ShortNodeInfo, 0, len(dir.Routers)) for _, n := range dir.Routers { if n.Fast && n.Running && n.Stable && n.Valid && (n.Port == 443 || n.Port == 80) { shortInfos = append(shortInfos, n.ShortNodeInfo) } } rendShort := nd.Pick(shortInfos, rendID) for _, r := range dir.Routers { if r.ShortNodeInfo == rendShort { return r } } panic("unreachable") }).(*directory.NodeInfo) // when we talk to a website over TOR, the website knows what the third hop // is. Therefore our converstion partner may as well. nodes := make([]*directory.NodeInfo, 0, 3) if !identifiable { nodes = append(nodes, tr.Pick(weigh, rnd)) nodes = append(nodes, tr.Pick(weigh, rnd)) } nodes = append(nodes, rendNode) rr := fnet.NewRoundRobin(nd.FRAMESIZE) defer rr.Close() fmt.Println("plan:") for _, n := range nodes { fmt.Printf("%d\n", n.IP) } sending := false for i := 0; i < numStreams; i++ { seed_i := sha256.Sum256(append(append([]byte{}, seed...), byte(i))) tc1, c1, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc1.Close() tc2, c2, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes) if err != nil { return err } defer tc2.Close() ndc, err := nd.Handshake(ctx, c1, c2, seed_i[:]) // Arbitrarily choose one of the sides of the TOR connection to be the sender of the test data // By choosing the first ndc.bit if i == 0 { sending = ndc.Bit } if err != nil { return err } rr.AddConn(ndc) } println("connected and running") if sending { if err = clockstation.Run(ctx, rr, time.Tick(50*time.Millisecond)); err != nil { return fmt.Errorf("clockstation.Run: %s\n", err.Error()) } } else { if err = clockprinter.Run(ctx, rr); err != nil { fmt.Errorf("clockprinter.Run: %s\n", err.Error()) } } return nil <-ctx.Done() return nil }
import ( "net" "net/http" "os" "strings" "time" "golang.org/x/net/proxy" "github.com/syncthing/syncthing/lib/logger" "github.com/syncthing/syncthing/lib/osutil" ) var ( l = logger.DefaultLogger.NewFacility("dialer", "Dialing connections") dialer = proxy.FromEnvironment() usingProxy = dialer != proxy.Direct ) func init() { l.SetDebug("dialer", strings.Contains(os.Getenv("STTRACE"), "dialer") || os.Getenv("STTRACE") == "all") if usingProxy { http.DefaultTransport = &http.Transport{ Dial: Dial, Proxy: http.ProxyFromEnvironment, TLSHandshakeTimeout: 10 * time.Second, } // Defer this, so that logging gets setup. go func() { time.Sleep(500 * time.Millisecond)
func (m *MailData) SendMail() error { var smx string var mx []*net.MX var conn net.Conn if m.Iface == "" { // default interface m.n = net.Dialer{} } else { if m.Iface[0:8] == "socks://" { m.Iface = m.Iface[8:] var err error m.s, err = proxy.SOCKS5("tcp", m.Iface, nil, proxy.FromEnvironment()) if err != nil { return err } } else { connectAddr := net.ParseIP(m.Iface) tcpAddr := &net.TCPAddr{ IP: connectAddr, } m.n = net.Dialer{LocalAddr: tcpAddr} } } //ToDo cache MX servers // punycode convert domain, err := idna.ToASCII(strings.Split(m.To, "@")[1]) if err != nil { return errors.New(fmt.Sprintf("Domain name failed: %v\r\n", err)) } m.To = strings.Split(m.To, "@")[0] + "@" + domain mx, err = net.LookupMX(domain) if err != nil { return errors.New(fmt.Sprintf("LookupMX failed: %v\r\n", err)) } else { for i := range mx { smx := net.JoinHostPort(mx[i].Host, "25") // Set ip (from MX records) and port mail server if m.s != nil { conn, err = m.s.Dial("tcp", smx) } else { conn, err = m.n.Dial("tcp", smx) } if err == nil { defer conn.Close() break } } } if err != nil { return err } host, _, _ := net.SplitHostPort(smx) c, err := smtp.NewClient(conn, host) if err != nil { return err } if err := c.Hello(m.Host); err != nil { return err } // Set the sender and recipient first if err := c.Mail(m.From); err != nil { return err } if err := c.Rcpt(m.To); err != nil { return err } msg := m.makeMail() //dkim.New() w, err := c.Data() if err != nil { return err } _, err = fmt.Fprintf(w, msg) if err != nil { return err } err = w.Close() if err != nil { return err } // Send the QUIT command and close the connection. return c.Quit() }
// Send email func (m *MailData) Send() error { // trim space m.To_email = strings.TrimSpace(m.To_email) // punycode convert splitEmail := strings.Split(m.To_email, "@") if len(splitEmail) != 2 { return errors.New(fmt.Sprintf("Bad email")) } domain, err := idna.ToASCII(splitEmail[1]) if err != nil { return errors.New(fmt.Sprintf("Domain name failed: %v", err)) } m.To_email = strings.Split(m.To_email, "@")[0] + "@" + domain if m.Iface == "" { // default interface m.netConn = net.Dialer{} } else { if m.Iface[0:8] == "socks://" { m.Iface = m.Iface[8:] var err error m.socksConn, err = proxy.SOCKS5("tcp", m.Iface, nil, proxy.FromEnvironment()) if err != nil { return err } } else { connectAddr := net.ParseIP(m.Iface) tcpAddr := &net.TCPAddr{ IP: connectAddr, } m.netConn = net.Dialer{LocalAddr: tcpAddr} } } start := time.Now() //record, err := net.LookupMX(c.domain) record, err := models.DomainGetMX(domain) if err != nil { return err } lookupTime := time.Since(start) start = time.Now() var serverMx string for i := range record { smx := net.JoinHostPort(record[i].Host, "25") if m.socksConn != nil { m.conn, err = m.socksConn.Dial("tcp", smx) } else { m.conn, err = m.netConn.Dial("tcp", smx) } if err == nil { serverMx = record[i].Host connTime := time.Since(start) fmt.Printf("Connect time to %s %s. Lookup time %s.\n\r", domain, connTime, lookupTime) break } } if err != nil { return err } defer m.conn.Close() // 5 minute by RFC m.conn.SetDeadline(time.Now().Add(5 * time.Minute)) c, err := smtp.NewClient(m.conn, serverMx) if err != nil { return errors.New(fmt.Sprintf("%v (NewClient)", err)) } if err := c.Hello(m.Host); err != nil { return errors.New(fmt.Sprintf("%v (Hello)", err)) } // Set the sender and recipient first if err := c.Mail(m.From_email); err != nil { return errors.New(fmt.Sprintf("%v (Mail)", err)) } if err := c.Rcpt(m.To_email); err != nil { return errors.New(fmt.Sprintf("%v (Rcpt)", err)) } w, err := c.Data() if err != nil { return errors.New(fmt.Sprintf("%v (Data)", err)) } _, err = fmt.Fprint(w, m.Data()) if err != nil { return errors.New(fmt.Sprintf("%v (SendData)", err)) } err = w.Close() if err != nil { return errors.New(fmt.Sprintf("%v (Close)", err)) } return c.Quit() }