Exemplo n.º 1
0
        public static bool LoadRule(FirewallRule rule, INetFwRule2 entry)
        {
            try
            {
                INetFwRule3 entry3 = entry as INetFwRule3;

                rule.BinaryPath = entry.ApplicationName;
                rule.ServiceTag = entry.serviceName;
                if (entry3 != null)
                {
                    rule.AppSID = entry3.LocalAppPackageId;
                }

                // Note: while LocalAppPackageId and serviceName can be set at the same timea universall App can not be started as a service
                ProgramID progID;
                if (entry.ApplicationName != null && entry.ApplicationName.Equals("System", StringComparison.OrdinalIgnoreCase))
                {
                    progID = ProgramID.NewID(ProgramID.Types.System);
                }
                // Win10
                else if (entry3 != null && entry3.LocalAppPackageId != null)
                {
                    if (entry.serviceName != null)
                    {
                        throw new ArgumentException("Firewall paremeter conflict");
                    }
                    progID = ProgramID.NewAppID(entry3.LocalAppPackageId, entry.ApplicationName);
                }
                //
                else if (entry.serviceName != null)
                {
                    progID = ProgramID.NewSvcID(entry.serviceName, entry.ApplicationName);
                }
                else if (entry.ApplicationName != null)
                {
                    progID = ProgramID.NewProgID(entry.ApplicationName);
                }
                else // if nothing is configured than its a global roule
                {
                    progID = ProgramID.NewID(ProgramID.Types.Global);
                }

                rule.ProgID = Priv10Engine.AdjustProgID(progID);

                // https://docs.microsoft.com/en-us/windows/desktop/api/netfw/nn-netfw-inetfwrule

                rule.Name        = entry.Name;
                rule.Grouping    = entry.Grouping;
                rule.Description = entry.Description;

                //rule.ProgramPath = entry.ApplicationName;
                //rule.ServiceName = entry.serviceName;

                rule.Enabled = entry.Enabled;

                switch (entry.Direction)
                {
                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN: rule.Direction = FirewallRule.Directions.Inbound; break;

                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT: rule.Direction = FirewallRule.Directions.Outboun; break;
                }

                switch (entry.Action)
                {
                case NET_FW_ACTION_.NET_FW_ACTION_ALLOW: rule.Action = FirewallRule.Actions.Allow; break;

                case NET_FW_ACTION_.NET_FW_ACTION_BLOCK: rule.Action = FirewallRule.Actions.Block; break;
                }

                rule.Profile = entry.Profiles;

                if (entry.InterfaceTypes.Equals("All", StringComparison.OrdinalIgnoreCase))
                {
                    rule.Interface = (int)FirewallRule.Interfaces.All;
                }
                else
                {
                    rule.Interface = 0;
                    if (entry.InterfaceTypes.IndexOf("Lan", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Lan;
                    }
                    if (entry.InterfaceTypes.IndexOf("Wireless", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Wireless;
                    }
                    if (entry.InterfaceTypes.IndexOf("RemoteAccess", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.RemoteAccess;
                    }
                }

                rule.Protocol = entry.Protocol;

                /*The localAddrs parameter consists of one or more comma-delimited tokens specifying the local addresses from which the application can listen for traffic. "*" is the default value. Valid tokens include:
                 *
                 * "*" indicates any local address. If present, this must be the only token included.
                 * "Defaultgateway"
                 * "DHCP"
                 * "WINS"
                 * "LocalSubnet" indicates any local address on the local subnet. This token is not case-sensitive.
                 * A subnet can be specified using either the subnet mask or network prefix notation. If neither a subnet mask not a network prefix is specified, the subnet mask defaults to 255.255.255.255.
                 * A valid IPv6 address.
                 * An IPv4 address range in the format of "start address - end address" with no spaces included.
                 * An IPv6 address range in the format of "start address - end address" with no spaces included.*/

                switch (rule.Protocol)
                {
                case (int)FirewallRule.KnownProtocols.ICMP:
                case (int)FirewallRule.KnownProtocols.ICMPv6:
                    rule.SetIcmpTypesAndCodes(entry.IcmpTypesAndCodes);
                    break;

                case (int)FirewallRule.KnownProtocols.TCP:
                case (int)FirewallRule.KnownProtocols.UDP:
                    // , separated number or range 123-456
                    rule.LocalPorts  = entry.LocalPorts;
                    rule.RemotePorts = entry.RemotePorts;
                    break;
                }

                rule.LocalAddresses  = entry.LocalAddresses;
                rule.RemoteAddresses = entry.RemoteAddresses;

                // https://docs.microsoft.com/de-de/windows/desktop/api/icftypes/ne-icftypes-net_fw_edge_traversal_type_
                //EdgeTraversal = (int)(Entry.EdgeTraversal ? NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW : NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY);
                rule.EdgeTraversal = entry.EdgeTraversalOptions;

                if (entry3 != null)
                {
                    /*
                     * string s0 = entry3.LocalAppPackageId // 8
                     * string s1 = entry3.RemoteUserAuthorizedList; // 7
                     * string s2 = entry3.RemoteMachineAuthorizedList; // 7
                     * string s3 = entry3.LocalUserAuthorizedList; // 8
                     * string s4 = entry3.LocalUserOwner; // 8
                     * int i1 = entry3.SecureFlags; // ??
                     */
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Reading Firewall Rule failed {0}", err.ToString());
                return(false);
            }
            return(true);
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            App.args = args;

            HasConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            if (TestArg("-dbg_log"))
            {
                AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            }

            StartModes startMode = StartModes.Normal; // Normal GUI Mode

            if (TestArg("-svc"))
            {
                startMode = StartModes.Service;
            }
            else if (TestArg("-engine"))
            {
                startMode = StartModes.Engine;
            }

            Log = new AppLog(Key);
            AppLog.ExceptionLogID    = (long)Priv10Logger.EventIDs.Exception;
            AppLog.ExceptionCategory = (short)Priv10Logger.EventFlags.DebugEvents;

            // When running as worker we need the windows event log
            if (!Log.UsingEventLog())
            {
                Log.SetupEventLog(Key);
            }

            // load current version
            exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location;
            //*FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);
            //Version = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            //if (fvi.FileBuildPart != 0)
            //    Version += "." + fvi.FileBuildPart;
            //if (fvi.FilePrivatePart != 0)
            //    Version += (char)('a' + (fvi.FilePrivatePart - 1));
            appPath = Path.GetDirectoryName(exePath);

            dataPath = appPath + @"\Data";
            if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run
            {
                isPortable = true;

                AppLog.Debug("Portable Mode");
            }
            else
            {
                string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                if (progData == null)
                {
                    progData = @"C:\ProgramData";
                }

                dataPath = progData + "\\" + Key;
            }

            AppLog.Debug("Config Directory: {0}", dataPath);

            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            if (AdminFunc.IsAdministrator())
            {
                FileOps.SetAnyDirSec(dataPath);
            }

            Priv10Logger.LogInfo("PrivateWin10 Service Process Started, Mode {0}.", startMode.ToString());

            // setup custom assembly resolution for x86/x64 synamic compatybility
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler;

            // is the process starting as a service/worker?
            if (startMode != StartModes.Normal)
            {
                engine = new Priv10Engine();
                if (startMode == StartModes.Service)
                {
                    using (Priv10Service svc = new Priv10Service())
                        ServiceBase.Run(svc);
                }
                else
                {
                    engine.Run();
                }
                return;
            }
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            App.args = args;

            HasConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            if (TestArg("-dbg_log"))
            {
                AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            }

            StartModes startMode = StartModes.Normal; // Normal GUI Mode

            if (TestArg("-svc"))
            {
                startMode = StartModes.Service;
            }
            else if (TestArg("-engine"))
            {
                startMode = StartModes.Engine;
            }

            Log = new AppLog(Key);
            AppLog.ExceptionLogID    = (long)EventIDs.Exception;
            AppLog.ExceptionCategory = (short)EventFlags.DebugEvents;

            if (startMode == StartModes.Normal)
            {
                Log.EnableLogging();
                Log.LoadLog();
            }
            // When running as worker we need the windows event log
            else if (!Log.UsingEventLog())
            {
                Log.SetupEventLog(Key);
            }

            // load current version
            exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);

            Version = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                Version += "." + fvi.FileBuildPart;
            }
            if (fvi.FilePrivatePart != 0)
            {
                Version += (char)('a' + (fvi.FilePrivatePart - 1));
            }
            appPath = Path.GetDirectoryName(exePath);

            Translate.Load();

            dataPath = appPath + @"\Data";
            if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run
            {
                isPortable = true;

                AppLog.Debug("Portable Mode");
            }
            else
            {
                string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                if (progData == null)
                {
                    progData = @"C:\ProgramData";
                }

                dataPath = progData + "\\" + Key;
            }

            AppLog.Debug("Config Directory: {0}", dataPath);

            // execute commandline commands
            if (ExecuteCommands())
            {
                return;
            }

            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            if (AdminFunc.IsAdministrator())
            {
                FileOps.SetAnyDirSec(dataPath);
            }

            App.LogInfo("PrivateWin10 Process Started, Mode {0}.", startMode.ToString());

            Session = Process.GetCurrentProcess().SessionId;

            // setup custom assembly resolution for x86/x64 synamic compatybility
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler;

            // is the process starting as a service/worker?
            if (startMode != StartModes.Normal)
            {
                engine = new Priv10Engine();
                if (startMode == StartModes.Service)
                {
                    using (Priv10Service svc = new Priv10Service())
                        ServiceBase.Run(svc);
                }
                else
                {
                    engine.Run();
                }
                return;
            }

            Thread.CurrentThread.Name = "Gui";

            client = new Priv10Client();

            // Encure wie have the required privilegs
            //if (!AdminFunc.IsDebugging())
            {
                AppLog.Debug("Trying to connect to Engine...");
                int conRes = client.Connect(1000);
                if (conRes == 0)
                {
                    if (!AdminFunc.IsAdministrator())
                    {
                        AppLog.Debug("Trying to obtain Administrative proivilegs...");
                        if (AdminFunc.SkipUacRun(App.Key, App.args))
                        {
                            return;
                        }

                        AppLog.Debug("Trying to start with 'runas'...");
                        // Restart program and run as admin
                        string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                        ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
                        startInfo.UseShellExecute = true;
                        startInfo.Verb            = "runas";
                        try
                        {
                            Process.Start(startInfo);
                            return; // we restarted as admin
                        }
                        catch
                        {
                            //MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName);
                            //return; // no point in cintinuing without admin rights or an already running engine
                        }
                    }
                    else if (Priv10Service.IsInstalled())
                    {
                        AppLog.Debug("Trying to start service...");
                        if (Priv10Service.Startup())
                        {
                            AppLog.Debug("Trying to connect to service...");

                            if (client.Connect() != 0)
                            {
                                AppLog.Debug("Connected to service...");
                            }
                            else
                            {
                                AppLog.Debug("Failed to connect to service...");
                            }
                        }
                        else
                        {
                            AppLog.Debug("Failed to start service...");
                        }
                    }
                }
                else if (conRes == -1)
                {
                    MessageBox.Show(Translate.fmt("msg_dupliate_session", Title), Title);
                    return; // no point in cintinuing without admin rights or an already running engine
                }
            }

            //

            tweaks = new TweakManager();

            // if we couldn't connect to the engine start it and connect
            if (!client.IsConnected() && AdminFunc.IsAdministrator())
            {
                AppLog.Debug("Starting Engine Thread...");

                engine = new Priv10Engine();

                engine.Start();

                AppLog.Debug("... engine started.");

                client.Connect();
            }

            var app = new App();

            app.InitializeComponent();

            InitLicense();

            MainWnd = new MainWindow();

            TrayIcon         = new TrayIcon();
            TrayIcon.Action += TrayAction;
            TrayIcon.Visible = (GetConfigInt("Startup", "Tray", 0) != 0) || App.TestArg("-autorun");

            if (!App.TestArg("-autorun") || !TrayIcon.Visible)
            {
                MainWnd.Show();
            }

            app.Run();

            TrayIcon.DestroyNotifyicon();

            client.Close();

            tweaks.Store();

            if (engine != null)
            {
                engine.Stop();
            }
        }
Exemplo n.º 4
0
        public bool Load(XmlNode entryNode)
        {
            foreach (XmlNode node in entryNode.ChildNodes)
            {
                if (node.Name == "ID")
                {
                    ProgramID id = new ProgramID();
                    if (id.Load(node))
                    {
                        // COMPAT: remove service tag
                        ID = Priv10Engine.AdjustProgID(id);
                    }
                }
                else if (node.Name == "Description")
                {
                    Description = node.InnerText;
                }
                else if (node.Name == "ReceivedBytes")
                {
                    UInt64.TryParse(node.InnerText, out OldDownload);
                }
                else if (node.Name == "SentBytes")
                {
                    UInt64.TryParse(node.InnerText, out OldUpload);
                }
                else if (node.Name == "FwRules")
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        FirewallRuleEx rule = new FirewallRuleEx();
                        rule.ProgID = ID;
                        if (rule.Load(childNode) && !Rules.ContainsKey(rule.guid))
                        {
                            // COMPAT: update entry, old version did not save these data separatly
                            //if (ID.Type != ProgramID.Types.Global && (rule.BinaryPath == null && rule.ServiceTag == null && rule.AppSID == null))
                            //    rule.SetProgID(ID);

                            Rules.Add(rule.guid, rule);
                        }
                        else
                        {
                            Priv10Logger.LogError("Failed to load Firewall RuleEx {0} in {1}", rule.Name != null ? rule.Name : "[un named]", this.Description);
                        }
                    }
                }
                else if (node.Name == "DnsLog")
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        DnsEntry Entry = new DnsEntry(ID);
                        if (Entry.Load(childNode) && !DnsLog.ContainsKey(Entry.HostName))
                        {
                            DnsLog.Add(Entry.HostName, Entry);
                        }
                        else
                        {
                            Priv10Logger.LogError("Failed to load DnsLog Entry in {0}", this.Description);
                        }
                    }
                }
                else
                {
                    AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText);
                }
            }

            if (Description == null || Description.Substring(0, 2) == "@{")
            {
                Description = GetDescription();
            }

            return(ID != null);
        }