C# Socket 允许控制台应用通过防火墙

news2024/9/24 21:19:58

需求:

在代码中将exe添加到防火墙规则中,允许Socket通过

添加库引用

效果:

一键三联

若可用记得点赞·评论·收藏哦,你的支持就是写作的动力。

源地址:

https://gist.github.com/cstrahan/513804

调用代码:

private static void AddToFireWall()
{
    if (FirewallHelper.Instance.HasAuthorization(Environment.ProcessPath))
    {
        Console.WriteLine("有防火墙权限");
    }
    else
    {
        Console.WriteLine("没有防火墙权限");
        FirewallHelper.Instance.GrantAuthorization(Environment.ProcessPath, Path.GetFileNameWithoutExtension(Environment.ProcessPath));
    }
}

源代码:

/// 
  /// Allows basic access to the windows firewall API.
  /// This can be used to add an exception to the windows firewall
  /// exceptions list, so that our programs can continue to run merrily
  /// even when nasty windows firewall is running.
  ///
  /// Please note: It is not enforced here, but it might be a good idea
  /// to actually prompt the user before messing with their firewall settings,
  /// just as a matter of politeness.
  /// 
  /// 
  /// To allow the installers to authorize idiom products to work through
  /// the Windows Firewall.
  /// 
  public class FirewallHelper
  {
    #region Variables
    /// 
    /// Hooray! Singleton access.
    /// 
    private static FirewallHelper instance = null;

    /// 
    /// Interface to the firewall manager COM object
    /// 
    private INetFwMgr fwMgr = null;
    #endregion
    #region Properties
    /// 
    /// Singleton access to the firewallhelper object.
    /// Threadsafe.
    /// 
    public static FirewallHelper Instance
    {
      get
      {
        lock (typeof(FirewallHelper))
        {
          if (instance == null)
            instance = new FirewallHelper();
          return instance;
        }
      }
    }
    #endregion
    #region Constructivat0r
    /// 
    /// Private Constructor.  If this fails, HasFirewall will return
    /// false;
    /// 
    private FirewallHelper()
    {
      // Get the type of HNetCfg.FwMgr, or null if an error occurred
      Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);

      // Assume failed.
      fwMgr = null;

      if (fwMgrType != null)
      {
        try
        {
          fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);
        }
        // In all other circumnstances, fwMgr is null.
        catch (ArgumentException) { }
        catch (NotSupportedException) { }
        catch (System.Reflection.TargetInvocationException) { }
        catch (MissingMethodException) { }
        catch (MethodAccessException) { }
        catch (MemberAccessException) { }
        catch (InvalidComObjectException) { }
        catch (COMException) { }
        catch (TypeLoadException) { }
      }
    }
    #endregion
    #region Helper Methods
    /// 
    /// Gets whether or not the firewall is installed on this computer.
    /// 
    /// 
    public bool IsFirewallInstalled
    {
      get
      {
        if (fwMgr != null &&
              fwMgr.LocalPolicy != null &&
              fwMgr.LocalPolicy.CurrentProfile != null)
          return true;
        else
          return false;
      }
    }

    /// 
    /// Returns whether or not the firewall is enabled.
    /// If the firewall is not installed, this returns false.
    /// 
    public bool IsFirewallEnabled
    {
      get
      {
        if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)
          return true;
        else
          return false;
      }
    }

    /// 
    /// Returns whether or not the firewall allows Application "Exceptions".
    /// If the firewall is not installed, this returns false.
    /// 
    /// 
    /// Added to allow access to this metho
    /// 
    public bool AppAuthorizationsAllowed
    {
      get
      {
        if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)
          return true;
        else
          return false;
      }
    }

    /// 
    /// Adds an application to the list of authorized applications.
    /// If the application is already authorized, does nothing.
    /// 
    /// 
    ///         The full path to the application executable.  This cannot
    ///         be blank, and cannot be a relative path.
    /// 
    /// 
    ///         This is the name of the application, purely for display
    ///         puposes in the Microsoft Security Center.
    /// 
    /// 
    ///         When applicationFullPath is null OR
    ///         When appName is null.
    /// 
    /// 
    ///         When applicationFullPath is blank OR
    ///         When appName is blank OR
    ///         applicationFullPath contains invalid path characters OR
    ///         applicationFullPath is not an absolute path
    /// 
    /// 
    ///         If the firewall is not installed OR
    ///         If the firewall does not allow specific application 'exceptions' OR
    ///         Due to an exception in COM this method could not create the
    ///         necessary COM types
    /// 
    /// 
    ///         If no file exists at the given applicationFullPath
    /// 
    public void GrantAuthorization(string applicationFullPath, string appName)
    {
      #region  Parameter checking
      if (applicationFullPath == null)
        throw new ArgumentNullException("applicationFullPath");
      if (appName == null)
        throw new ArgumentNullException("appName");
      if (applicationFullPath.Trim().Length == 0)
        throw new ArgumentException("applicationFullPath must not be blank");
      if (applicationFullPath.Trim().Length == 0)
        throw new ArgumentException("appName must not be blank");
      if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
        throw new ArgumentException("applicationFullPath must not contain invalid path characters");
      if (!Path.IsPathRooted(applicationFullPath))
        throw new ArgumentException("applicationFullPath is not an absolute path");
      if (!File.Exists(applicationFullPath))
        throw new FileNotFoundException("File does not exist", applicationFullPath);
      // State checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed.");
      if (!AppAuthorizationsAllowed)
        throw new FirewallHelperException("Application exemptions are not allowed.");
      #endregion

      if (!HasAuthorization(applicationFullPath))
      {
        // Get the type of HNetCfg.FwMgr, or null if an error occurred
        Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);

        // Assume failed.
        INetFwAuthorizedApplication appInfo = null;

        if (authAppType != null)
        {
          try
          {
            appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);
          }
          // In all other circumnstances, appInfo is null.
          catch (ArgumentException) { }
          catch (NotSupportedException) { }
          catch (System.Reflection.TargetInvocationException) { }
          catch (MissingMethodException) { }
          catch (MethodAccessException) { }
          catch (MemberAccessException) { }
          catch (InvalidComObjectException) { }
          catch (COMException) { }
          catch (TypeLoadException) { }
        }

        if (appInfo == null)
          throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");

        appInfo.Name = appName;
        appInfo.ProcessImageFileName = applicationFullPath;
        // ...
        // Use defaults for other properties of the AuthorizedApplication COM object

        // Authorize this application
        fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);
      }
      // otherwise it already has authorization so do nothing
    }
    /// 
    /// Removes an application to the list of authorized applications.
    /// Note that the specified application must exist or a FileNotFound
    /// exception will be thrown.
    /// If the specified application exists but does not current have
    /// authorization, this method will do nothing.
    /// 
    /// 
    ///         The full path to the application executable.  This cannot
    ///         be blank, and cannot be a relative path.
    /// 
    /// 
    ///         When applicationFullPath is null
    /// 
    /// 
    ///         When applicationFullPath is blank OR
    ///         applicationFullPath contains invalid path characters OR
    ///         applicationFullPath is not an absolute path
    /// 
    /// 
    ///         If the firewall is not installed.
    /// 
    /// 
    ///         If the specified application does not exist.
    /// 
    public void RemoveAuthorization(string applicationFullPath)
    {

      #region  Parameter checking
      if (applicationFullPath == null)
        throw new ArgumentNullException("applicationFullPath");
      if (applicationFullPath.Trim().Length == 0)
        throw new ArgumentException("applicationFullPath must not be blank");
      if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
        throw new ArgumentException("applicationFullPath must not contain invalid path characters");
      if (!Path.IsPathRooted(applicationFullPath))
        throw new ArgumentException("applicationFullPath is not an absolute path");
      if (!File.Exists(applicationFullPath))
        throw new FileNotFoundException("File does not exist", applicationFullPath);
      // State checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
      #endregion

      if (HasAuthorization(applicationFullPath))
      {
        // Remove Authorization for this application
        fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);
      }
      // otherwise it does not have authorization so do nothing
    }
    /// 
    /// Returns whether an application is in the list of authorized applications.
    /// Note if the file does not exist, this throws a FileNotFound exception.
    /// 
    /// 
    ///         The full path to the application executable.  This cannot
    ///         be blank, and cannot be a relative path.
    /// 
    /// 
    ///         The full path to the application executable.  This cannot
    ///         be blank, and cannot be a relative path.
    /// 
    /// 
    ///         When applicationFullPath is null
    /// 
    /// 
    ///         When applicationFullPath is blank OR
    ///         applicationFullPath contains invalid path characters OR
    ///         applicationFullPath is not an absolute path
    /// 
    /// 
    ///         If the firewall is not installed.
    /// 
    /// 
    ///         If the specified application does not exist.
    /// 
    public bool HasAuthorization(string applicationFullPath)
    {
      #region  Parameter checking
      if (applicationFullPath == null)
        throw new ArgumentNullException("applicationFullPath");
      if (applicationFullPath.Trim().Length == 0)
        throw new ArgumentException("applicationFullPath must not be blank");
      if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
        throw new ArgumentException("applicationFullPath must not contain invalid path characters");
      if (!Path.IsPathRooted(applicationFullPath))
        throw new ArgumentException("applicationFullPath is not an absolute path");
      if (!File.Exists(applicationFullPath))
        throw new FileNotFoundException("File does not exist.", applicationFullPath);
      // State checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");

      #endregion

      // Locate Authorization for this application
      foreach (string appName in GetAuthorizedAppPaths())
      {
        // Paths on windows file systems are not case sensitive.
        if (appName.ToLower() == applicationFullPath.ToLower())
          return true;
      }

      // Failed to locate the given app.
      return false;

    }

    /// 
    /// Retrieves a collection of paths to applications that are authorized.
    /// 
    /// 
    /// 
    ///         If the Firewall is not installed.
    ///   
    public ICollection GetAuthorizedAppPaths()
    {
      // State checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");

      ArrayList list = new ArrayList();
      //  Collect the paths of all authorized applications
      foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
        list.Add(app.ProcessImageFileName);

      return list;
    }
    #endregion
  }

  /// 
  /// Describes a FirewallHelperException.
  /// 
  /// 
  ///
  /// 
  public class FirewallHelperException : System.Exception
  {
    /// 
    /// Construct a new FirewallHelperException
    /// 
    /// 
    public FirewallHelperException(string message)
      : base(message)
    { }
  }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1420619.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AI投资或成科技裁员罪魁祸首

