프로그래밍 방식으로 추가하는 응용 프로그램 윈도우 방화벽
문제
내가 있는 응용 프로그램이 설치 및 업데이트를 통해 ClickOnce.응용 프로그램 다운로드 파일을 FTP 를 통해,따라서 필요가 추가될 예외로 윈도우 방화벽에 있습니다.하는 방식 때문에 ClickOnce 작동,경로 EXE 변화는 모든 업데이트와 함께,그래서 예외가 필요해도 변경됩니다.무엇을 할 수있는 가장 좋은 방법이 될 것이 변경하는 방화벽의 눈에 보이지 않는 최종 사용자에게?
(응용 프로그램입니다 C#으로 작성)
해결책 2
이 문서에서는 완전한 래퍼 클래스가 포함되어 조작하기 위한 윈도우 방화벽에 있습니다. 응용 프로그램을 추가하는 예외 목록에 윈도우 방화벽
///
/// 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)
{ }
}
ClickOnce 샌드 제시하지 않았습니다 문제입니다.
다른 팁
가 확실하지 않으면 이것은 가장 좋은 방법이지만,실행 netsh 작동:
netsh 방화벽에 추가 allowedprogram C:\MyApp\MyApp.exe 프로그램이 setup 사용
나는 생각이 관리자 권한이 필요합하지만,분명한 이유:)
편집:나는지에 대해 충분히 알고 있 ClickOnce 지 여부를 알고 실행할 수 있습니다 외부 프로그램을 통해니다.
그것은 가능한 한 데이터에 액세스하는 방화벽에서 보면 다음과 같은 기사입니다.
진짜 문제는 않 ClickOnce 샌드박스용의 이런 종류의 액세스?나의 추측 것 그것을 하지 않습니다.어쩌면 사용할 수 있습니다 웹 서비스?(에 대한 자세한 내용은 데이터 액세스 방법에 ClickOnce 를 참조 액세스하는 로컬 및 원격에서 데이터 ClickOnce 응용 프로그램)
죽음에 대한 링크를"응용 프로그램을 추가하는 예외 목록에 윈도우 방화벽"에서 찾을 수 있습니다 Wayback Machine:
가정 우리가 사용하는 Visual Studio 에 설치 관리자->설치 프로젝트-당신은 필요 설치 등과 같은 이 안에는 어셈블리의 설치되어 있는지 확인하십시오에 추가할 사용자 지정 작업에 대한"기본 출력에서"설치 단계입니다.
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Diagnostics;
namespace YourNamespace
{
[RunInstaller(true)]
public class AddFirewallExceptionInstaller : Installer
{
protected override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
var path = Path.GetDirectoryName(Context.Parameters["assemblypath"]);
OpenFirewallForProgram(Path.Combine(path, "YourExe.exe"),
"Your program name for display");
}
private static void OpenFirewallForProgram(string exeFileName, string displayName)
{
var proc = Process.Start(
new ProcessStartInfo
{
FileName = "netsh",
Arguments =
string.Format(
"firewall add allowedprogram program=\"{0}\" name=\"{1}\" profile=\"ALL\"",
exeFileName, displayName),
WindowStyle = ProcessWindowStyle.Hidden
});
proc.WaitForExit();
}
}
}
대답은 당신만을 허용할 신뢰할 수 있는 소프트웨어 실행과 관리자 권한이 있습니다.시간이 어떤 소프트웨어가 있는 관리자 권한이 있고 민감한 변경 시스템입니다.당신이뿐만 아니라 읽기만 하드 디스크에 그렇지 않으면...
이 대답을 늦었습니다.이것은 내가 결국 사용: