func NewClient(proxyURL *url.URL, timeout int) (*http.Client, error) { client := &http.Client{} client.Timeout = time.Duration(timeout) * time.Second if proxyURL.Scheme == "http" { client.Transport = &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return proxyURL, nil }, } } else if proxyURL.Scheme == "socks5" { ph, err := proxy.FromURL(proxyURL, proxy.Direct) if err != nil { return nil, err } client.Transport = &http.Transport{ Dial: ph.Dial, } } else if proxyURL.Scheme == "socks4" { dialSocksProxy := socks.DialSocksProxy(socks.SOCKS4, proxyURL.Host) client.Transport = &http.Transport{ Dial: dialSocksProxy, } } else if proxyURL.Scheme == "socks4a" { dialSocksProxy := socks.DialSocksProxy(socks.SOCKS4A, proxyURL.Host) client.Transport = &http.Transport{ Dial: dialSocksProxy, } } else { return nil, fmt.Errorf("unknow proxy scheme:%s", proxyURL.Scheme) } return client, nil }
func init() { proxyTransports["http"] = func(proxyURL *url.URL) (*http.Transport, error) { return &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return proxyURL, nil }, }, nil } proxyTransports["socks5"] = func(proxyURL *url.URL) (*http.Transport, error) { ph, err := proxy.FromURL(proxyURL, proxy.Direct) if err != nil { return nil, err } return &http.Transport{ Dial: ph.Dial, }, nil } proxyTransports["socks4"] = func(proxyURL *url.URL) (*http.Transport, error) { dialSocksProxy := socks.DialSocksProxy(socks.SOCKS4A, proxyURL.Host) return &http.Transport{ Dial: dialSocksProxy, }, nil } proxyTransports["socks4a"] = func(proxyURL *url.URL) (*http.Transport, error) { dialSocksProxy := socks.DialSocksProxy(socks.SOCKS4A, proxyURL.Host) return &http.Transport{ Dial: dialSocksProxy, }, nil } //shadowsocks proxyTransports["ss"] = func(proxyURL *url.URL) (*http.Transport, error) { if proxyURL.User == nil { return nil, fmt.Errorf("wrong shadowsocks uri,need method and passwd") } psw, _ := proxyURL.User.Password() cipher, err := ss.NewCipher(proxyURL.User.Username(), psw) if err != nil { return nil, err } serverAddr := proxyURL.Host return &http.Transport{ Dial: func(_, addr string) (net.Conn, error) { return ss.Dial(addr, serverAddr, cipher.Copy()) }, // DialTLS:func(_, addr string) (net.Conn, error) { // return ss.Dial(addr, serverAddr, cipher.Copy()) // }, }, nil } }
// 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 enroll(config *Config, term *terminal.Terminal) bool { var err error warn(term, "Enrolling new config file") var domain string for { term.SetPrompt("Account (i.e. [email protected], enter to quit): ") if config.Account, err = term.ReadLine(); err != nil || len(config.Account) == 0 { return false } parts := strings.SplitN(config.Account, "@", 2) if len(parts) != 2 { alert(term, "invalid username (want user@domain): "+config.Account) continue } domain = parts[1] break } term.SetPrompt("Enable debug logging to /tmp/xmpp-client-debug.log? ") if debugLog, err := term.ReadLine(); err != nil || debugLog != "yes" { info(term, "Not enabling debug logging...") } else { info(term, "Debug logging enabled...") config.RawLogFile = "/tmp/xmpp-client-debug.log" } term.SetPrompt("Use Tor?: ") if useTorQuery, err := term.ReadLine(); err != nil || useTorQuery != "yes" { info(term, "Not using Tor...") config.UseTor = false } else { info(term, "Using Tor...") config.UseTor = true } term.SetPrompt("File to import libotr private key from (enter to generate): ") var priv otr.PrivateKey for { importFile, err := term.ReadLine() if err != nil { return false } if len(importFile) > 0 { privKeyBytes, err := ioutil.ReadFile(importFile) if err != nil { alert(term, "Failed to open private key file: "+err.Error()) continue } if !priv.Import(privKeyBytes) { alert(term, "Failed to parse libotr private key file (the parser is pretty simple I'm afraid)") continue } break } else { info(term, "Generating private key...") priv.Generate(rand.Reader) break } } config.PrivateKey = priv.Serialize(nil) config.OTRAutoAppendTag = true config.OTRAutoStartSession = true config.OTRAutoTearDown = false // If we find ourselves here - we want to autoconfigure everything quickly if domain == "jabber.ccc.de" && config.UseTor == true { const torProxyURL = "socks5://127.0.0.1:9050" info(term, "It appears that you are using a well known server and we will use its Tor hidden service to connect.") config.Server = "okj7xc6j2szr2y75.onion" config.Port = 5222 config.Proxies = []string{torProxyURL} term.SetPrompt("> ") return true } if domain == "riseup.net" && config.UseTor == true { const torProxyURL = "socks5://127.0.0.1:9050" info(term, "It appears that you are using a well known server and we will use its Tor hidden service to connect.") config.Server = "ztmc4p37hvues222.onion" config.Port = 5222 config.Proxies = []string{torProxyURL} term.SetPrompt("> ") return true } var proxyStr string term.SetPrompt("Proxy (i.e socks5://127.0.0.1:9050, enter for none): ") for { if proxyStr, err = term.ReadLine(); err != nil { return false } if len(proxyStr) == 0 { break } u, err := url.Parse(proxyStr) if err != nil { alert(term, "Failed to parse "+proxyStr+" as a URL: "+err.Error()) continue } if _, err = proxy.FromURL(u, proxy.Direct); err != nil { alert(term, "Failed to parse "+proxyStr+" as a proxy: "+err.Error()) continue } break } if len(proxyStr) > 0 { config.Proxies = []string{proxyStr} info(term, "Since you selected a proxy, we need to know the server and port to connect to as a SRV lookup would leak information every time.") term.SetPrompt("Server (i.e. xmpp.example.com, enter to lookup using unproxied DNS): ") if config.Server, err = term.ReadLine(); err != nil { return false } if len(config.Server) == 0 { var port uint16 info(term, "Performing SRV lookup") if config.Server, port, err = xmpp.Resolve(domain); err != nil { alert(term, "SRV lookup failed: "+err.Error()) return false } config.Port = int(port) info(term, "Resolved "+config.Server+":"+strconv.Itoa(config.Port)) } else { for { term.SetPrompt("Port (enter for 5222): ") portStr, err := term.ReadLine() if err != nil { return false } if len(portStr) == 0 { portStr = "5222" } if config.Port, err = strconv.Atoi(portStr); err != nil || config.Port <= 0 || config.Port > 65535 { info(term, "Port numbers must be 0 < port <= 65535") continue } break } } } term.SetPrompt("> ") return true }
func main() { flag.Parse() oldState, err := terminal.MakeRaw(0) if err != nil { panic(err.Error()) } defer terminal.Restore(0, oldState) term := terminal.NewTerminal(os.Stdin, "> ") updateTerminalSize(term) resizeChan := make(chan os.Signal) go func() { for _ = range resizeChan { updateTerminalSize(term) } }() signal.Notify(resizeChan, syscall.SIGWINCH) if len(*configFile) == 0 { homeDir := os.Getenv("HOME") if len(homeDir) == 0 { alert(term, "$HOME not set. Please either export $HOME or use the -config-file option.\n") return } persistentDir := filepath.Join(homeDir, "Persistent") if stat, err := os.Lstat(persistentDir); err == nil && stat.IsDir() { // Looks like Tails. homeDir = persistentDir } *configFile = filepath.Join(homeDir, ".xmpp-client") } config, err := ParseConfig(*configFile) if err != nil { alert(term, "Failed to parse config file: "+err.Error()) config = new(Config) if !enroll(config, term) { return } config.filename = *configFile config.Save() } password := config.Password if len(password) == 0 { if password, err = term.ReadPassword(fmt.Sprintf("Password for %s (will not be saved to disk): ", config.Account)); err != nil { alert(term, "Failed to read password: "******"@", 2) if len(parts) != 2 { alert(term, "invalid username (want user@domain): "+config.Account) return } user := parts[0] domain := parts[1] var addr string addrTrusted := false if len(config.Server) > 0 && config.Port > 0 { addr = fmt.Sprintf("%s:%d", config.Server, config.Port) addrTrusted = true } else { if len(config.Proxies) > 0 { alert(term, "Cannot connect via a proxy without Server and Port being set in the config file as an SRV lookup would leak information.") return } host, port, err := xmpp.Resolve(domain) if err != nil { alert(term, "Failed to resolve XMPP server: "+err.Error()) return } addr = fmt.Sprintf("%s:%d", host, port) } var dialer proxy.Dialer for i := len(config.Proxies) - 1; i >= 0; i-- { u, err := url.Parse(config.Proxies[i]) if err != nil { alert(term, "Failed to parse "+config.Proxies[i]+" as a URL: "+err.Error()) return } if dialer == nil { dialer = proxy.Direct } if dialer, err = proxy.FromURL(u, dialer); err != nil { alert(term, "Failed to parse "+config.Proxies[i]+" as a proxy: "+err.Error()) return } } var certSHA256 []byte if len(config.ServerCertificateSHA256) > 0 { certSHA256, err = hex.DecodeString(config.ServerCertificateSHA256) if err != nil { alert(term, "Failed to parse ServerCertificateSHA256 (should be hex string): "+err.Error()) return } if len(certSHA256) != 32 { alert(term, "ServerCertificateSHA256 is not 32 bytes long") return } } xmppConfig := &xmpp.Config{ Log: &lineLogger{term, nil}, Create: *createAccount, TrustedAddress: addrTrusted, Archive: false, ServerCertificateSHA256: certSHA256, } if len(config.RawLogFile) > 0 { rawLog, err := os.OpenFile(config.RawLogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { alert(term, "Failed to open raw log file: "+err.Error()) return } lock := new(sync.Mutex) in := rawLogger{ out: rawLog, prefix: []byte("<- "), lock: lock, } out := rawLogger{ out: rawLog, prefix: []byte("-> "), lock: lock, } in.other, out.other = &out, &in xmppConfig.InLog = &in xmppConfig.OutLog = &out defer in.flush() defer out.flush() } if dialer != nil { info(term, "Making connection to "+addr+" via proxy") if xmppConfig.Conn, err = dialer.Dial("tcp", addr); err != nil { alert(term, "Failed to connect via proxy: "+err.Error()) return } } conn, err := xmpp.Dial(addr, user, domain, password, xmppConfig) if err != nil { alert(term, "Failed to connect to XMPP server: "+err.Error()) return } s := Session{ account: config.Account, conn: conn, term: term, conversations: make(map[string]*otr.Conversation), knownStates: make(map[string]string), privateKey: new(otr.PrivateKey), config: config, pendingRosterChan: make(chan *rosterEdit), pendingSubscribes: make(map[string]string), lastActionTime: time.Now(), } info(term, "Fetching roster") //var rosterReply chan xmpp.Stanza rosterReply, _, err := s.conn.RequestRoster() if err != nil { alert(term, "Failed to request roster: "+err.Error()) return } conn.SignalPresence("") s.input = Input{ term: term, uidComplete: new(priorityList), } commandChan := make(chan interface{}) go s.input.ProcessCommands(commandChan) stanzaChan := make(chan xmpp.Stanza) go s.readMessages(stanzaChan) s.privateKey.Parse(config.PrivateKey) s.timeouts = make(map[xmpp.Cookie]time.Time) info(term, fmt.Sprintf("Your fingerprint is %x", s.privateKey.Fingerprint())) ticker := time.NewTicker(1 * time.Second) MainLoop: for { select { case now := <-ticker.C: haveExpired := false for _, expiry := range s.timeouts { if now.After(expiry) { haveExpired = true break } } if !haveExpired { continue } newTimeouts := make(map[xmpp.Cookie]time.Time) for cookie, expiry := range s.timeouts { if now.After(expiry) { s.conn.Cancel(cookie) } else { newTimeouts[cookie] = expiry } } s.timeouts = newTimeouts case edit := <-s.pendingRosterChan: if !edit.isComplete { info(s.term, "Please edit "+edit.fileName+" and run /rostereditdone when complete") s.pendingRosterEdit = edit continue } if s.processEditedRoster(edit) { s.pendingRosterEdit = nil } else { alert(s.term, "Please reedit file and run /rostereditdone again") } case rosterStanza, ok := <-rosterReply: if !ok { alert(s.term, "Failed to read roster: "+err.Error()) return } if s.roster, err = xmpp.ParseRoster(rosterStanza); err != nil { alert(s.term, "Failed to parse roster: "+err.Error()) return } for _, entry := range s.roster { s.input.AddUser(entry.Jid) } info(s.term, "Roster received") case cmd, ok := <-commandChan: if !ok { warn(term, "Exiting because command channel closed") break MainLoop } s.lastActionTime = time.Now() switch cmd := cmd.(type) { case quitCommand: for to, conversation := range s.conversations { msgs := conversation.End() for _, msg := range msgs { s.conn.Send(to, string(msg)) } } break MainLoop case versionCommand: replyChan, cookie, err := s.conn.SendIQ(cmd.User, "get", xmpp.VersionQuery{}) if err != nil { alert(s.term, "Error sending version request: "+err.Error()) continue } s.timeouts[cookie] = time.Now().Add(5 * time.Second) go s.awaitVersionReply(replyChan, cmd.User) case rosterCommand: info(s.term, "Current roster:") maxLen := 0 for _, item := range s.roster { if maxLen < len(item.Jid) { maxLen = len(item.Jid) } } for _, item := range s.roster { state, ok := s.knownStates[item.Jid] line := "" if ok { line += "[*] " } else if cmd.OnlineOnly { continue } else { line += "[ ] " } line += item.Jid numSpaces := 1 + (maxLen - len(item.Jid)) for i := 0; i < numSpaces; i++ { line += " " } line += item.Subscription + "\t" + item.Name if ok { line += "\t" + state } info(s.term, line) } case rosterEditCommand: if s.pendingRosterEdit != nil { warn(s.term, "Aborting previous roster edit") s.pendingRosterEdit = nil } rosterCopy := make([]xmpp.RosterEntry, len(s.roster)) copy(rosterCopy, s.roster) go s.editRoster(rosterCopy) case rosterEditDoneCommand: if s.pendingRosterEdit == nil { warn(s.term, "No roster edit in progress. Use /rosteredit to start one") continue } go s.loadEditedRoster(*s.pendingRosterEdit) case toggleStatusUpdatesCommand: s.config.HideStatusUpdates = !s.config.HideStatusUpdates s.config.Save() // Tell the user the current state of the statuses if s.config.HideStatusUpdates { info(s.term, "Status updated disabled") } else { info(s.term, "Status updates enabled") } case confirmCommand: s.handleConfirmOrDeny(cmd.User, true /* confirm */) case denyCommand: s.handleConfirmOrDeny(cmd.User, false /* deny */) case addCommand: s.conn.SendPresence(cmd.User, "subscribe", "" /* generate id */) case msgCommand: conversation, ok := s.conversations[cmd.to] if (!ok || !conversation.IsEncrypted()) && config.ShouldEncryptTo(cmd.to) { warn(s.term, fmt.Sprintf("Did not send: no encryption established with %s", cmd.to)) continue } var msgs [][]byte message := []byte(cmd.msg) // Automatically tag all outgoing plaintext // messages with a whitespace tag that // indicates that we support OTR. if config.OTRAutoAppendTag && !bytes.Contains(message, []byte("?OTR")) && (!ok || !conversation.IsEncrypted()) { message = append(message, OTRWhitespaceTag...) } if ok { var err error msgs, err = conversation.Send(message) if err != nil { alert(s.term, err.Error()) break } } else { msgs = [][]byte{[]byte(message)} } for _, message := range msgs { s.conn.Send(cmd.to, string(message)) } case otrCommand: s.conn.Send(string(cmd.User), otr.QueryMessage) case otrInfoCommand: info(term, fmt.Sprintf("Your OTR fingerprint is %x", s.privateKey.Fingerprint())) for to, conversation := range s.conversations { if conversation.IsEncrypted() { info(s.term, fmt.Sprintf("Secure session with %s underway:", to)) printConversationInfo(s, to, conversation) } } case endOTRCommand: to := string(cmd.User) conversation, ok := s.conversations[to] if !ok { alert(s.term, "No secure session established") break } msgs := conversation.End() for _, msg := range msgs { s.conn.Send(to, string(msg)) } case authQACommand: to := string(cmd.User) conversation, ok := s.conversations[to] if !ok { alert(s.term, "Can't authenticate without a secure conversation established") break } msgs, err := conversation.Authenticate(cmd.Question, []byte(cmd.Secret)) if err != nil { alert(s.term, "Error while starting authentication with "+to+": "+err.Error()) } for _, msg := range msgs { s.conn.Send(to, string(msg)) } case authOobCommand: fpr, err := hex.DecodeString(cmd.Fingerprint) if err != nil { alert(s.term, fmt.Sprintf("Invalid fingerprint %s - not authenticated", cmd.Fingerprint)) break } existing := s.config.UserIdForFingerprint(fpr) if len(existing) != 0 { alert(s.term, fmt.Sprintf("Fingerprint %s already belongs to %s", cmd.Fingerprint, existing)) break } s.config.KnownFingerprints = append(s.config.KnownFingerprints, KnownFingerprint{fingerprint: fpr, UserId: cmd.User}) s.config.Save() info(s.term, fmt.Sprintf("Saved manually verified fingerprint %s for %s", cmd.Fingerprint, cmd.User)) case awayCommand: s.conn.SignalPresence("away") case chatCommand: s.conn.SignalPresence("chat") case dndCommand: s.conn.SignalPresence("dnd") case xaCommand: s.conn.SignalPresence("xa") case onlineCommand: s.conn.SignalPresence("") } case rawStanza, ok := <-stanzaChan: if !ok { warn(term, "Exiting because channel to server closed") break MainLoop } switch stanza := rawStanza.Value.(type) { case *xmpp.ClientMessage: s.processClientMessage(stanza) case *xmpp.ClientPresence: s.processPresence(stanza) case *xmpp.ClientIQ: if stanza.Type != "get" && stanza.Type != "set" { continue } reply := s.processIQ(stanza) if reply == nil { reply = xmpp.ErrorReply{ Type: "cancel", Error: xmpp.ErrorBadRequest{}, } } if err := s.conn.SendIQReply(stanza.From, "result", stanza.Id, reply); err != nil { alert(term, "Failed to send IQ message: "+err.Error()) } default: info(term, fmt.Sprintf("%s %s", rawStanza.Name, rawStanza.Value)) } } } os.Stdout.Write([]byte("\n")) }
func main() { log.SetFlags(0) flag.Usage = usage flag.Parse() if flag.NArg() != 0 { usage() } // Setup the TLS client configuration. config := &tls.Config{ServerName: *host} if *skipVerify { if *verbose { log.Print("WARNING: Skipping certificate verification") } config.InsecureSkipVerify = true } if *certFile != "" { data, err := ioutil.ReadFile(*certFile) if err != nil { log.Fatalf("could not read certificate file: %s", err) } p := x509.NewCertPool() if ok := p.AppendCertsFromPEM(data); !ok { log.Fatalf("could not parse certificates in %q", *certFile) } config.RootCAs = p } // Determine how we should converse with the remote server. fn, ok := tlsMethods[*method] if !ok { log.Fatalf("unknown connection method %q", method) } // Determine the proxy dialer method. var dialer proxy.Dialer = proxy.Direct if *proxyURL != "" { u, err := url.Parse(*proxyURL) if err != nil { log.Fatalf("failed to parse proxy url: %s", err) } d, err := proxy.FromURL(u, dialer) if err != nil { log.Fatal(err) } dialer = d usualHandshakeRTT = proxyHandshakeRTT } // Connect to the remote server. c, err := dialer.Dial("tcp", net.JoinHostPort(*host, *port)) if err != nil { log.Fatalf("could not dial remote host: %s", err) } // Wrap the connection in a shim so we can sniff the TLS traffic. s := &shim{Conn: c} // Run our predetermined TLS conversation. // If successful, the connection will be automatically closed. if err := fn(s, config); err != nil { s.Close() log.Fatalf("error in TLS conversation: %s", err) } // Warn if the TLS handshake took too long. rtt := s.HandshakeRTT() if rtt > usualHandshakeRTT { log.Printf("WARNING: the TLS handshake took too long (%s)\n", rtt) } // Show the server's time in Unix format. if *showTime { fmt.Println(s.ServerTime().Format(time.UnixDate)) } // Go no further if we don't have to set the clock. if *dontSetClock { return } // Check for unreasonable time values. t := s.ServerTime().Add(rtt) if t.After(maxReasonableTime) { log.Fatal("remote time is too far in the future") } if t.Before(recentCompileTime) { log.Fatal("remote time is too far in the past") } // Set the system clock. if err := setClock(t); err != nil { log.Fatal(err) } }