最近的科技裁员让许多人对这个行业的稳定性产生了疑问。然而,仔细观察发现,这些裁员并不是经济困境的迹象,而是科技公司为了重新调整优先事项并投资未来而进行的战略举措。科技行业正投入数十亿美元用于人工智能(AI)&a…

BIO、NIO编程与直接内存、零拷贝

一、网络通信 1、什么是socket? Socket 是应用层与 TCP/IP 协议族通信的中间软件抽象层,它是一组接口,一般由操作 系统提供。客户端连接上一个服务端,就会在客户端中产生一个 socket 接口实例,服务端每接受 一个客户端…

iTunes Connect 中修改后的内购(IPA)审核所需的时间

引言 在 iOS 开发过程中,将应用上传到 App Store 是一个重要的步骤。应用审核和 IAP 商品审核是分开的,审核一般需要等待一周左右。如果审核通过,我们会收到 Apple 发来的反馈邮件,根据邮件中的指示进行后续操作。如果已经上架的…

顺序表的奥秘:高效数据存储与检索

🍿顺序表 🧀1、顺序表的实现🍥1.1 创建顺序表类🍥1.2 插入操作🍥1.3 查找操作🍥1.4 删除操作🍥1.5 清空操作 🧀2、ArrayList的说明🧀3、ArrayList使用🍥3.1 A…

