public static string SendCommand(string cmd) { string result = ""; try { using (TcpClient s = new TcpClient()) { Connect(s); Write(s, cmd + "\n"); result = Read(s); return(result); } } catch (Exception e) { result = MessagesFormatter.Format(Messages.TorControlException, e.Message); } Engine.Instance.Logs.Log(LogType.Verbose, "Tor Test: " + result); return(result); }
public string Get(string name) { lock (Options) { if (CommandLine.SystemEnvironment.Exists(name)) { return(CommandLine.SystemEnvironment.Get(name, "")); } else if (Exists(name)) { Option option = Options[name]; if (option.Value != "") { return(option.Value); } else { return(option.Default); } } else { Engine.Instance.Logs.Log(LogType.Error, MessagesFormatter.Format(Messages.OptionsUnknown, name)); return(""); } } }
public virtual bool RouteRemove(Json jRoute) { lock (m_routes) { bool known = false; for (int i = 0; i < m_routes.Count; i++) { Json jRouteC = m_routes[i] as Json; if ((jRouteC["address"].Value as string == jRoute["address"].Value as string) && (jRouteC["gateway"].Value as string == jRoute["gateway"].Value as string) && (jRouteC["type"].Value as string == "added")) { Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.RouteDelAdded, new IpAddress(jRoute["address"].Value as string).ToCIDR(), new IpAddress(jRoute["gateway"].Value as string).ToCIDR())); m_routes.RemoveAt(i); known = true; break; } } if (known == false) { Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.RouteDelExist, new IpAddress(jRoute["address"].Value as string).ToCIDR(), new IpAddress(jRoute["gateway"].Value as string).ToCIDR())); jRoute["type"].Value = "removed"; m_routes.Add(jRoute); } } Recovery.Save(); return(true); }
public static string Test(string host, int controlPort, string controlPassword) { string result = ""; try { TcpClient s = Connect(host, controlPort, controlPassword); Write(s, "getinfo version\n"); result = Read(s); if ((result.IndexOf("250 OK") != -1) && (result.IndexOf("version=") != -1)) { result = result.Replace("250-", "").Trim(); result = result.Replace("250 OK", ""); result = result.Replace("version=", ""); result = Messages.TorControlTest + result.Trim(); } } catch (Exception e) { result = MessagesFormatter.Format(Messages.TorControlException, e.Message); } Engine.Instance.Logs.Log(LogType.Verbose, "Tor Test: " + result); return(result); }
public void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. IPAddress ipAddress = IPAddress.Loopback; string address = Engine.Instance.Storage.Get("tcpserver.ip"); int port = Engine.Instance.Storage.GetInt("tcpserver.port"); if (address == "localhost") { ipAddress = IPAddress.Loopback; } else if (address == "0.0.0.0") { ipAddress = IPAddress.Any; } else { IPAddress[] addresses = Dns.GetHostAddresses(address); if (addresses.Length > 0) { ipAddress = addresses[0]; } else { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.TcpServerNoBindAddress, address)); } } IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { m_listener.Bind(localEndPoint); m_listener.Listen(100); //while (true) { // Set the event to nonsignaled state. AllDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine("Waiting for a connection..."); m_listener.BeginAccept(new AsyncCallback(AcceptCallback), m_listener); // Wait until a connection is made before continuing. //allDone.WaitOne(); } } catch (Exception e) { Engine.Instance.Logs.Log(e); } }
public void Log(LogType Type, string Message, int BalloonTime, Exception e) { // Avoid repetition if ((Engine.Instance.Storage != null) && (Engine.Instance.Storage.GetBool("log.repeat") == false)) { string logRepetitionNormalized = Message; logRepetitionNormalized = System.Text.RegularExpressions.Regex.Replace(logRepetitionNormalized, "#\\d+", "#n"); if (logRepetitionNormalized == m_logLast) { m_logLastCount++; return; } else { int oldCount = m_logLastCount; m_logLast = logRepetitionNormalized; m_logLastCount = 0; if (oldCount != 0) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.LogsLineRepetitionSummary, oldCount.ToString())); } } } LogEntry l = new LogEntry(); l.Type = Type; l.Message = Message; l.BalloonTime = BalloonTime; l.Exception = e; if (l.Type > LogType.Realtime) { m_lastLogMessage = l.Message; m_logDotCount += 1; m_logDotCount = m_logDotCount % 10; } Entries.Add(l); if ((Engine.Instance != null) && (Engine.Instance.Storage != null) && (Entries.Count >= Engine.Instance.Storage.GetInt("gui.log_limit"))) { Entries.RemoveAt(0); } if (LogEvent != null) { LogEvent(l); } XmlItem xml = new XmlItem("command"); xml.SetAttribute("action", "ui.log"); l.WriteXML(xml); Engine.Instance.Command(xml); Engine.Instance.OnLog(l); }
public void Log(LogType type, string message, Exception e) { // Avoid repetition if ((type != LogType.Fatal) && (Engine.Instance.Storage != null) && (Engine.Instance.Storage.GetBool("log.repeat") == false)) { string logRepetitionNormalized = message; logRepetitionNormalized = System.Text.RegularExpressions.Regex.Replace(logRepetitionNormalized, "#\\d+", "#n"); if (logRepetitionNormalized == m_logLast) { m_logLastCount++; return; } else { int oldCount = m_logLastCount; m_logLast = logRepetitionNormalized; m_logLastCount = 0; if (oldCount != 0) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.LogsLineRepetitionSummary, oldCount.ToString())); } } } LogEntry l = new LogEntry(); l.Type = type; l.Message = message; l.Exception = e; if (l.Type > LogType.Realtime) { m_lastLogMessage = l.Message; m_logDotCount += 1; m_logDotCount = m_logDotCount % 10; } #if EDDIENET4 DispatchLog(l); #endif lock (Entries) { Entries.Add(l); if ((Engine.Instance != null) && (Engine.Instance.Storage != null) && (Entries.Count >= Engine.Instance.Storage.GetInt("gui.log_limit"))) { Entries.RemoveAt(0); } } if (LogEvent != null) { LogEvent(l); } Engine.Instance.OnLog(l); }
public override string ToString() { if (Engine.Instance.IsConnected()) { return(MessagesFormatter.Format(Messages.PingerStatsPending, UtilsString.FormatTime(LatestCheckDate))); } else { return(MessagesFormatter.Format(Messages.PingerStatsNormal, Invalid.ToString(), UtilsString.FormatTime(OlderCheckDate), UtilsString.FormatTime(LatestCheckDate))); } }
public void Set(string name, string val) { lock (this) { if (Exists(name) == false) { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.OptionsUnknown, name)); } else { Options[name].Value = val; } } }
public static void Connect(TcpClient client, string host, int controlPort, string controlPassword) { if (client == null) { throw new Exception("Internal error (client is null)"); } bool controlAuthenticate = Engine.Instance.Storage.GetBool("proxy.tor.control.auth"); byte[] password = System.Text.Encoding.ASCII.GetBytes(controlPassword); if (controlAuthenticate) { if (controlPassword == "") { string path = GetControlAuthCookiePath(); if (path == "") { throw new Exception(Messages.TorControlNoPath); } Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.TorControlAuth, "Cookie, from " + path)); password = Platform.Instance.FileContentsReadBytes(path); } else { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.TorControlAuth, "Password")); } } client.Connect(host, controlPort); if (controlAuthenticate) { Write(client, "AUTHENTICATE "); Write(client, UtilsString.BytesToHex(password)); Write(client, "\n"); string result = Read(client); if (result != "250 OK") { throw new Exception(result); } } Flush(client); }
public void UpdatePath() { try { OnUpdatePath(); OnUpdateVersion(); OnNormalizeVersion(); } catch (Exception e) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.BundleExecutableError, Code, Path)); Engine.Instance.Logs.Log(LogType.Verbose, e.Message); Engine.Instance.Logs.Log(LogType.Verbose, Platform.Instance.GetExecutableReport(Path)); Path = ""; Version = ""; Location = "missing"; } }
public void AddToIpsList(List <IpAddressRange> result, IpAddressRange ip, bool warning) { if (ip.Valid == false) { if (warning == true) { Engine.Instance.Logs.Log(LogType.Error, MessagesFormatter.Format(Messages.NetworkLockAllowedIpInvalid, ip.ToString())); } return; } if (result.Contains(ip)) { if (warning == true) { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.NetworkLockAllowedIpDuplicated, ip.ToString())); } return; } result.Add(ip); }
public OvpnBuilder BuildOVPN(bool preview) { // If preview, no physical additional files are created. Storage s = Engine.Instance.Storage; OvpnBuilder ovpn = new OvpnBuilder(); if (s.GetBool("openvpn.skip_defaults") == false) { ovpn.AppendDirectives(Engine.Instance.Storage.Get("openvpn.directives"), "Client level"); string directivesPath = Engine.Instance.Storage.Get("openvpn.directives.path"); if (directivesPath.Trim() != "") { try { if (Platform.Instance.FileExists(directivesPath)) { string text = Platform.Instance.FileContentsReadText(directivesPath); ovpn.AppendDirectives(text, "Client level"); } else { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.FileNotFound, directivesPath)); } } catch (Exception ex) { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.FileErrorRead, directivesPath, ex.Message)); } } Provider.OnBuildOvpnDefaults(ovpn); ovpn.AppendDirectives(OvpnDirectives, "Server level"); if (Path != "") { if (Platform.Instance.FileExists(Path)) { string text = Platform.Instance.FileContentsReadText(Path); ovpn.AppendDirectives(text, "Config file"); string dirPath = Platform.Instance.FileGetDirectoryPath(Path); ovpn.NormalizeRelativePath(dirPath); } } } if (s.Get("openvpn.dev_node") != "") { ovpn.AppendDirective("dev-node", s.Get("openvpn.dev_node"), ""); } int rcvbuf = s.GetInt("openvpn.rcvbuf"); if (rcvbuf == -2) { rcvbuf = Platform.Instance.GetRecommendedRcvBufDirective(); } if (rcvbuf == -2) { rcvbuf = -1; } if (rcvbuf != -1) { ovpn.AppendDirective("rcvbuf", rcvbuf.ToString(), ""); } int sndbuf = s.GetInt("openvpn.sndbuf"); if (sndbuf == -2) { sndbuf = Platform.Instance.GetRecommendedSndBufDirective(); } if (sndbuf == -2) { sndbuf = -1; } if (sndbuf != -1) { ovpn.AppendDirective("sndbuf", sndbuf.ToString(), ""); } string proxyDirectiveName = ""; string proxyDirectiveArgs = ""; string proxyMode = s.GetLower("proxy.mode"); string proxyWhen = s.GetLower("proxy.when"); if ((proxyWhen == "none") || (proxyWhen == "web")) { proxyMode = "none"; } if (proxyMode == "tor") { proxyDirectiveName = "socks-proxy"; } else if (proxyMode == "http") { proxyDirectiveName = "http-proxy"; } else if (proxyMode == "socks") { proxyDirectiveName = "socks-proxy"; } if (proxyDirectiveName != "") { proxyDirectiveArgs += s.Get("proxy.host") + " " + s.Get("proxy.port"); if ((s.GetLower("proxy.mode") != "none") && (s.GetLower("proxy.mode") != "tor")) { if (s.Get("proxy.auth") != "None") { string fileNameAuthOvpn = ""; if (preview) { fileNameAuthOvpn = "dummy.ppw"; } else { ovpn.FileProxyAuth = new TemporaryFile("ppw"); fileNameAuthOvpn = ovpn.FileProxyAuth.Path.Replace("\\", "\\\\"); // 2.6, Escaping for Windows string fileNameData = s.Get("proxy.login") + "\n" + s.Get("proxy.password") + "\n"; Platform.Instance.FileContentsWriteText(ovpn.FileProxyAuth.Path, fileNameData); Platform.Instance.FileEnsurePermission(ovpn.FileProxyAuth.Path, "600"); } proxyDirectiveArgs += " \"" + fileNameAuthOvpn + "\" " + s.Get("proxy.auth").ToLowerInvariant(); // 2.6 Auth Fix } } ovpn.AppendDirective(proxyDirectiveName, proxyDirectiveArgs, ""); } if (Lib.Common.Constants.AlphaFeatures) { if (Software.GetTool("openvpn").VersionAboveOrEqual("2.4")) { // IP Layer routes ovpn.AppendDirective("pull-filter", "ignore \"redirect-gateway\"", "Forced at client side"); bool ipv4In = true; bool ipv6In = true; if (s.GetLower("protocol.ipv4.route") == "in-always") { ipv4In = true; } else if (s.GetLower("protocol.ipv4.route") == "in-out") { if (SupportIPv4) { ipv4In = true; } else { ipv4In = false; } } else if (s.GetLower("protocol.ipv4.route") == "in-block") { if (SupportIPv4) { ipv4In = true; } else { ipv4In = false; // Out, but doesn't matter, will be blocked. } } else if (s.GetLower("protocol.ipv4.route") == "out") { ipv4In = false; } else if (s.GetLower("protocol.ipv4.route") == "block") { ipv4In = false; // Out, but doesn't matter, will be blocked. } if (s.GetLower("protocol.ipv6.route") == "in-always") { ipv6In = true; } else if (s.GetLower("protocol.ipv6.route") == "in-out") { if (SupportIPv4) { ipv6In = true; } else { ipv6In = false; } } else if (s.GetLower("protocol.ipv6.route") == "in-block") { if (SupportIPv6) { ipv6In = true; } else { ipv6In = false; // Out, but doesn't matter, will be blocked. } } else if (s.GetLower("protocol.ipv6.route") == "out") { ipv6In = false; } else if (s.GetLower("protocol.ipv6.route") == "block") { ipv6In = false; // Out, but doesn't matter, will be blocked. } if ((ipv4In == false) && (ipv6In == false)) { // no redirect-gateway } else if ((ipv4In == true) && (ipv6In == false)) { ovpn.AppendDirective("redirect-gateway", "def1 bypass-dhcp", ""); } else if ((ipv4In == false) && (ipv6In == true)) { ovpn.AppendDirective("redirect-gateway", "ipv6 !ipv4 def1 bypass-dhcp", ""); } else { ovpn.AppendDirective("redirect-gateway", "ipv6 def1 bypass-dhcp", ""); } } else { // ClodoTemp: If <2.4 ? Ipv6 are anyway non managed well. } } else { } string routesDefault = s.Get("routes.default"); if (routesDefault == "out") { if (Software.GetTool("openvpn").VersionAboveOrEqual("2.4")) { ovpn.RemoveDirective("redirect-gateway"); // Remove if exists ovpn.AppendDirective("pull-filter", "ignore \"redirect-gateway\"", "For Routes Out"); } else // Compatibility <2.4 { ovpn.AppendDirective("route-nopull", "", "For Routes Out"); // For DNS // < 2.9. route directive useless, and DNS are forced manually in every supported platform. // TOCLEAN /* * ovpn += "dhcp-option DNS " + Constants.DnsVpn + "\n"; // Manually because route-nopull skip it * ovpn += "route 10.4.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.5.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.6.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.7.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.8.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.9.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.30.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.50.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; */ // 2.9, Can be removed when resolv-conf method it's not binded anymore in up/down ovpn directive // TOFIX ovpn.AppendDirective("dhcp-option", "DNS " + Lib.Common.Constants.DnsVpn, ""); } // For Checking foreach (IpAddress ip in IpsExit.IPs) { if (ip.IsV4) // TOFIX IPv6 { ovpn.AppendDirective("route", ip.ToOpenVPN() + " vpn_gateway", "For Checking Route"); } } } string routes = s.Get("routes.custom"); string[] routes2 = routes.Split(';'); foreach (string route in routes2) { string[] routeEntries = route.Split(','); if (routeEntries.Length != 3) { continue; } string ipCustomRoute = routeEntries[0]; IpAddresses ipsCustomRoute = new IpAddresses(ipCustomRoute); if (ipsCustomRoute.Count == 0) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.CustomRouteInvalid, ipCustomRoute.ToString())); } else { string action = routeEntries[1]; string notes = routeEntries[2]; string gateway = ""; if ((routesDefault == "out") && (action == "in")) { gateway = "vpn_gateway"; } if ((routesDefault == "in") && (action == "out")) { gateway = "net_gateway"; } if (gateway != "") { foreach (IpAddress ip in ipsCustomRoute.IPs) { if (ip.IsV4) { ovpn.AppendDirective("route", ip.ToOpenVPN() + " " + gateway, (notes != "") ? Utils.StringSafe(notes) : ipCustomRoute); } // TOFIX IPv6 /* * else if(ipCustomRoute.IsV6) * ovpn.AppendDirective("route-ipv6", ipCustomRoute.ToOpenVPN() + " " + gateway + "_ipv6", Utils.StringSafe(notes)); */ } } } } if (routesDefault == "in") { if (proxyMode == "tor") { IpAddresses torNodeIps = TorControl.GetGuardIps(); foreach (IpAddress torNodeIp in torNodeIps.IPs) { if (torNodeIp.IsV4) { ovpn.AppendDirective("route", torNodeIp.ToOpenVPN() + " net_gateway", "Tor Circuit"); } // TOFIX IPv6 /* * else if(torNodeIp.IsV6) * ovpn.AppendDirective("route-ipv6", torNodeIp.ToOpenVPN() + " net_gateway_ipv6", "Tor Circuit"); */ } } } ovpn.AppendDirective("management", "127.0.0.1 " + Engine.Instance.Storage.Get("openvpn.management_port"), ""); ovpn.AppendDirectives(Engine.Instance.Storage.Get("openvpn.custom"), "Custom level"); // Experimental - Allow identification as Public Network in Windows. Advanced Option? // ovpn.Append("route-metric 512"); // ovpn.Append("route 0.0.0.0 0.0.0.0"); Provider.OnBuildOvpn(this, ovpn); Provider.OnBuildOvpnAuth(ovpn); Platform.Instance.OnBuildOvpn(ovpn); ovpn.Normalize(); string ovpnText = ovpn.Get(); Provider.OnBuildOvpnPost(ref ovpnText); return(ovpn); }
public void Load() { lock (this) { try { XmlDocument xmlDoc = new XmlDocument(); Providers = xmlDoc.CreateElement("providers"); if (Get("profile").ToLowerInvariant() == "none") { return; } string path = GetProfilePath(); CompatibilityManager.FixOldProfilePath(path); // 2.15 Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.OptionsRead, path)); if (Platform.Instance.FileExists(path) == false) { Engine.Instance.Logs.Log(LogType.Verbose, Messages.OptionsNotFound); return; } // CompatibilityManager.FixOldProfile(path); // ClodoTemp xmlDoc.Load(path); ResetAll(true); Providers = UtilsXml.XmlGetFirstElementByTagName(xmlDoc.DocumentElement, "providers"); if (Providers == null) { Providers = xmlDoc.CreateElement("providers"); } XmlNode nodeOptions = xmlDoc.DocumentElement.GetElementsByTagName("options")[0]; Dictionary <string, string> options = new Dictionary <string, string>(); foreach (XmlElement e in nodeOptions) { string name = e.Attributes["name"].Value; string value = e.Attributes["value"].Value; CompatibilityManager.FixOption(ref name, ref value); options[name] = value; } CompatibilityManager.FixOptions(options); foreach (KeyValuePair <string, string> item in options) { Set(item.Key, item.Value); } // For compatibility <3 XmlElement xmlManifest = UtilsXml.XmlGetFirstElementByTagName(xmlDoc.DocumentElement, "manifest"); if (xmlManifest != null) { XmlElement providerAirVpn = xmlDoc.CreateElement("AirVPN"); Providers.AppendChild(providerAirVpn); UtilsXml.XmlCopyElement(xmlManifest, providerAirVpn); XmlElement xmlUser = UtilsXml.XmlGetFirstElementByTagName(xmlDoc.DocumentElement, "user"); if (xmlUser != null) // Compatibility with old manifest < 2.11 { XmlElement oldKeyFormat = xmlUser.SelectSingleNode("keys/key[@id='default']") as XmlElement; if (oldKeyFormat != null) { oldKeyFormat.SetAttribute("name", "Default"); } } if (xmlUser != null) { UtilsXml.XmlCopyElement(xmlUser, providerAirVpn); } } } catch (Exception ex) { Engine.Instance.Logs.Log(LogType.Fatal, MessagesFormatter.Format(Messages.OptionsReverted, ex.Message)); ResetAll(true); } } }
public void Save() { string path = GetProfilePath(); bool remember = GetBool("remember"); lock (this) { try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); XmlElement rootNode = xmlDoc.CreateElement("eddie"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); XmlElement optionsNode = xmlDoc.CreateElement("options"); rootNode.AppendChild(optionsNode); xmlDoc.AppendChild(rootNode); foreach (Option option in Options.Values) { bool skip = false; if ((remember == false) && (option.Code == "login")) { skip = true; } if ((remember == false) && (option.Code == "password")) { skip = true; } if (option.CommandLineOnly) { skip = true; } if ((option.Value == "") || (option.Value == option.Default)) { skip = true; } if (skip == false) { XmlElement itemNode = xmlDoc.CreateElement("option"); itemNode.SetAttribute("name", option.Code); itemNode.SetAttribute("value", option.Value); optionsNode.AppendChild(itemNode); } } XmlElement providersNode = xmlDoc.CreateElement("providers"); rootNode.AppendChild(providersNode); foreach (Provider provider in Engine.Instance.ProvidersManager.Providers) { XmlNode providerNode = xmlDoc.ImportNode(provider.Storage.DocumentElement, true); providersNode.AppendChild(providerNode); } if (Engine.Instance.ProvidersManager.Providers.Count == 1) { if (Engine.Instance.ProvidersManager.Providers[0].Code == "AirVPN") { // Move providers->AirVPN to root. XmlElement xmlAirVPN = UtilsXml.XmlGetFirstElementByTagName(providersNode, "AirVPN"); if (xmlAirVPN != null) { foreach (XmlElement xmlChild in xmlAirVPN.ChildNodes) { UtilsXml.XmlCopyElement(xmlChild, xmlDoc.DocumentElement); } providersNode.RemoveChild(xmlAirVPN); } if (providersNode.ChildNodes.Count == 0) { providersNode.ParentNode.RemoveChild(providersNode); } } } xmlDoc.Save(path); Platform.Instance.FileEnsurePermission(path, "600"); } catch (Exception ex) { Engine.Instance.Logs.Log(LogType.Fatal, MessagesFormatter.Format(Messages.OptionsWriteFailed, path, ex.Message)); } } }
public static IpAddresses GetGuardIps(bool force) { // This is called a lots of time. Int64 now = UtilsCore.UnixTimeStamp(); if ((force == false) && ((now - m_lastGuardTime < 60))) { return(m_lastGuardIps); } IpAddresses ips = new IpAddresses(); try { string controlHost = Engine.Instance.Storage.Get("proxy.host").ToLowerInvariant().Trim(); if ((controlHost != "127.0.0.1") && (controlHost.ToLowerInvariant() != "localhost")) { // Guard IPS are used to avoid routing loop, that occur only if the Tor host is the same machine when OpenVPN run. return(ips); } List <string> ipsMessages = new List <string>(); using (TcpClient s = new TcpClient()) { Connect(s); Write(s, "getinfo circuit-status\n"); Flush(s); string circuits = Read(s); string[] circuitsLines = circuits.Split('\n'); foreach (string circuit in circuitsLines) { string id = UtilsString.RegExMatchOne(circuit.ToLowerInvariant(), "\\d+\\sbuilt\\s\\$([0-9a-f]+)"); if (id != "") { Write(s, "getinfo ns/id/" + id.ToUpperInvariant() + "\n"); string nodeInfo = Read(s); string[] nodeLines = nodeInfo.Split('\n'); foreach (string line in nodeLines) { string ip = UtilsString.RegExMatchOne(line, "r\\s.+?\\s.+?\\s.+?\\s.+?\\s.+?\\s(.+?)\\s"); if ((IpAddress.IsIP(ip)) && (!ips.Contains(ip))) { ips.Add(ip); ipsMessages.Add(ip + " (circuit)"); } } } } Write(s, "getconf bridge\n"); Flush(s); string bridges = Read(s); if (bridges.IndexOf("meek") == -1) //Panic if we have meek enabled, don't yet know what to do :-( { string[] bridgeLines = bridges.Split('\n'); foreach (string bridge in bridgeLines) { List <string> matches = UtilsString.RegExMatchSingle(bridge.ToLowerInvariant(), "250.bridge=(.+?)\\s([0-9a-f\\.\\:]+?):\\d+\\s"); if ((matches != null) && (matches.Count == 2)) { string bridgeType = matches[0]; string ip = matches[1]; if ((IpAddress.IsIP(ip)) && (!ips.Contains(ip))) { ips.Add(matches[1]); ipsMessages.Add(matches[1] + " (" + bridgeType + ")"); } } } } else { Engine.Instance.Logs.Log(LogType.Warning, Messages.TorControlMeekUnsupported); } if (ips.Count == 0) { Engine.Instance.Logs.Log(LogType.Warning, Messages.TorControlNoIps); //throw new Exception(Messages.TorControlNoIps); } else { string list = String.Join("; ", ipsMessages.ToArray()); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.TorControlGuardIps, list)); } } } catch (Exception e) { //throw new Exception(MessagesFormatter.Format(Messages.TorControlException, e.Message)); Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.TorControlException, e.Message)); } m_lastGuardIps = ips; m_lastGuardTime = now; return(ips); }
public static List <string> GetGuardIps() { List <string> ips = new List <string>(); try { string controlHost = Engine.Instance.Storage.Get("proxy.host").ToLowerInvariant().Trim(); if ((controlHost != "127.0.0.1") && (controlHost.ToLowerInvariant() != "localhost")) { // Guard IPS are used to avoid routing loop, that occur only if the Tor host is the same machine when OpenVPN run. return(ips); } TcpClient s = Connect(); Write(s, "getinfo circuit-status\n"); Flush(s); string circuits = Read(s); string[] circuitsLines = circuits.Split('\n'); foreach (string circuit in circuitsLines) { string[] circuitItems = circuit.Split(' '); if (circuitItems.Length < 3) { continue; } if (circuitItems[1] != "BUILT") { continue; } string id = circuitItems[2]; id = id.Substring(1, id.IndexOf('~') - 1); Write(s, "getinfo ns/id/" + id + "\n"); string nodeInfo = Read(s); string[] nodeLines = nodeInfo.Split('\n'); foreach (string line in nodeLines) { string[] lineItems = line.Split(' '); if (lineItems.Length < 7) { continue; } if (lineItems[0] != "r") { continue; } string ip = lineItems[6]; if (ips.Contains(ip) == false) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.TorControlGuardIp, ip, id)); ips.Add(ip); } } } s.Close(); if (ips.Count == 0) { Engine.Instance.Logs.Log(LogType.Warning, Messages.TorControlNoIps); //throw new Exception(Messages.TorControlNoIps); } } catch (Exception e) { //throw new Exception(MessagesFormatter.Format(Messages.TorControlException, e.Message)); Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.TorControlException, e.Message)); } return(ips); }
public static XmlDocument FetchUrls(string title, string authPublicKey, List <string> urls, Dictionary <string, string> parameters) { parameters["login"] = Engine.Instance.Storage.Get("login"); parameters["password"] = Engine.Instance.Storage.Get("password"); parameters["system"] = Platform.Instance.GetSystemCode(); parameters["version"] = Constants.VersionInt.ToString(CultureInfo.InvariantCulture); string firstError = ""; int hostN = 0; foreach (string url in urls) { string host = Utils.HostFromUrl(url); hostN++; if (IpAddress.IsIP(host) == false) { // If locked network are enabled, skip the hostname and try only by IP. // To avoid DNS issue (generally, to avoid losing time). if (Engine.Instance.NetworkLockManager.IsDnsResolutionAvailable(host) == false) { continue; } } try { RouteScope routeScope = new RouteScope(host); XmlDocument xmlDoc = AirExchange.FetchUrl(authPublicKey, url, parameters); routeScope.End(); if (xmlDoc == null) { throw new Exception("No answer."); } if (xmlDoc.DocumentElement.Attributes["error"] != null) { throw new Exception(xmlDoc.DocumentElement.Attributes["error"].Value); } return(xmlDoc); } catch (Exception e) { string info = e.Message; string proxyMode = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant(); string proxyAuth = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant(); if (proxyMode != "none") { info += " - with '" + proxyMode + "' proxy and '" + proxyAuth + "' auth"; } if (Engine.Instance.Storage.GetBool("advanced.expert")) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.ExchangeTryFailed, title, hostN.ToString(), info)); } if (firstError == "") { firstError = info; } } } throw new Exception(firstError); }
public ConnectionActive BuildConnectionActive(bool preview) { // If preview, no physical additional files are created. ConnectionActive connectionActive = new ConnectionActive(); Storage s = Engine.Instance.Storage; connectionActive.OpenVpnProfileStartup = new OvpnBuilder(); OvpnBuilder ovpn = connectionActive.OpenVpnProfileStartup; ovpn.AppendDirective("setenv", "IV_GUI_VER " + Constants.Name + Constants.VersionDesc, "Client level"); if (s.GetBool("openvpn.skip_defaults") == false) { ovpn.AppendDirectives(Engine.Instance.Storage.Get("openvpn.directives"), "Client level"); string directivesPath = Engine.Instance.Storage.Get("openvpn.directives.path"); if (directivesPath.Trim() != "") { try { if (Platform.Instance.FileExists(directivesPath)) { string text = Platform.Instance.FileContentsReadText(directivesPath); ovpn.AppendDirectives(text, "Client level"); } else { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.FileNotFound, directivesPath)); } } catch (Exception ex) { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.FileErrorRead, directivesPath, ex.Message)); } } Provider.OnBuildOvpnDefaults(ovpn); ovpn.AppendDirectives(OvpnDirectives, "Server level"); if (Path != "") { if (Platform.Instance.FileExists(Path)) { string text = Platform.Instance.FileContentsReadText(Path); ovpn.AppendDirectives(text, "Config file"); string dirPath = Platform.Instance.FileGetDirectoryPath(Path); ovpn.NormalizeRelativePath(dirPath); } } } if (s.Get("openvpn.dev_node") != "") { ovpn.AppendDirective("dev-node", s.Get("openvpn.dev_node"), ""); } if (s.Get("network.entry.iface") != "") { ovpn.AppendDirective("local", s.Get("network.entry.iface"), ""); ovpn.RemoveDirective("nobind"); } else { ovpn.RemoveDirective("local"); ovpn.AppendDirective("nobind", "", ""); } int rcvbuf = s.GetInt("openvpn.rcvbuf"); if (rcvbuf == -2) { rcvbuf = Platform.Instance.GetRecommendedRcvBufDirective(); } if (rcvbuf == -2) { rcvbuf = -1; } if (rcvbuf != -1) { ovpn.AppendDirective("rcvbuf", rcvbuf.ToString(), ""); } int sndbuf = s.GetInt("openvpn.sndbuf"); if (sndbuf == -2) { sndbuf = Platform.Instance.GetRecommendedSndBufDirective(); } if (sndbuf == -2) { sndbuf = -1; } if (sndbuf != -1) { ovpn.AppendDirective("sndbuf", sndbuf.ToString(), ""); } string proxyDirectiveName = ""; string proxyDirectiveArgs = ""; string proxyMode = s.GetLower("proxy.mode"); string proxyWhen = s.GetLower("proxy.when"); if ((proxyWhen == "none") || (proxyWhen == "web")) { proxyMode = "none"; } if (proxyMode == "tor") { proxyDirectiveName = "socks-proxy"; } else if (proxyMode == "http") { proxyDirectiveName = "http-proxy"; } else if (proxyMode == "socks") { proxyDirectiveName = "socks-proxy"; } if (proxyDirectiveName != "") { proxyDirectiveArgs += s.Get("proxy.host") + " " + s.Get("proxy.port"); if ((s.GetLower("proxy.mode") != "none") && (s.GetLower("proxy.mode") != "tor")) { if (s.Get("proxy.auth") != "None") { string fileNameAuthOvpn = ""; if (preview) { fileNameAuthOvpn = "dummy.ppw"; } else { connectionActive.ProxyAuthFile = new TemporaryFile("ppw"); fileNameAuthOvpn = connectionActive.ProxyAuthFile.Path; string fileNameData = s.Get("proxy.login") + "\n" + s.Get("proxy.password") + "\n"; Platform.Instance.FileContentsWriteText(connectionActive.ProxyAuthFile.Path, fileNameData); Platform.Instance.FileEnsurePermission(connectionActive.ProxyAuthFile.Path, "600"); Platform.Instance.FileEnsureOwner(connectionActive.ProxyAuthFile.Path); } proxyDirectiveArgs += " " + ovpn.EncodePath(fileNameAuthOvpn) + " " + s.Get("proxy.auth").ToLowerInvariant(); // 2.6 Auth Fix } } ovpn.AppendDirective(proxyDirectiveName, proxyDirectiveArgs, ""); } if (Common.Constants.FeatureIPv6ControlOptions) { if (s.GetLower("network.ipv4.mode") == "in") { connectionActive.TunnelIPv4 = true; } else if (s.GetLower("network.ipv4.mode") == "in-out") { if (SupportIPv4) { connectionActive.TunnelIPv4 = true; } else { connectionActive.TunnelIPv4 = false; } } else if (s.GetLower("network.ipv4.mode") == "in-block") { if (SupportIPv4) { connectionActive.TunnelIPv4 = true; } else { connectionActive.TunnelIPv4 = false; // Out, but doesn't matter, will be blocked. } } else if (s.GetLower("network.ipv4.mode") == "out") { connectionActive.TunnelIPv4 = false; } else if (s.GetLower("network.ipv4.mode") == "block") { connectionActive.TunnelIPv4 = false; // Out, but doesn't matter, will be blocked. } if (Engine.Instance.GetNetworkIPv6Mode() == "in") { connectionActive.TunnelIPv6 = true; } else if (Engine.Instance.GetNetworkIPv6Mode() == "in-out") { if (SupportIPv6) { connectionActive.TunnelIPv6 = true; } else { connectionActive.TunnelIPv6 = false; } } else if (Engine.Instance.GetNetworkIPv6Mode() == "in-block") { if (SupportIPv6) { connectionActive.TunnelIPv6 = true; } else { connectionActive.TunnelIPv6 = false; } } else if (Engine.Instance.GetNetworkIPv6Mode() == "out") { connectionActive.TunnelIPv6 = false; } else if (Engine.Instance.GetNetworkIPv6Mode() == "block") { connectionActive.TunnelIPv6 = false; } if (Software.GetTool("openvpn").VersionAboveOrEqual("2.4")) { ovpn.RemoveDirective("redirect-gateway"); // Remove if exists ovpn.AppendDirective("pull-filter", "ignore \"redirect-gateway\"", "Forced at client side"); if (connectionActive.TunnelIPv6 == false) { ovpn.AppendDirective("pull-filter", "ignore \"dhcp-option DNS6\"", "Client side"); ovpn.AppendDirective("pull-filter", "ignore \"tun-ipv6\"", "Client side"); ovpn.AppendDirective("pull-filter", "ignore \"ifconfig-ipv6\"", "Client side"); } if ((connectionActive.TunnelIPv4 == false) && (connectionActive.TunnelIPv6 == false)) { // no redirect-gateway } else if ((connectionActive.TunnelIPv4 == true) && (connectionActive.TunnelIPv6 == false)) { ovpn.AppendDirective("redirect-gateway", "def1 bypass-dhcp", ""); } else if ((connectionActive.TunnelIPv4 == false) && (connectionActive.TunnelIPv6 == true)) { ovpn.AppendDirective("redirect-gateway", "ipv6 !ipv4 def1 bypass-dhcp", ""); } else { ovpn.AppendDirective("redirect-gateway", "ipv6 def1 bypass-dhcp", ""); } } else { // OpenVPN <2.4, IPv6 not supported, IPv4 required. if (connectionActive.TunnelIPv4) { ovpn.AppendDirective("redirect-gateway", "def1 bypass-dhcp", ""); } else { ovpn.AppendDirective("route-nopull", "", "For Routes Out"); // 2.9, this is used by Linux resolv-conf DNS method. Need because route-nopull also filter pushed dhcp-option. // Incorrect with other provider, but the right-approach (pull-filter based) require OpenVPN <2.4. ovpn.AppendDirective("dhcp-option", "DNS " + Common.Constants.DnsVpn, ""); } } } else { string routesDefault = s.Get("routes.default"); connectionActive.TunnelIPv4 = (routesDefault == "in"); connectionActive.TunnelIPv6 = (routesDefault == "in"); if (routesDefault == "out") { if (Software.GetTool("openvpn").VersionAboveOrEqual("2.4")) { ovpn.RemoveDirective("redirect-gateway"); // Remove if exists ovpn.AppendDirective("pull-filter", "ignore \"redirect-gateway\"", "For Routes Out"); } else // Compatibility <2.4 { ovpn.AppendDirective("route-nopull", "", "For Routes Out"); // For DNS // < 2.9. route directive useless, and DNS are forced manually in every supported platform. // TOCLEAN /* * ovpn += "dhcp-option DNS " + Constants.DnsVpn + "\n"; // Manually because route-nopull skip it * ovpn += "route 10.4.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.5.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.6.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.7.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.8.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.9.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.30.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; * ovpn += "route 10.50.0.1 255.255.255.255 vpn_gateway # AirDNS\n"; */ // 2.9, this is used by Linux resolv-conf DNS method. Need because route-nopull also filter pushed dhcp-option. // Incorrect with other provider, but the right-approach (pull-filter based) require OpenVPN <2.4. ovpn.AppendDirective("dhcp-option", "DNS " + Common.Constants.DnsVpn, ""); } } } // For Checking foreach (IpAddress ip in IpsExit.IPs) { connectionActive.AddRoute(ip, "vpn_gateway", "For Checking Route"); } string routes = s.Get("routes.custom"); string[] routes2 = routes.Split(';'); foreach (string route in routes2) { string[] routeEntries = route.Split(','); if (routeEntries.Length != 3) { continue; } string ipCustomRoute = routeEntries[0]; IpAddresses ipsCustomRoute = new IpAddresses(ipCustomRoute); if (ipsCustomRoute.Count == 0) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.CustomRouteInvalid, ipCustomRoute.ToString())); } else { string action = routeEntries[1]; string notes = routeEntries[2]; foreach (IpAddress ip in ipsCustomRoute.IPs) { bool layerIn = false; if (ip.IsV4) { layerIn = connectionActive.TunnelIPv4; } else if (ip.IsV6) { layerIn = connectionActive.TunnelIPv6; } string gateway = ""; if ((layerIn == false) && (action == "in")) { gateway = "vpn_gateway"; } if ((layerIn == true) && (action == "out")) { gateway = "net_gateway"; } if (gateway != "") { connectionActive.AddRoute(ip, gateway, (notes != "") ? UtilsString.StringSafe(notes) : ipCustomRoute); } } } } if (proxyMode == "tor") { if (preview == false) { TorControl.SendNEWNYM(); } IpAddresses torNodeIps = TorControl.GetGuardIps((preview == false)); foreach (IpAddress torNodeIp in torNodeIps.IPs) { if (((connectionActive.TunnelIPv4) && (torNodeIp.IsV4)) || ((connectionActive.TunnelIPv6) && (torNodeIp.IsV6))) { connectionActive.AddRoute(torNodeIp, "net_gateway", "Tor Guard"); } } } { string managementPasswordFile = "dummy.ppw"; if (preview == false) { connectionActive.ManagementPassword = RandomGenerator.GetHash(); connectionActive.ManagementPasswordFile = new TemporaryFile("ppw"); managementPasswordFile = connectionActive.ManagementPasswordFile.Path; Platform.Instance.FileContentsWriteText(managementPasswordFile, connectionActive.ManagementPassword); Platform.Instance.FileEnsurePermission(managementPasswordFile, "600"); Platform.Instance.FileEnsureOwner(managementPasswordFile); } ovpn.AppendDirective("management", "127.0.0.1 " + Engine.Instance.Storage.Get("openvpn.management_port") + " " + ovpn.EncodePath(managementPasswordFile), ""); } // TOCLEAN - Moved bottom in 2.14.0 // ovpn.AppendDirectives(Engine.Instance.Storage.Get("openvpn.custom"), "Custom level"); // Experimental - Allow identification as Public Network in Windows. Advanced Option? // ovpn.Append("route-metric 512"); // ovpn.Append("route 0.0.0.0 0.0.0.0"); Provider.OnBuildConnectionActive(this, connectionActive); Provider.OnBuildConnectionActiveAuth(connectionActive); Platform.Instance.OnBuildOvpn(ovpn); ovpn.AppendDirectives(Engine.Instance.Storage.Get("openvpn.custom"), "Custom level"); foreach (ConnectionActiveRoute route in connectionActive.Routes) { if ((route.Address.IsV6) || (Constants.FeatureAlwaysBypassOpenvpnRoute)) { } else { // We never find a better method to manage IPv6 route via OpenVPN, at least <2.4.4 ovpn.AppendDirective("route", route.Address.ToOpenVPN() + " " + route.Gateway, UtilsString.StringSafe(route.Notes)); } } ovpn.Normalize(); return(connectionActive); }