private void AddClick(object sender, RoutedEventArgs e) { var rule = new FirewallRule(); if (OperationComboBox.SelectedItem is ComboBoxItem operationItem) { rule.RuleOperation = Enum.TryParse((string)operationItem.Tag, out FirewallRule.Operation operation) ? operation : FirewallRule.Operation.Deny; } if (DirectionComboBox.SelectedItem is ComboBoxItem directionItem && Enum.TryParse((string)directionItem.Tag, out Direction direction)) { rule.RuleDirection = direction; } if (ProtocolComboBox.SelectedItem is ComboBoxItem protocolItem && Enum.TryParse((string)protocolItem.Tag, out Protocol protocol)) { rule.RuleProtocol = protocol; } InlineTry(() => rule.DestinationMac = PhysicalAddress.Parse(DestinationMacTextBox.Text)); InlineTry(() => rule.DestinationIp = IPAddress.Parse(DestinationIpTextBox.Text)); InlineTry(() => rule.SourceMac = PhysicalAddress.Parse(SourceMacTextBox.Text)); InlineTry(() => rule.SourceIp = IPAddress.Parse(SourceIpTextBox.Text)); InlineTry(() => rule.DestinationPort = DestinationPortTextBox.Text.Length != 0 ? Convert.ToUInt16(DestinationPortTextBox.Text) : (ushort?)null); InlineTry(() => rule.SourcePort = SourcePortTextBox.Text.Length != 0 ? Convert.ToUInt16(SourcePortTextBox.Text) : (ushort?)null); _device.FirewallRules.Add(rule); this.Close(); }
/// <summary> /// 创建要执行的指令 /// </summary> /// <param name="lstIP"></param> /// <param name="dicExistsRule"></param> public override List <string> CreateCommand(SshClient ssh) { Dictionary <string, FirewallRule> dicExistsRule = LoadExists(ssh); List <string> lstIP = LoadUserIP(); List <FirewallRule> lstCreateItem = new List <FirewallRule>();//需要创建的列表 foreach (string ip in lstIP) { foreach (FirewallItem fwItem in _firewallRule) { //int port = kvpPort.Key; string key = GetKey(ip, fwItem.Port, fwItem.Protocol); if (dicExistsRule.ContainsKey(key)) //已存在规则,在存在列表删除并跳过 { dicExistsRule.Remove(key); continue; } lstCreateItem.Add(new FirewallRule(ip, fwItem.Port, fwItem.Protocol)); } } List <string> cmd = new List <string>(); foreach (FirewallRule rule in lstCreateItem) { cmd.Add(CreateAddCommand(rule));//增加白名单命令 } foreach (KeyValuePair <string, FirewallRule> kvpRule in dicExistsRule) { FirewallRule rule = kvpRule.Value; cmd.Add(CreateDeleteCommand(rule));//删除白名单命令 } return(cmd); }
public async Task CanUseFirewall() { Debug.WriteLine("Creating firewall rule"); var rule = new FirewallRule("TestRule1", "0.0.0.0", "255.255.255.255"); await DatabaseServer.AddFirewallRule(rule); Debug.WriteLine("Retrieving firewall rule"); var retrievedRule = (await DatabaseServer.FirewallRules.AsTask()).SingleOrDefault(r => r.Name == "TestRule1"); Assert.IsNotNull(retrievedRule); Assert.AreEqual(retrievedRule.StartIpAddress, rule.StartIpAddress); Assert.AreEqual(retrievedRule.EndIpAddress, rule.EndIpAddress); var cxString = "Data Source=tcp:" + DatabaseServer.Name + ".database.windows.net;User ID=testadmin;Password="******";Initial Catalog=master;Encrypt=true"; using (var cx = new SqlConnection(cxString)) { Debug.WriteLine("Testing SQL connection"); cx.Open(); Assert.AreEqual(1, new SqlCommand("SELECT COUNT(*) FROM sys.firewall_rules", cx).ExecuteScalar()); } Debug.WriteLine("Deleting firewall rule"); await rule.DeleteAsync(); Debug.WriteLine("Verifying firewall rule deletion"); var deletedRule = (await DatabaseServer.FirewallRules.AsTask()).SingleOrDefault(r => r.Name == "TestRule1"); Assert.IsNull(deletedRule); }
public static ProgramID GetIdFromRule(FirewallRule rule) { ProgramID progID; string fullPath = rule.BinaryPath != null?Environment.ExpandEnvironmentVariables(rule.BinaryPath) : null; if (rule.BinaryPath != null && rule.BinaryPath.Equals("System", StringComparison.OrdinalIgnoreCase)) { progID = ProgramID.NewID(ProgramID.Types.System); } // Win 8+ else if (rule.AppSID != null) { if (rule.ServiceTag != null) { AppLog.Debug("Firewall paremeter conflict in rule: {0}", rule.Name); } progID = ProgramID.NewAppID(rule.AppSID, fullPath); } // else if (rule.ServiceTag != null) { progID = ProgramID.NewSvcID(rule.ServiceTag, fullPath); } else if (rule.BinaryPath != null) { progID = ProgramID.NewProgID(fullPath); } else // if nothing is configured than its a global roule { progID = ProgramID.NewID(ProgramID.Types.Global); } return(AdjustProgID(progID)); }
public static void Stop() { Log.Information("ServiceHelper Stop called"); ISettings s = Settings.LoadSettings(); CriticalProcessBase.SetProcessAsNotCritical(s); FirewallRule.AllowConnection(true); RegistryWrapper.StopRegistryMonitor(); RegistryWrapper.RestoreDefaultSettings(true); Log.Information("Closing WCF Host"); host?.Close(); if (host is null) { Log.Information("Host was null"); } if (host != null) { Log.Information("WCF Host status = " + host.State); } }
public void TestCreateAndUpdateFirewallRule() { string testPrefix = "firewallrulecrudtest-"; using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); // Create Firewall Rule and Validate // string firewallRuleName = SqlManagementTestUtilities.GenerateName(testPrefix); FirewallRule toCreate = new FirewallRule() { StartIpAddress = "0.0.0.0", EndIpAddress = "0.0.0.0" }; var fr1 = sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, firewallRuleName, toCreate); SqlManagementTestUtilities.ValidateFirewallRule(toCreate, fr1, firewallRuleName); // Update Firewall Rule and Validate toCreate = new FirewallRule() { StartIpAddress = "1.1.1.1", EndIpAddress = "255.255.255.255" }; fr1 = sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, firewallRuleName, toCreate); SqlManagementTestUtilities.ValidateFirewallRule(toCreate, fr1, firewallRuleName); } }
void SetRules() { string remoteAddresses = RangeCalculator.GetRemoteAddresses(addresses); // If the firewall rules aren't set yet. if (!set) { FirewallRule.CreateInbound(remoteAddresses, true, false); FirewallRule.CreateOutbound(remoteAddresses, true, false); active = true; set = true; UpdateActive(); return; } // If they are set but not enabled. if (set && !active) { FirewallRule.CreateInbound(remoteAddresses, true, true); FirewallRule.CreateOutbound(remoteAddresses, true, true); active = true; UpdateActive(); return; } // If they are active and set. if (active && set) { FirewallRule.CreateInbound(remoteAddresses, false, true); FirewallRule.CreateOutbound(remoteAddresses, false, true); UpdateNotActive(); active = false; } }
private void btnApply_Click(object sender, RoutedEventArgs e) { ProgramList.ID id = mEventList.ElementAt(curIndex); long expiration = GetExpiration(); Program.Config.AccessLevels NetAccess = (Program.Config.AccessLevels)(cmbAccess.SelectedItem as ComboBoxItem).Tag; if (NetAccess == Program.Config.AccessLevels.CustomConfig) { if (!MakeCustom(id, expiration)) { return; } } else if (NetAccess == Program.Config.AccessLevels.StopNotify) { Program prog = App.itf.GetProgram(id); if (expiration != 0) { prog.config.SilenceUntill = expiration; } else { prog.config.Notify = false; } App.itf.UpdateProgram(prog.guid, prog.config); } else { switch (NetAccess) { case Program.Config.AccessLevels.FullAccess: // add and enable allow all rule App.itf.UpdateRule(FirewallRule.MakeAllowRule(id, Firewall.Directions.Bidirectiona, expiration)); break; case Program.Config.AccessLevels.LocalOnly: // create block rule only of we operate in blacklist mode //if (App.itf.GetFilteringMode() == Firewall.FilteringModes.BlackList) //{ //add and enable block rules for the internet App.itf.UpdateRule(FirewallRule.MakeBlockInetRule(id, Firewall.Directions.Bidirectiona, expiration)); //} //add and enable allow rules for the lan App.itf.UpdateRule(FirewallRule.MakeAllowLanRule(id, Firewall.Directions.Bidirectiona, expiration)); break; case Program.Config.AccessLevels.BlockAccess: // add and enable broad block rules App.itf.UpdateRule(FirewallRule.MakeBlockRule(id, Firewall.Directions.Bidirectiona, expiration)); break; } } PopEntry(); }
/// <summary> /// Initializes <see cref="_rule"/> from existing windows firewall rule or generating new one if not found. also populates <see cref="_rules"/> with managed rules. /// </summary> private void initManagedRule() { for (int _ruleCount = 0; _ruleCount < _settings.MaxRulesCount; ++_ruleCount) { if (_ruleCount + 1 == _settings.MaxRulesCount) { throw new Exception($"Max rules reached. ({_settings.MaxRulesCount})"); } // a counter is appended to the rule name to support more than 1000 records and be able to manage all of them var ruleName = $"{_settings.RuleName}_{_ruleCount}"; var ruleObj = FirewallHelper.Find(ruleName); if (ruleObj == null) { // we assume there is no manual modifications on our firewall rules and it is managed only by this application generateRule(_ruleCount); break; } var rule = new FirewallRule(ruleObj, _settings.IsApplyToRemoteAddresses, _settings.IsApplyToLocalAddresses); _rules.Add(rule); if (rule.IsAddressCountLimitReached) { // generate new rule or find other existing rule where limit is not reached continue; } // record limit is not reached on this rule _rule = rule; break; } }
public async stt::Task UpdateIngressRuleRequestObjectAsync() { moq::Mock <Firewall.FirewallClient> mockGrpcClient = new moq::Mock <Firewall.FirewallClient>(moq::MockBehavior.Strict); UpdateIngressRuleRequest request = new UpdateIngressRuleRequest { Name = "name1c9368b0", Rule = new FirewallRule(), UpdateMask = new wkt::FieldMask(), }; FirewallRule expectedResponse = new FirewallRule { Priority = 1546225849, Action = FirewallRule.Types.Action.Deny, SourceRange = "source_range8d355d94", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateIngressRuleAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <FirewallRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FirewallClient client = new FirewallClientImpl(mockGrpcClient.Object, null); FirewallRule responseCallSettings = await client.UpdateIngressRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FirewallRule responseCancellationToken = await client.UpdateIngressRuleAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); }
protected override void OnClosed(EventArgs e) { _source.RemoveHook(HwndHook); _source = null; UnregisterHotKey(); FirewallRule.DeleteRules(); base.OnClosed(e); }
protected async Task Test(SqlServer model, FirewallRule r) { using (var client = await CreateClient()) { var options = CreateFirewallOptions(model); var response = await client.FirewallRules.CreateOrUpdateAsync(Region.Name, model.Name, RuleName, options); } }
private void removeButton_Click(object sender, EventArgs e) { if (this.dataGridView1.SelectedRows.Count > 0 && MessageBox.Show("Do you want to remove the selected rule?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { FirewallRule item = (FirewallRule)this.dataGridView1.SelectedRows[0].DataBoundItem; Configuration.GetConfig().Rules.Remove(item); this.SaveConfigAndRefresh(); } }
public LogItem(Program.LogEntry entry, string name) { this.entry = entry; this.name = name != null ? name : "[unknown progream]"; this.IsLocal = NetFunc.IsLocalHost(entry.FwEvent.RemoteAddress); this.IsMulti = NetFunc.IsMultiCast(entry.FwEvent.RemoteAddress); this.IsLan = FirewallRule.MatchAddress(entry.FwEvent.RemoteAddress, FirewallRule.AddrKeywordLocalSubnet); }
public void ClientConnectionSetFirewallExceptionState(string connectionName, string connectionId, string programName, int firewallRule) { EnsureValidClientConnection(connectionName, connectionId); FirewallExceptionState firewallExceptionState = new FirewallExceptionState(programName); FirewallRule firewallExceptionStateValue = (FirewallRule)firewallRule; StateManager.Current.Transition(connectionName, firewallExceptionState, firewallExceptionStateValue); }
public static FirewallRule Get_FirewallRuleByName(string ruleName) { if (string.IsNullOrEmpty(ruleName)) { throw new Exception("Can't get rule without name!"); } if (ruleName.Any(char.IsWhiteSpace)) { throw new Exception("Rule name contains whitespaces!"); } var routerConfig = SshConnection.Send_CustomCommand($"uci show firewall.{ruleName}"); var currentConfiguratrion = SshConnection.ParseAnswerToDictionary(routerConfig); var rule = new FirewallRule { RuleName = ruleName }; if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.name")) { rule.FriendlyName = currentConfiguratrion[$"firewall.{ruleName}.name"].Trim('\''); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.src_mac")) { rule.Src_mac = currentConfiguratrion[$"firewall.{ruleName}.src_mac"].Trim().Trim('\'').Split(','); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.src_ip")) { rule.Src_ip = currentConfiguratrion[$"firewall.{ruleName}.src_ip"].Trim().Trim('\'').Split(','); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.src_port")) { rule.Src_port = currentConfiguratrion[$"firewall.{ruleName}.src_port"].Trim().Trim('\'').Split(','); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.dest_ip")) { rule.Dest_ip = currentConfiguratrion[$"firewall.{ruleName}.dest_ip"].Trim().Trim('\'').Split(','); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.dest_port")) { rule.Dest_port = currentConfiguratrion[$"firewall.{ruleName}.dest_port"].Trim().Trim('\'').Split(','); } if (currentConfiguratrion.ContainsKey($"firewall.{ruleName}.enabled")) { rule.Enabled = currentConfiguratrion[$"firewall.{ruleName}.enabled"].Trim('\''); } return(rule); }
public void Can_add_simple_udp_rule() { FirewallManager sut = new FirewallManager(); var rules = new FirewallRule[] { new FirewallRule("test", 1000, 1000, "any") }; sut.ApplyUdpRules(rules); }
/// <summary>Snippet for GetIngressRule</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void GetIngressRuleRequestObject() { // Create client FirewallClient firewallClient = FirewallClient.Create(); // Initialize request argument(s) GetIngressRuleRequest request = new GetIngressRuleRequest { Name = "", }; // Make the request FirewallRule response = firewallClient.GetIngressRule(request); }
static FirewallRule CreateOrUpdateFirewallRule(SqlManagementClient sqlMgmtClient, string resourceGroupName, string serverName, string firewallRuleName, string startIpAddress, string endIpAddress) { FirewallRule firewallParameters = new FirewallRule() { StartIpAddress = startIpAddress, EndIpAddress = endIpAddress }; FirewallRule firewallResult = sqlMgmtClient.FirewallRules.CreateOrUpdate(resourceGroupName, serverName, firewallRuleName, firewallParameters); return(firewallResult); }
public override bool Load(XmlNode entryNode) { if (!base.Load(entryNode)) { return(false); } foreach (XmlNode node in entryNode.ChildNodes) { if (node.Name == "ProgID") { ProgID = new ProgramID(); ProgID.Load(node); } else if (node.Name == "State") { Enum.TryParse <States>(node.InnerText, out State); } //else if (node.Name == "Changed") // bool.TryParse(node.InnerText, out Changed); else if (node.Name == "LastChangedTime") { DateTime.TryParse(node.InnerText, out LastChangedTime); } else if (node.Name == "ChangedCount") { int.TryParse(node.InnerText, out ChangedCount); } else if (node.Name == "Expiration") { UInt64.TryParse(node.InnerText, out Expiration); } else if (node.Name == "HitCount") { Int64.TryParse(node.InnerText, out HitCount); } else if (node.Name == "Backup") { Backup = new FirewallRule(); if (!Backup.Load(node)) { Backup = null; } } } return(ProgID != null); }
protected override void OnClosed(EventArgs e) { _source.RemoveHook(HwndHook); _source = null; UnregisterHotKey(); foreach (Game g in games) { FirewallRule.DeleteRules(g); } base.OnClosed(e); }
public FormEditRule(FirewallRule rule) : this() { this.Rule = rule; if (this.Rule == null) { this.Rule = new FirewallRule(); return; } FillControls(); }
public void FirewallCreate() { Configure(); fw = new FirewallRule { Properties = new FirewallruleProperties { Protocol = "TCP", Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(), } }; fw = fwApi.Create(datacenter.Id, server.Id, nic.Id, fw); DoWait(fw.Request); Assert.IsNotNull(fw); }
private bool MakeCustom(ProgramList.ID id, long expiration, ConEntry entry = null) { FirewallRule rule = new FirewallRule() { guid = Guid.Empty, Profile = (int)Firewall.Profiles.All, Interface = (int)Firewall.Interfaces.All, Enabled = true }; rule.mID = id; rule.Name = Translate.fmt("custom_rule", id.GetDisplayName()); rule.Grouping = FirewallRule.RuleGroup; rule.Expiration = expiration; if (entry != null) { rule.Direction = entry.Entry.Direction; rule.Protocol = entry.Entry.Protocol; switch (entry.Entry.Protocol) { /*case (int)FirewallRule.KnownProtocols.ICMP: * case (int)FirewallRule.KnownProtocols.ICMPv6: * * break;*/ case (int)FirewallRule.KnownProtocols.TCP: case (int)FirewallRule.KnownProtocols.UDP: rule.LocalPorts = "*"; rule.RemotePorts = entry.Entry.RemotePort.ToString(); break; } rule.LocalAddresses = "*"; rule.RemoteAddresses = entry.Entry.RemoteAddress.ToString(); } else { rule.Direction = Firewall.Directions.Bidirectiona; } RuleWindow ruleWnd = new RuleWindow(new List <ProgramList.ID>() { id }, rule); if (ruleWnd.ShowDialog() != true) { return(false); } if (!App.itf.UpdateRule(rule)) { MessageBox.Show(Translate.fmt("msg_rule_failed"), App.mName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } return(true); }
protected override void OnClosed(EventArgs e) { _source.RemoveHook(HwndHook); _source = null; UnregisterHotKey(); FirewallRule.DeleteRules(); foreach (NetworkInterfaceItem nic in _nics) { nic.Enable(); } base.OnClosed(e); }
/// <summary>Snippet for GetIngressRuleAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetIngressRuleRequestObjectAsync() { // Create client FirewallClient firewallClient = await FirewallClient.CreateAsync(); // Initialize request argument(s) GetIngressRuleRequest request = new GetIngressRuleRequest { Name = "", }; // Make the request FirewallRule response = await firewallClient.GetIngressRuleAsync(request); }
private bool MakeCustom(Program prog, UInt64 expiration, ConEntry entry = null) { FirewallRule rule = new FirewallRule() { guid = null, Profile = (int)FirewallRule.Profiles.All, Interface = (int)FirewallRule.Interfaces.All, Enabled = true }; rule.ProgID = prog.ID; rule.Name = FirewallManager.MakeRuleName(FirewallManager.CustomName, expiration != 0, prog.Description); rule.Grouping = FirewallManager.RuleGroup; if (entry != null) { rule.Direction = entry.Entry.FwEvent.Direction; rule.Protocol = (int)entry.Entry.FwEvent.Protocol; switch (entry.Entry.FwEvent.Protocol) { /*case (int)FirewallRule.KnownProtocols.ICMP: * case (int)FirewallRule.KnownProtocols.ICMPv6: * * break;*/ case (int)FirewallRule.KnownProtocols.TCP: case (int)FirewallRule.KnownProtocols.UDP: rule.LocalPorts = "*"; rule.RemotePorts = entry.Entry.FwEvent.RemotePort.ToString(); break; } rule.LocalAddresses = "*"; rule.RemoteAddresses = entry.Entry.FwEvent.RemoteAddress.ToString(); } else { rule.Direction = FirewallRule.Directions.Bidirectiona; } RuleWindow ruleWnd = new RuleWindow(new List <Program>() { prog }, rule); if (ruleWnd.ShowDialog() != true) { return(false); } if (!App.client.UpdateRule(rule, expiration)) { MessageBox.Show(Translate.fmt("msg_rule_failed"), App.mName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } return(true); }
private void editButton_Click(object sender, EventArgs e) { if (this.dataGridView1.SelectedRows.Count > 0) { FirewallRule usb = (FirewallRule)this.dataGridView1.SelectedRows[0].DataBoundItem; FormEditRule FormEditRule = new FormEditRule(usb); if (FormEditRule.ShowDialog() == DialogResult.OK) { this.SaveConfigAndRefresh(); } } }
/// <summary>Snippet for CreateIngressRule</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateIngressRuleRequestObject() { // Create client FirewallClient firewallClient = FirewallClient.Create(); // Initialize request argument(s) CreateIngressRuleRequest request = new CreateIngressRuleRequest { Parent = "", Rule = new FirewallRule(), }; // Make the request FirewallRule response = firewallClient.CreateIngressRule(request); }
private void Delete_Click(object sender, RoutedEventArgs e) { if (lsbAddresses.SelectedIndex != -1) { addresses.Remove(IPAddress.Parse(lsbAddresses.SelectedItem.ToString())); lsbAddresses.Items.Refresh(); whitelist.Save(addresses); set = false; active = false; FirewallRule.DeleteRules(); SetIpCount(); UpdateNotActive(); } }
/// <summary> /// 创建新增命令 /// </summary> /// <returns></returns> public string CreateDeleteCommand(FirewallRule rule) { StringBuilder sbCmd = new StringBuilder(); sbCmd.Append("firewall-cmd --permanent --remove-rich-rule=\"rule family=\"ipv4\" source address=\""); sbCmd.Append(rule.IP); sbCmd.Append("\" port protocol=\""); sbCmd.Append(rule.Protocol); sbCmd.Append("\" port=\"");; sbCmd.Append(rule.Port.ToString()); sbCmd.Append("\" accept\""); return(sbCmd.ToString()); }
public void AddToFirewallRules(FirewallRule firewallRule) { base.AddObject("FirewallRules", firewallRule); }
public static FirewallRule CreateFirewallRule(string name, global::System.DateTime createDate, global::System.DateTime modifyDate) { FirewallRule firewallRule = new FirewallRule(); firewallRule.Name = name; firewallRule.CreateDate = createDate; firewallRule.ModifyDate = modifyDate; return firewallRule; }
/// <summary> /// InitObject: Initializes the VShieldEdgeConfig object. /// </summary> /// <returns>VShieldEdgeConfig</returns> private VShieldEdgeConfig InitObject() { VShieldEdgeConfig vsec = new VShieldEdgeConfig(); FirewallConfig fwconf = new FirewallConfig(); FirewallRule fwrule = new FirewallRule(); PortInfo dpi = new PortInfo(); PortInfo spi = new PortInfo(); IpInfo dip = new IpInfo(); IpInfo sip = new IpInfo(); try { fwrule.destinationIpAddress = dip; fwrule.destinationPort = dpi; fwrule.ruleId = 0; fwrule.sourceIpAddress = sip; fwrule.sourcePort = spi; if (_FirewallRules.FirewallConfig.Count > 0) { _FirewallRules.FirewallConfig.Add(fwrule); return _FirewallRules; } else { fwconf.Add(fwrule); vsec.FirewallConfig = fwconf; return vsec; } } catch (Exception e) { WriteObject("C-Sharp Exception: " + e); return null; } }
/// <summary> /// Create a Firewall Rule This will add a Firewall Rule to the NIC /// </summary> /// <param name="datacenterId"></param> /// <param name="serverId"></param> /// <param name="nicId"></param> /// <param name="firewallrule">Firewall Rule to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n - depth=0: only direct properties are included. Children (servers etc.) are not included\n - depth=1: direct properties and children references are included\n - depth=2: direct properties and children properties are included\n - depth=3: direct properties and children properties and children's children are included\n - depth=... and so on</param> /// <returns>Task of ApiResponse (FirewallRule)</returns> public async System.Threading.Tasks.Task<ApiResponse<FirewallRule>> CreateAsyncWithHttpInfo(string datacenterId, string serverId, string nicId, FirewallRule firewallrule, bool? parameter = null, int? depth = null) { // verify the required parameter 'datacenterId' is set if (datacenterId == null) throw new ApiException(400, "Missing required parameter 'datacenterId' when calling Create"); // verify the required parameter 'serverId' is set if (serverId == null) throw new ApiException(400, "Missing required parameter 'serverId' when calling Create"); // verify the required parameter 'nicId' is set if (nicId == null) throw new ApiException(400, "Missing required parameter 'nicId' when calling Create"); // verify the required parameter 'firewallrule' is set if (firewallrule == null) throw new ApiException(400, "Missing required parameter 'firewallrule' when calling Create"); var path_ = "/datacenters/{datacenterId}/servers/{serverId}/nics/{nicId}/firewallrules"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "application/json", "application/vnd.profitbricks.resource+json" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/vnd.profitbricks.resource+json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (datacenterId != null) pathParams.Add("datacenterId", Configuration.ApiClient.ParameterToString(datacenterId)); // path parameter if (serverId != null) pathParams.Add("serverId", Configuration.ApiClient.ParameterToString(serverId)); // path parameter if (nicId != null) pathParams.Add("nicId", Configuration.ApiClient.ParameterToString(nicId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter postBody = Configuration.ApiClient.Serialize(firewallrule); // http body (model) parameter // authentication (basicAuth) required // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Create: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<FirewallRule>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (FirewallRule)Configuration.ApiClient.Deserialize(response, typeof(FirewallRule))); }
/// <summary> /// Create a Firewall Rule This will add a Firewall Rule to the NIC /// </summary> /// <param name="datacenterId"></param> /// <param name="serverId"></param> /// <param name="nicId"></param> /// <param name="firewallrule">Firewall Rule to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n - depth=0: only direct properties are included. Children (servers etc.) are not included\n - depth=1: direct properties and children references are included\n - depth=2: direct properties and children properties are included\n - depth=3: direct properties and children properties and children's children are included\n - depth=... and so on</param> /// <returns>Task of FirewallRule</returns> public async System.Threading.Tasks.Task<FirewallRule> CreateAsync(string datacenterId, string serverId, string nicId, FirewallRule firewallrule, bool? parameter = null, int? depth = null) { ApiResponse<FirewallRule> response = await CreateAsyncWithHttpInfo(datacenterId, serverId, nicId, firewallrule, parameter, depth); return response.Data; }
/// <summary> /// Create a Firewall Rule This will add a Firewall Rule to the NIC /// </summary> /// <param name="datacenterId"></param> /// <param name="serverId"></param> /// <param name="nicId"></param> /// <param name="firewallrule">Firewall Rule to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n - depth=0: only direct properties are included. Children (servers etc.) are not included\n - depth=1: direct properties and children references are included\n - depth=2: direct properties and children properties are included\n - depth=3: direct properties and children properties and children's children are included\n - depth=... and so on</param> /// <returns>FirewallRule</returns> public FirewallRule Create(string datacenterId, string serverId, string nicId, FirewallRule firewallrule, bool? parameter = null, int? depth = null) { ApiResponse<FirewallRule> response = CreateWithHttpInfo(datacenterId, serverId, nicId, firewallrule, parameter, depth); response.Data.Request = response.Headers["Location"]; return response.Data; }
/// <summary> /// Modify a Firewall Rule You can use update attributes of a resource /// </summary> /// <param name="datacenterId"></param> /// <param name="serverId"></param> /// <param name="nicId"></param> /// <param name="firewallruleId"></param> /// <param name="firewallrule">Modified Firewall Rule</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n - depth=0: only direct properties are included. Children (servers etc.) are not included\n - depth=1: direct properties and children references are included\n - depth=2: direct properties and children properties are included\n - depth=3: direct properties and children properties and children's children are included\n - depth=... and so on</param> /// <returns>FirewallRule</returns> public FirewallRule Update(string datacenterId, string serverId, string nicId, string firewallruleId, FirewallRule firewallrule, bool? parameter = null, int? depth = null) { ApiResponse<FirewallRule> response = UpdateWithHttpInfo(datacenterId, serverId, nicId, firewallruleId, firewallrule, parameter, depth); return response.Data; }