jQuery 遍历 —— W3school 详解 简单易懂(十八)

什么是遍历? jQuery 遍历,意为“移动”,用于根据其相对于其他元素的关系来“查找”(或选取)HTML 元素。以某项选择开始,并沿着这个选择移动,直到抵达您期望的元素为止。 下图展示了一个家族树…

Spring Security的入门案例!!!

一、导入依赖 <dependencies><!--web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--security--><dependency><groupId>…

Kubernetes安装Seata1.8.0(注册到Nacos,连接外置数据库)

文章目录 Seata简介效果安装Seata1.8.01、拷贝数据2、修改配置3、初始化数据库4、安装Seata Seata简介 Seata 是一款开源的分布式事务解决方案&#xff0c;致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式&#xff0c;为用户…

CSA大中华区发布《AI安全白皮书》,中国电信、蚂蚁集团、华为、百度安全等单位参编

关注国际云安全联盟CSA公众号&#xff0c;回复关键词“AI”获取报告 2023年9月&#xff0c;CSA大中华区成立AI安全工作组&#xff0c;旨在共同解决 AI 技术快速发展所带来的安全难题。《AI安全白皮书》是CSA大中华区AI安全工作组的首个研究成果&#xff0c;由来自中国电信、蚂…

【计算机网络】——TCP协议

&#x1f4d1;前言 本文主要是【计算机网络】——传输层TCP协议的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是青衿&#x1f947; ☁️博客首页&#xff1a;CSDN主页放风讲故事 &#x1f304;每日一句…

Java学习-常用API-ArrayList

ArrayList的遍历并删除元素&#xff08;案例&#xff09;ArrayList的常用apiArrayList是一种泛型集合ArrayList是什么&#xff1f;有何特点&#xff1f;作用&#xff1f; importjava.util.ArrayList; importjava.util.List; publicclassapiArrayListDemo1{ publicstaticvoidmai…

44 漏洞发现-APP应用之漏洞探针类型利用修复

目录 文章思路说明案例演示:抓包工具WEB协议面使用说明抓包工具非WEB协议面使用说明安卓逆向便捷APK一键提取URL演示利用Burp筛选及联动功能打出军体拳模拟器四个违法案例APP安全分析测试 涉及资源&#xff1a; 逆向只会涉及到相关工具的使用&#xff0c;不会涉及到原理&#x…

【论文阅读】Long-Tailed Recognition via Weight Balancing(CVPR2022)附MaxNorm的代码

目录 论文使用方法weight decayMaxNorm 如果使用原来的代码报错的可以看下面这个 论文 问题&#xff1a;真实世界中普遍存在长尾识别问题&#xff0c;朴素训练产生的模型在更高准确率方面偏向于普通类&#xff0c;导致稀有的类别准确率偏低。 key:解决LTR的关键是平衡各方面&a…

AutoMQ Kafka 云上十倍成本节约的奥秘(一): SPOT 实例

近年来&#xff0c;无论是海外还是国内&#xff0c;虽然受疫情影响&#xff0c;公有云的市场规模增速有所放缓&#xff0c;但是云的市场总规模仍然是持续增长的。公有云作为一个各个国家重点布局的战略方向和其本身万亿级市场的定位[1]&#xff0c;我们学习用好云是非常有必要的…

彻底解决 MAC Android Studio gradle async 时出现 “connect timed out“ 问题

最近在编译一个比较老的项目&#xff0c;git clone 之后使用 async 之后出现一下现象&#xff1a; 首先确定是我网络本身是没有问题的&#xff0c;尝试几次重新 async 之后还是出现问题&#xff0c;网上找了一些方法解决了本问题&#xff0c;以此来记录一下问题是如何解决的。 …

网络地址相关函数一网打尽

这块的函数又多又乱&#xff0c;今天写篇日志&#xff0c;以后慢慢补充 1. 网络地址介绍 1.1 ipv4 1.1.1 点、分十进制的ipv4 你对这个地址熟悉吗&#xff1f; 192.168.10.100&#xff0c;这可以当做一个字符串。被十进制数字、 “ . ”分开。IP地址的知识就不再多讲…

关于MyBatis和JVM的最常见的十道面试题

ORM项目中类属性名和数据库字段名不一致会导致什么问题&#xff1f;它的解决方案有哪些&#xff1f; 在ORM项目中&#xff0c;如果类的属性名称和数据库字段名不一致会场导致插入、修改时设置的这个不一致字段为null&#xff0c;查询的时候即使数据库有数据&#xff0c;但是查…

Jenkins如何从GIT下拉项目并启动Tomcat

一、先添加服务器 二、添加视图 点击控制台输出&#xff0c;滑到最下面&#xff0c;出现这个就说明构建成功了&#xff0c;如果没有出现&#xff0c;说明构建有问题&#xff0c;需要解决好问题才能启动哦~

Python 九九乘法表的7种实现方式

Python 九九乘法表的7种实现方式 九九乘法表是初学者学习编程的必要练手题目之一&#xff0c;因此各种语言都有对应的实现方式&#xff0c;而 Python 也不例外。在 Python 中&#xff0c;我们可以使用多种方式来生成一个简单的九九乘法表。 实现方式一&#xff1a;双重循环 f…

使用 Node.js 和 Cheerio 爬取网站图片

写一个关于图片爬取的小案例 爬取效果 使用插件如下&#xff1a; {"dependencies": {"axios": "^1.6.0","cheerio": "^1.0.0-rc.12","request": "^2.88.2"} }新建一个config.js配置文件 // 爬取图片…

Android T 远程动画显示流程(更新中)

序 本地动画和远程动画区别是什么? 本地动画&#xff1a;自给自足。对自身SurfaceControl矢量动画进行控制。 远程动画&#xff1a;拿来吧你&#xff01;一个app A对另一个app B通过binder跨进程通信&#xff0c;控制app B的SurfaceControl矢量动画。 无论是本地动画还是远程…