Merge pull request #1084 from ekholabs/improvement/remove_scripts-CLOUDSTACK-9067

CLOUDSTACK-9067 - As I developer I want to remove all the unused router-shell scripts from ACSThis PR removes the unused shell scripts that were present in the ACS project. Those script were replaced by the.

Some of the scripts are used by the HyperV Resource, which were hardcoded. I took the opportunity to use the Java constants over there as well, so the next one touching the code will know they exist and won't hardcode anything.

The following task were applied:

* Remove the shell files and the Java constants that were mapping them;
* Apply the use of the Java constants to the HyperV Resource class;
* Wrap the String.format() method in the StringUtils so we can test the changes in the HyperV Resource class.

The last point was added because I do not have a HyperV test environment. Hence, I wanted to make sure the tiny code I changed is covered at least by unit tests.

* pr/1084:
  CLOUDSTACK-9067 - Replaces hardcoded paths with the VRScripts constants.
  CLOUDSTACK-9067 - Fomatting the code of HypervDirectConnectResource class
  CLOUDSTACK-9067 - Remove old script file from the project

Signed-off-by: Remi Bergsma <github@remi.nl>
This commit is contained in:
Remi Bergsma 2015-11-19 17:58:42 +01:00
commit 791f9dfe5f
18 changed files with 439 additions and 3223 deletions

View File

@ -45,37 +45,25 @@ public class VRScripts {
// New scripts for use with chef
public static final String UPDATE_CONFIG = "update_config.py";
// Script still in use - mostly by HyperV
public static final String S2SVPN_CHECK = "checkbatchs2svpn.sh";
public static final String S2SVPN_IPSEC = "ipsectunnel.sh";
public static final String DHCP = "edithosts.sh";
public static final String DNSMASQ_CONFIG = "dnsmasq.sh";
public static final String FIREWALL_EGRESS = "firewall_egress.sh";
public static final String FIREWALL_INGRESS = "firewall_ingress.sh";
public static final String FIREWALL_NAT = "firewall_nat.sh";
public static final String IPALIAS_CREATE = "createipAlias.sh";
public static final String IPALIAS_DELETE = "deleteipAlias.sh";
public static final String IPASSOC = "ipassoc.sh";
public static final String LB = "loadbalancer.sh";
public static final String MONITOR_SERVICE = "monitor_service.sh";
public static final String ROUTER_ALERTS = "getRouterAlerts.sh";
public static final String PASSWORD = "savepassword.sh";
public static final String ROUTER_ALERTS = "getRouterAlerts.sh";
public static final String RVR_CHECK = "checkrouter.sh";
public static final String RVR_BUMPUP_PRI = "bumpup_priority.sh";
public static final String VMDATA = "vmdata.py";
public static final String RVR_BUMPUP_PRI = "bumpup_priority.sh";
public static final String VERSION = "get_template_version.sh";
public static final String VPC_ACL = "vpc_acl.sh";
public static final String VPC_GUEST_NETWORK = "vpc_guestnw.sh";
public static final String VPC_IPASSOC = "vpc_ipassoc.sh";
public static final String VPC_LB = "vpc_loadbalancer.sh";
public static final String VPC_PRIVATEGW = "vpc_privateGateway.sh";
public static final String VPC_PRIVATEGW_ACL = "vpc_privategw_acl.sh";
public static final String VPC_PORTFORWARDING = "vpc_portforwarding.sh";
public static final String VPC_SOURCE_NAT = "vpc_snat.sh";
public static final String VPC_STATIC_NAT = "vpc_staticnat.sh";
public static final String VPC_STATIC_ROUTE = "vpc_staticroute.sh";
public static final String VPN_L2TP = "vpn_l2tp.sh";
public static final String UPDATE_HOST_PASSWD = "update_host_passwd.sh";
public static final String VR_CFG = "vr_cfg.sh";
}
}

View File

@ -24,8 +24,6 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@ -83,9 +81,6 @@ import com.cloud.network.vpc.NetworkACLItem.TrafficType;
import com.cloud.network.vpc.VpcGateway;
import com.cloud.utils.ExecutionResult;
import com.cloud.utils.net.NetUtils;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@ -154,18 +149,14 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
private void verifyFile(final NetworkElementCommand cmd, final String path, final String filename, final String content) {
if (cmd instanceof AggregationControlCommand) {
verifyFile((AggregationControlCommand)cmd, path, filename, content);
verifyFile(cmd, path, filename, content);
} else if (cmd instanceof LoadBalancerConfigCommand) {
verifyFile((LoadBalancerConfigCommand)cmd, path, filename, content);
}
}
protected void verifyCommand(final NetworkElementCommand cmd, final String script, final String args) {
if (cmd instanceof SetPortForwardingRulesVpcCommand) {
verifyArgs((SetPortForwardingRulesVpcCommand) cmd, script, args);
} else if (cmd instanceof SetPortForwardingRulesCommand) {
verifyArgs((SetPortForwardingRulesCommand) cmd, script, args);
} else if (cmd instanceof SetStaticRouteCommand) {
if (cmd instanceof SetStaticRouteCommand) {
verifyArgs((SetStaticRouteCommand) cmd, script, args);
} else if (cmd instanceof SetStaticNatRulesCommand) {
verifyArgs((SetStaticNatRulesCommand) cmd, script, args);
@ -175,18 +166,10 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
verifyArgs((SavePasswordCommand)cmd, script, args);
} else if (cmd instanceof DhcpEntryCommand) {
verifyArgs((DhcpEntryCommand)cmd, script, args);
} else if (cmd instanceof CreateIpAliasCommand) {
verifyArgs((CreateIpAliasCommand)cmd, script, args);
} else if (cmd instanceof DnsMasqConfigCommand) {
verifyArgs((DnsMasqConfigCommand)cmd, script, args);
} else if (cmd instanceof DeleteIpAliasCommand) {
verifyArgs((DeleteIpAliasCommand)cmd, script, args);
} else if (cmd instanceof VmDataCommand) {
verifyArgs((VmDataCommand)cmd, script, args);
} else if (cmd instanceof SetFirewallRulesCommand) {
verifyArgs((SetFirewallRulesCommand)cmd, script, args);
} else if (cmd instanceof BumpUpPriorityCommand) {
verifyArgs((BumpUpPriorityCommand)cmd, script, args);
} else if (cmd instanceof RemoteAccessVpnCfgCommand) {
verifyArgs((RemoteAccessVpnCfgCommand)cmd, script, args);
} else if (cmd instanceof VpnUsersCfgCommand) {
@ -229,11 +212,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
assertTrue(answer.getResult());
}
private void verifyArgs(final BumpUpPriorityCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.RVR_BUMPUP_PRI);
assertEquals(args, null);
}
@Test
public void testSetPortForwardingRulesVpcCommand() {
final SetPortForwardingRulesVpcCommand cmd = generateSetPortForwardingRulesVpcCommand();
@ -257,21 +235,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(final SetPortForwardingRulesVpcCommand cmd, final String script, final String args) {
assertTrue(script.equals(VRScripts.VPC_PORTFORWARDING));
_count ++;
switch (_count) {
case 1:
assertEquals(args, "-A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80");
break;
case 2:
assertEquals(args, "-D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080");
break;
default:
fail("Failed to recongize the match!");
}
}
@Test
public void testSetPortForwardingRulesCommand() {
final SetPortForwardingRulesCommand cmd = generateSetPortForwardingRulesCommand();
@ -294,21 +257,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(final SetPortForwardingRulesCommand cmd, final String script, final String args) {
assertTrue(script.equals(VRScripts.FIREWALL_NAT));
_count ++;
switch (_count) {
case 1:
assertEquals(args, "-A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80");
break;
case 2:
assertEquals(args, "-D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080");
break;
default:
fail("Failed to recongize the match!");
}
}
@Test
public void testIpAssocCommand() {
final IpAssocCommand cmd = generateIpAssocCommand();
@ -383,22 +331,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
assertEquals(VRScripts.UPDATE_CONFIG, script);
assertEquals(VRScripts.IP_ASSOCIATION_CONFIG, args);
break;
case 2:
assertEquals(script, VRScripts.VPC_PRIVATEGW);
assertEquals(args, " -A -l 64.1.1.10 -c eth2");
break;
case 3:
assertEquals(script, VRScripts.VPC_IPASSOC);
assertEquals(args, " -D -l 64.1.1.11 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0");
break;
case 4:
assertEquals(script, VRScripts.VPC_PRIVATEGW);
assertEquals(args, " -D -l 64.1.1.11 -c eth2");
break;
case 5:
assertEquals(script, VRScripts.VPC_IPASSOC);
assertEquals(args, " -A -l 65.1.1.11 -c eth2 -g 65.1.1.1 -m 24 -n 65.1.1.0");
break;
default:
fail("Failed to recongize the match!");
}
@ -676,17 +608,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(final SetFirewallRulesCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.FIREWALL_INGRESS);
//Since the arguments are generated with a Set
//one can not make a bet on the order
assertTrue(args.startsWith(" -F -a "));
assertTrue(args.contains("64.10.10.10:ICMP:0:0:10.10.1.1/24-10.10.1.2/24:"));
assertTrue(args.contains("64.10.10.10:reverted:0:0:0:"));
assertTrue(args.contains("64.10.10.10:TCP:22:80:10.10.1.1/24-10.10.1.2/24:"));
}
@Test
public void testVmDataCommand() {
final Answer answer = _resource.executeRequest(generateVmDataCommand());
@ -804,11 +725,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(final CreateIpAliasCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.IPALIAS_CREATE);
assertEquals(args, "1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-");
}
@Test
public void testDeleteIpAliasCommand() {
final Answer answer = _resource.executeRequest(generateDeleteIpAliasCommand());
@ -825,11 +741,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(final DeleteIpAliasCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.IPALIAS_DELETE);
assertEquals(args, "1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-- 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-");
}
@Test
public void testDnsMasqConfigCommand() {
final Answer answer = _resource.executeRequest(generateDnsMasqConfigCommand());
@ -951,10 +862,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
assertEquals(script, VRScripts.LB);
assertEquals(args, " -i 10.1.10.2 -f " + _file + " -a 64.10.1.10:80:, -s 10.1.10.2:8081:0/0:,,");
break;
case 4:
assertEquals(script, VRScripts.VPC_LB);
assertEquals(args, " -i 10.1.10.2 -f " + _file + " -a 64.10.1.10:80:, -s 10.1.10.2:8081:0/0:,,");
break;
default:
fail();
}
@ -1009,122 +916,4 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
assertTrue(args.startsWith("-c /var/cache/cloud/VR-"));
assertTrue(args.endsWith(".cfg"));
}
protected void verifyFile(final AggregationControlCommand cmd, final String path, final String filename, final String content) {
assertEquals(path, "/var/cache/cloud/");
assertTrue(filename.startsWith("VR-"));
assertTrue(filename.endsWith(".cfg"));
final Collection<String> filteredScripts = Collections2.transform(Collections2.filter (
Arrays.asList(content.split("</?script>")), new Predicate<String>() {
@Override
public boolean apply(final String str) {
return str.trim().startsWith("/opt/cloud");
}
}), new Function<String, String>() {
@Override
public String apply(final String str) {
return str.trim();
}
});
final String[] scripts = filteredScripts.toArray(new String[filteredScripts
.size()]);
assertEquals(
"/opt/cloud/bin/ipassoc.sh -A -s -f -l 64.1.1.10/24 -c eth2 -g 64.1.1.1",
scripts[0]);
assertEquals(
"/opt/cloud/bin/ipassoc.sh -D -l 64.1.1.11/24 -c eth2 -g 64.1.1.1",
scripts[1]);
assertEquals(
"/opt/cloud/bin/ipassoc.sh -A -l 65.1.1.11/24 -c eth2 -g 65.1.1.1",
scripts[2]);
assertEquals(
"/opt/cloud/bin/vpc_ipassoc.sh -A -l 64.1.1.10 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0",
scripts[3]);
assertEquals(
"/opt/cloud/bin/vpc_privateGateway.sh -A -l 64.1.1.10 -c eth2",
scripts[4]);
assertEquals(
"/opt/cloud/bin/vpc_ipassoc.sh -D -l 64.1.1.11 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0",
scripts[5]);
assertEquals(
"/opt/cloud/bin/vpc_privateGateway.sh -D -l 64.1.1.11 -c eth2",
scripts[6]);
assertEquals(
"/opt/cloud/bin/vpc_ipassoc.sh -A -l 65.1.1.11 -c eth2 -g 65.1.1.1 -m 24 -n 65.1.1.0",
scripts[7]);
//the list generated by SetFirewallCmd is actually generated through a Set
//therefore we can not bet on the order of the parameters
assertTrue(
scripts[8].matches("/opt/cloud/bin/firewall_ingress.sh -F -a .*"));
assertTrue(
scripts[8].contains("64.10.10.10:ICMP:0:0:10.10.1.1/24-10.10.1.2/24:"));
assertTrue(
scripts[8].contains("64.10.10.10:TCP:22:80:10.10.1.1/24-10.10.1.2/24:"));
assertTrue(
scripts[8].contains("64.10.10.10:reverted:0:0:0:"));
assertEquals(
"/opt/cloud/bin/firewall_nat.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80",
scripts[9]);
assertEquals(
"/opt/cloud/bin/firewall_nat.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080",
scripts[10]);
assertEquals(
"/opt/cloud/bin/vpc_portforwarding.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80",
scripts[11]);
assertEquals(
"/opt/cloud/bin/vpc_portforwarding.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080",
scripts[12]);
assertEquals(
"/opt/cloud/bin/createIpAlias.sh 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-",
scripts[13]);
assertEquals(
"/opt/cloud/bin/deleteIpAlias.sh 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-- 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-",
scripts[14]);
assertEquals(
"/opt/cloud/bin/dnsmasq.sh 10.1.20.2:10.1.20.1:255.255.255.0:10.1.20.5-10.1.21.2:10.1.21.1:255.255.255.0:10.1.21.5-",
scripts[15]);
assertEquals(
"/opt/cloud/bin/vpn_l2tp.sh -r 10.10.1.10-10.10.1.20 -p sharedkey -s 124.10.10.10 -l 10.10.1.1 -c -C 10.1.1.1/24 -i eth2",
scripts[16]);
assertEquals(
"/opt/cloud/bin/vpn_l2tp.sh -d -s 124.10.10.10 -C 10.1.1.1/24 -i eth2",
scripts[17]);
assertEquals(
"/opt/cloud/bin/vpn_l2tp.sh -r 10.10.1.10-10.10.1.20 -p sharedkey -s 124.10.10.10 -l 10.10.1.1 -c -C 10.1.1.1/24 -i eth1",
scripts[18]);
assertEquals(
"/opt/cloud/bin/firewall_nat.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80",
scripts[19]);
assertEquals(
"/opt/cloud/bin/firewall_nat.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080",
scripts[20]);
assertEquals(
"/opt/cloud/bin/vpc_portforwarding.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80",
scripts[21]);
assertEquals(
"/opt/cloud/bin/vpc_portforwarding.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080",
scripts[22]);
assertEquals(
"/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -4 10.1.10.2 -h vm1",
scripts[23]);
assertEquals(
"/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -h vm1 -6 2001:db8:0:0:0:ff00:42:8329 -u 00:03:00:01:12:34:56:78:90:AB",
scripts[24]);
assertEquals(
"/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -4 10.1.10.2 -h vm1 -6 2001:db8:0:0:0:ff00:42:8329 -u 00:03:00:01:12:34:56:78:90:AB",
scripts[25]);
assertEquals("/opt/cloud/bin/savepassword.sh -v 10.1.10.4 -p 123pass",
scripts[26]);
assertEquals(
"/opt/cloud/bin/vmdata.py -d eyIxMC4xLjEwLjQiOltbInVzZXJkYXRhIiwidXNlci1kYXRhIiwidXNlci1kYXRhIl0sWyJtZXRhZGF0YSIsInNlcnZpY2Utb2ZmZXJpbmciLCJzZXJ2aWNlT2ZmZXJpbmciXSxbIm1ldGFkYXRhIiwiYXZhaWxhYmlsaXR5LXpvbmUiLCJ6b25lTmFtZSJdLFsibWV0YWRhdGEiLCJsb2NhbC1pcHY0IiwiMTAuMS4xMC40Il0sWyJtZXRhZGF0YSIsImxvY2FsLWhvc3RuYW1lIiwidGVzdC12bSJdLFsibWV0YWRhdGEiLCJwdWJsaWMtaXB2NCIsIjExMC4xLjEwLjQiXSxbIm1ldGFkYXRhIiwicHVibGljLWhvc3RuYW1lIiwiaG9zdG5hbWUiXSxbIm1ldGFkYXRhIiwiaW5zdGFuY2UtaWQiLCJpLTQtVk0iXSxbIm1ldGFkYXRhIiwidm0taWQiLCI0Il0sWyJtZXRhZGF0YSIsInB1YmxpYy1rZXlzIiwicHVibGlja2V5Il0sWyJtZXRhZGF0YSIsImNsb3VkLWlkZW50aWZpZXIiLCJDbG91ZFN0YWNrLXt0ZXN0fSJdXX0=",
scripts[27]);
}
}
}

View File

@ -85,6 +85,7 @@ import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.resource.virtualnetwork.VRScripts;
import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.dc.Vlan;
@ -614,7 +615,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
_clusterId = (String)params.get("cluster");
_updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, "update_host_passwd.sh");
_updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD);
if (_updateHostPasswdPath == null) {
throw new ConfigurationException("Unable to find update_host_passwd.sh");
}
@ -968,11 +969,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
protected void configureDiskActivityChecks(final Map<String, Object> params) {
_diskActivityCheckEnabled = Boolean.parseBoolean((String)params.get("vm.diskactivity.checkenabled"));
if (_diskActivityCheckEnabled) {
int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0);
final int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0);
if (timeout > 0) {
_diskActivityCheckTimeoutSeconds = timeout;
}
long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L);
final long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L);
if (inactiveTime > 0) {
_diskActivityInactiveThresholdMilliseconds = inactiveTime;
}
@ -1187,8 +1188,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
* @return
*/
boolean isInterface(final String fname) {
StringBuffer commonPattern = new StringBuffer();
for (String ifNamePrefix : _ifNamePrefixes) {
final StringBuffer commonPattern = new StringBuffer();
for (final String ifNamePrefix : _ifNamePrefixes) {
commonPattern.append("|(").append(ifNamePrefix).append(".*)");
}
if(fname.matches(commonPattern.toString())) {
@ -2076,7 +2077,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
s_logger.debug("Checking physical disk file at path " + volPath + " for disk activity to ensure vm is not running elsewhere");
try {
HypervisorUtils.checkVolumeFileForActivity(volPath, _diskActivityCheckTimeoutSeconds, _diskActivityInactiveThresholdMilliseconds, _diskActivityCheckFileSizeMin);
} catch (IOException ex) {
} catch (final IOException ex) {
throw new CloudRuntimeException("Unable to check physical disk file for activity", ex);
}
s_logger.debug("Disk activity check cleared");

View File

@ -1,129 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
usage() {
printf " %s <alias_count:ip:netmask;alias_count2:ip2:netmask2;....> \n" $(basename $0) >&2
}
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
PORTS_CONF=/etc/apache2/ports.conf
PORTS_CONF_BAK=/etc/ports.conf.bak
FAIL_DIR=/etc/failure_config
CMDLINE=$(cat /var/cache/cloud/cmdline | tr '\n' ' ')
if [ ! -d "$FAIL_DIR" ]
then
mkdir "$FAIL_DIR"
fi
#bakup ports.conf
cp "$PORTS_CONF" "$PORTS_CONF_BAK"
domain=$(echo "$CMDLINE" | grep -o " domain=.* " | sed -e 's/domain=//' | awk '{print $1}')
setup_apache2() {
local ip=$1
logger -t cloud "Setting up apache web server for $ip"
cp /etc/apache2/sites-available/default /etc/apache2/sites-available/ipAlias.${ip}.meta-data
cp /etc/apache2/sites-available/default-ssl /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data
cp /etc/apache2/ports.conf /etc/apache2/conf.d/ports.${ip}.meta-data.conf
sed -i -e "s/<VirtualHost.*>/<VirtualHost $ip:80>\nServerName $domain/" /etc/apache2/sites-available/ipAlias.${ip}.meta-data
sed -i -e "s/<VirtualHost.*>/<VirtualHost $ip:443>\nServerName $domain/" /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data
sed -i -e "/NameVirtualHost .*:80/d" /etc/apache2/conf.d/ports.${ip}.meta-data.conf
sed -i -e "s/Listen .*:80/Listen $ip:80/g" /etc/apache2/conf.d/ports.${ip}.meta-data.conf
sed -i -e "s/Listen .*:443/Listen $ip:443/g" /etc/apache2/conf.d/ports.${ip}.meta-data.conf
ln -s /etc/apache2/sites-available/ipAlias.${ip}.meta-data /etc/apache2/sites-enabled/ipAlias.${ip}.meta-data
ln -s /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data /etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data
}
var="$1"
cert="/root/.ssh/id_rsa.cloud"
config_ips=""
setDnsRules=0
while [ -n "$var" ]
do
var1=$(echo $var | cut -f1 -d "-")
alias_count=$( echo $var1 | cut -f1 -d ":" )
routerip=$(echo $var1 | cut -f2 -d ":")
netmask=$(echo $var1 | cut -f3 -d ":")
ifconfig eth0:$alias_count $routerip netmask $netmask up
setup_apache2 "$routerip"
config_ips="${config_ips}"$routerip":"
var=$( echo $var | sed "s/${var1}-//" )
setDnsRules=1
done
#restarting the apache server for the config to take effect.
service apache2 restart
result=$?
if [ "$result" -ne "0" ]
then
logger -t cloud "createIpAlias.sh: could not configure apache2 server"
logger -t cloud "createIpAlias.sh: reverting to the old config"
logger -t cloud "createIpAlias.sh: moving out the failure config to $FAIL_DIR"
while [ -n "$config_ips" ]
do
ip=$( echo $config_ips | cut -f1 -d ":" )
mv "/etc/apache2/sites-available/ipAlias.${ip}.meta-data" "$FAIL_DIR/ipAlias.${ip}.meta-data"
mv "/etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data" "$FAIL_DIR/ipAlias.${ip}-ssl.meta-data"
mv "/etc/apache2/conf.d/ports.${ip}.meta-data.conf" "$FAIL_DIR/ports.${ip}.meta-data.conf"
rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}.meta-data"
rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data"
config_ips=$( echo $config_ips | sed "s/${ip}://" )
done
service apache2 restart
unlock_exit $result $lock $locked
fi
if [ "$setDnsRules" -eq 1 ]
then
//check wether chain exist
iptables-save -t filter | grep 'dnsIpAlias_allow'
if [ $? -eq 0 ]
then
iptables -F dnsIpAlias_allow
else
//if not exist create it
iptables -N dnsIpAlias_allow
iptables -A INPUT -i eth0 -p tcp --dport 53 -j dnsIpAlias_allow
iptables -A INPUT -i eth0 -p udp --dport 53 -j dnsIpAlias_allow
fi
for cidr in $(ip addr | grep eth0 | grep inet | awk '{print $2}');
do
iptables -A dnsIpAlias_allow -i eth0 -p tcp --dport 53 -s $cidr -j ACCEPT
iptables -A dnsIpAlias_allow -i eth0 -p udp --dport 53 -s $cidr -j ACCEPT
done
else
iptables -D INPUT -i eth0 -p tcp --dport 53 -j dnsIpAlias_allow
iptables -D INPUT -i eth0 -p udp --dport 53 -j dnsIpAlias_allow
iptables -X dnsIpAlias_allow
fi
#restaring the password service to enable it on the ip aliases
/etc/init.d/cloud-passwd-srvr restart
unlock_exit $? $lock $locked

View File

@ -1,62 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
usage() {
printf " %s <alias_count:ip:netmask;alias_count2:ip2:netmask2;....> \n" $(basename $0) >&2
}
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
remove_apache_config() {
local ip=$1
logger -t cloud "removing apache web server config for $ip"
rm -f "/etc/apache2/sites-available/ipAlias.${ip}.meta-data"
rm -f "/etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data"
rm -f "/etc/apache2/conf.d/ports.${ip}.meta-data.conf"
rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data"
rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}.meta-data"
}
var="$1"
cert="/root/.ssh/id_rsa.cloud"
while [[ !( "$var" == "-" ) ]]
do
var1=$(echo $var | cut -f1 -d "-")
alias_count=$( echo $var1 | cut -f1 -d ":" )
routerip=$( echo $var1 | cut -f2 -d ":" )
ifconfig eth0:$alias_count down
remove_apache_config "$routerip"
var=$( echo $var | sed "s/${var1}-//" )
done
#restarting the apache server for the config to take effect.
service apache2 restart
releaseLockFile $lock $locked
iptables -F dnsIpAlias_allow
#recreating the active ip aliases
/opt/cloud/bin/createIpAlias.sh $2
unlock_exit $? $lock $locked

View File

@ -1,188 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# $Id: firewallRule_egress.sh 9947 2013-01-17 19:34:24Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/patches/xenserver/root/firewallRule_egress.sh $
# firewallRule_egress.sh -- allow some ports / protocols from vm instances
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
#set -x
usage() {
printf "Usage: %s: -a protocol:startport:endport:sourcecidrs> \n" $(basename $0) >&2
printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n"
}
fw_egress_remove_backup() {
# remove backup rules, ignore errors as they could not be present
sudo iptables -D FW_OUTBOUND -j _FW_EGRESS_RULES >/dev/null 2>&1
sudo iptables -F _FW_EGRESS_RULES >/dev/null 2>&1
sudo iptables -X _FW_EGRESS_RULES >/dev/null 2>&1
}
fw_egress_save() {
sudo iptables -E FW_EGRESS_RULES _FW_EGRESS_RULES
}
fw_egress_chain () {
#supress errors 2>/dev/null
fw_egress_remove_backup
fw_egress_save
sudo iptables -N FW_EGRESS_RULES
sudo iptables -A FW_OUTBOUND -j FW_EGRESS_RULES
}
fw_egress_backup_restore() {
sudo iptables -A FW_OUTBOUND -j FW_EGRESS_RULES
sudo iptables -E _FW_EGRESS_RULES FW_EGRESS_RULES
fw_egress_remove_backup
}
fw_entry_for_egress() {
local rule=$1
local prot=$(echo $rule | cut -d: -f2)
local sport=$(echo $rule | cut -d: -f3)
local eport=$(echo $rule | cut -d: -f4)
local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g')
if [ "$sport" == "0" -a "$eport" == "0" ]
then
DPORT=""
else
DPORT="--dport $sport:$eport"
fi
logger -t cloud "$(basename $0): enter apply fw egress rules for guest $prot:$sport:$eport:$cidrs"
for lcidr in $cidrs
do
[ "$prot" == "reverted" ] && continue;
if [ "$prot" == "icmp" ]
then
typecode="$sport/$eport"
[ "$eport" == "-1" ] && typecode="$sport"
[ "$sport" == "-1" ] && typecode="any"
sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr --icmp-type $typecode \
-j $target
result=$?
elif [ "$prot" == "all" ]
then
sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr -j $target
result=$?
else
sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr $DPORT -j $target
result=$?
fi
[ $result -gt 0 ] &&
logger -t cloud "Error adding iptables entry for guest network $prot:$sport:$eport:$cidrs" &&
break
done
logger -t cloud "$(basename $0): exit apply egress firewall rules for guest network"
return $result
}
aflag=0
rules=""
rules_list=""
ip=""
dev=""
pflag=0
shift
shift
while getopts 'a:P:' OPTION
do
case $OPTION in
a) aflag=1
rules="$OPTARG"
;;
P) pflag=1
pvalue="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
if [ "$aflag" != "1" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ -n "$rules" ]
then
rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ")
fi
# rule format
# protocal:sport:eport:cidr
#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32
# if any entry is reverted , entry will be in the format reverted:0:0:0
# example : tcp:80:80:0.0.0.0/0:, tcp:220:220:0.0.0.0/0:,200.1.1.2:reverted:0:0:0
success=0
if [ "$pvalue" == "1" -o "$pvalue" == "2" ]
then
target="DROP"
else
target="ACCEPT"
fi
fw_egress_chain
for r in $rules_list
do
fw_entry_for_egress $r
success=$?
if [ $success -gt 0 ]
then
logger -t cloud "failure to apply fw egress rules "
break
else
logger -t cloud "successful in applying fw egress rules"
fi
done
if [ $success -gt 0 ]
then
logger -t cloud "restoring from backup for guest network"
fw_egress_backup_restore
else
logger -t cloud "deleting backup for guest network"
if [ "$pvalue" == "1" ]
then
#Adding default policy rule
sudo iptables -A FW_EGRESS_RULES -j ACCEPT
fi
fi
fw_egress_remove_backup
unlock_exit $success $lock $locked

View File

@ -1,202 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# firewall_rule.sh -- allow some ports / protocols to vm instances
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: -a <public ip address:protocol:startport:endport:sourcecidrs> \n" $(basename $0) >&2
printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n"
}
#set -x
#FIXME: eating up the error code during execution of iptables
fw_remove_backup() {
local pubIp=$1
sudo iptables -t mangle -F _FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -D PREROUTING -d $pubIp -j _FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -X _FIREWALL_$pubIp 2> /dev/null
}
fw_restore() {
local pubIp=$1
sudo iptables -t mangle -F FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -D PREROUTING -d $pubIp -j FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -X FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -E _FIREWALL_$pubIp FIREWALL_$pubIp 2> /dev/null
}
fw_chain_for_ip () {
local pubIp=$1
fw_remove_backup $1
sudo iptables -t mangle -E FIREWALL_$pubIp _FIREWALL_$pubIp 2> /dev/null
sudo iptables -t mangle -N FIREWALL_$pubIp 2> /dev/null
# drop if no rules match (this will be the last rule in the chain)
sudo iptables -t mangle -A FIREWALL_$pubIp -j DROP> /dev/null
# ensure outgoing connections are maintained (first rule in chain)
sudo iptables -t mangle -I FIREWALL_$pubIp -m state --state RELATED,ESTABLISHED -j ACCEPT> /dev/null
#ensure that this table is after VPN chain
sudo iptables -t mangle -I PREROUTING 2 -d $pubIp -j FIREWALL_$pubIp
success=$?
if [ $success -gt 0 ]
then
# if VPN chain is not present for various reasons, try to add in to the first slot */
sudo iptables -t mangle -I PREROUTING -d $pubIp -j FIREWALL_$pubIp
fi
}
fw_entry_for_public_ip() {
local rules=$1
local pubIp=$(echo $rules | cut -d: -f1)
local prot=$(echo $rules | cut -d: -f2)
local sport=$(echo $rules | cut -d: -f3)
local eport=$(echo $rules | cut -d: -f4)
local scidrs=$(echo $rules | cut -d: -f5 | sed 's/-/ /g')
logger -t cloud "$(basename $0): enter apply firewall rules for public ip $pubIp:$prot:$sport:$eport:$scidrs"
# note that rules are inserted after the RELATED,ESTABLISHED rule
# but before the DROP rule
for src in $scidrs
do
[ "$prot" == "reverted" ] && continue;
if [ "$prot" == "icmp" ]
then
typecode="$sport/$eport"
[ "$eport" == "-1" ] && typecode="$sport"
[ "$sport" == "-1" ] && typecode="any"
sudo iptables -t mangle -I FIREWALL_$pubIp 2 -s $src -p $prot \
--icmp-type $typecode -j RETURN
else
sudo iptables -t mangle -I FIREWALL_$pubIp 2 -s $src -p $prot \
--dport $sport:$eport -j RETURN
fi
result=$?
[ $result -gt 0 ] &&
logger -t cloud "Error adding iptables entry for $pubIp:$prot:$sport:$eport:$src" &&
break
done
logger -t cloud "$(basename $0): exit apply firewall rules for public ip $pubIp"
return $result
}
get_vif_list() {
local vif_list=""
for i in /sys/class/net/eth*; do
vif=$(basename $i);
if [ "$vif" != "eth0" ] && [ "$vif" != "eth1" ]
then
vif_list="$vif_list $vif";
fi
done
if [ "$vif_list" == "" ]
then
vif_list="eth0"
fi
logger -t cloud "FirewallRule public interfaces = $vif_list"
echo $vif_list
}
shift
rules=
while getopts 'a:' OPTION
do
case $OPTION in
a) aflag=1
rules="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
VIF_LIST=$(get_vif_list)
if [ "$rules" == "" ]
then
rules="none"
fi
#-a 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32
# if any entry is reverted , entry will be in the format <ip>:reverted:0:0:0
# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:,200.1.1.2:reverted:0:0:0
# The reverted entries will fix the following partially
#FIXME: rule leak: when there are multiple ip address, there will chance that entry will be left over if the ipadress does not appear in the current execution when compare to old one
# example : In the below first transaction have 2 ip's whereas in second transaction it having one ip, so after the second trasaction 200.1.2.3 ip will have rules in mangle table.
# 1) -a 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:,
# 2) -a 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:,
success=0
publicIps=
rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ")
for r in $rules_list
do
pubIp=$(echo $r | cut -d: -f1)
publicIps="$pubIp $publicIps"
done
unique_ips=$(echo $publicIps| tr " " "\n" | sort | uniq | tr "\n" " ")
for u in $unique_ips
do
fw_chain_for_ip $u
done
for r in $rules_list
do
pubIp=$(echo $r | cut -d: -f1)
fw_entry_for_public_ip $r
success=$?
if [ $success -gt 0 ]
then
logger -t cloud "$(basename $0): failure to apply fw rules for ip $pubIp"
break
else
logger -t cloud "$(basename $0): successful in applying fw rules for ip $pubIp"
fi
done
if [ $success -gt 0 ]
then
for p in $unique_ips
do
logger -t cloud "$(basename $0): restoring from backup for ip: $p"
fw_restore $p
done
fi
for p in $unique_ips
do
logger -t cloud "$(basename $0): deleting backup for ip: $p"
fw_remove_backup $p
done
unlock_exit $success $lock $locked

View File

@ -1,358 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# $Id: firewall.sh 9947 2010-06-25 19:34:24Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/patches/xenserver/root/firewall.sh $
# firewall.sh -- allow some ports / protocols to vm instances
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
vpnoutmark="0x525"
usage() {
printf "Usage: %s: (-A|-D) -r <target-instance-ip> -P protocol (-p port_range | -t icmp_type_code) -l <public ip address> -d <target port> -s <source cidrs> [-G] \n" $(basename $0) >&2
}
#set -x
get_dev_list() {
ip link show | grep -e eth[2-9] | awk -F ":" '{print $2}'
ip link show | grep -e eth1[0-9] | awk -F ":" '{print $2}'
}
ip_to_dev() {
local ip=$1
for dev in $DEV_LIST; do
ip addr show dev $dev | grep inet | grep $ip &>> /dev/null
[ $? -eq 0 ] && echo $dev && return 0
done
return 1
}
doHairpinNat () {
local vrGuestIPNetwork=$(sudo ip addr show dev eth0 | grep inet | grep eth0 | awk '{print $2}' | head -1)
local vrGuestIP=$(echo $vrGuestIPNetwork | awk -F'/' '{print $1}')
local publicIp=$1
local prot=$2
local port=$3
local guestVmIp=$4
local guestPort=$(echo $5 | sed 's/:/-/')
local op=$6
local destPort=$5
logger -t cloud "$(basename $0): create HairPin entry : public ip=$publicIp \
instance ip=$guestVmIp proto=$proto portRange=$guestPort op=$op"
if [ "$prot" == "all" ]
then
logger -t cloud "creating hairpin nat rules for static nat"
(sudo iptables -t nat $op PREROUTING -d $publicIp -i eth0 -j DNAT --to-destination $guestVmIp &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t nat $op POSTROUTING -s $vrGuestIPNetwork -d $guestVmIp -j SNAT -o eth0 --to-source $vrGuestIP &>> $OUTFILE || [ "$op" == "-D" ])
else
(sudo iptables -t nat $op PREROUTING -d $publicIp -i eth0 -p $prot --dport $port -j DNAT --to-destination $guestVmIp:$guestPort &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t nat $op POSTROUTING -s $vrGuestIPNetwork -p $prot --dport $destPort -d $guestVmIp -j SNAT -o eth0 --to-source $vrGuestIP &>> $OUTFILE || [ "$op" == "-D" ])
fi
}
#Port (address translation) forwarding for tcp or udp
tcp_or_udp_entry() {
local instIp=$1
local dport0=$2
local dport=$(echo $2 | sed 's/:/-/')
local publicIp=$3
local port=$4
local op=$5
local proto=$6
local cidrs=$7
logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \
instance ip=$instIp proto=$proto port=$port dport=$dport op=$op"
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && tcp_or_udp_entry $instIp $dport0 $publicIp $port "-D" $proto $cidrs
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
local dev=$(ip_to_dev $publicIp)
local tableNo=$(echo $dev | awk -F'eth' '{print $2}')
# shortcircuit the process if error and it is an append operation
# continue if it is delete
(sudo iptables -t nat $op PREROUTING --proto $proto -i $dev -d $publicIp \
--destination-port $port -j DNAT \
--to-destination $instIp:$dport &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t mangle $op PREROUTING --proto $proto -i $dev -d $publicIp \
--destination-port $port -j MARK --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t mangle $op PREROUTING --proto $proto -i $dev -d $publicIp \
--destination-port $port -m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) &&
(doHairpinNat $publicIp $proto $port $instIp $dport0 $op) &&
(sudo iptables -t nat $op OUTPUT --proto $proto -d $publicIp \
--destination-port $port -j DNAT \
--to-destination $instIp:$dport &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables $op FORWARD -p $proto -s $cidrs -d $instIp -m state \
--state ESTABLISHED,RELATED -m comment --comment "$publicIp:$port" -j ACCEPT &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables $op FORWARD -p $proto -s $cidrs -d $instIp \
--destination-port $dport0 -m state --state NEW -m comment --comment "$publicIp:$port" -j ACCEPT &>> $OUTFILE)
local result=$?
logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result"
return $result
}
#Forward icmp
icmp_entry() {
local instIp=$1
local icmptype=$2
local publicIp=$3
local op=$4
logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \
instance ip=$instIp proto=icmp port=$port dport=$dport op=$op"
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && icmp_entry $instIp $icmpType $publicIp "-D"
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
local dev=$(ip_to_dev $publicIp)
sudo iptables -t nat $op PREROUTING --proto icmp -i $dev -d $publicIp --icmp-type $icmptype -j DNAT --to-destination $instIp &>> $OUTFILE
sudo iptables -t nat $op OUTPUT --proto icmp -d $publicIp --icmp-type $icmptype -j DNAT --to-destination $instIp &>> $OUTFILE
sudo iptables $op FORWARD -p icmp -s 0/0 -d $instIp --icmp-type $icmptype -j ACCEPT &>> $OUTFILE
result=$?
logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result"
return $result
}
one_to_one_fw_entry() {
local publicIp=$1
local instIp=$2
local proto=$3
local portRange=$4
local op=$5
logger -t cloud "$(basename $0): create firewall entry for static nat: public ip=$publicIp \
instance ip=$instIp proto=$proto portRange=$portRange op=$op"
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && one_to_one_fw_entry $publicIp $instIp $proto $portRange "-D"
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
local dev=$(ip_to_dev $publicIp)
[ $? -ne 0 ] && echo "Could not find device associated with $publicIp" && return 1
# shortcircuit the process if error and it is an append operation
# continue if it is delete
(sudo iptables -t nat $op PREROUTING -i $dev -d $publicIp --proto $proto \
--destination-port $portRange -j DNAT \
--to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) &&
(doHairpinNat $publicIp $proto $portRange $instIp $portRange $op) &&
(sudo iptables $op FORWARD -i $dev -o eth0 -d $instIp --proto $proto \
--destination-port $portRange -m state \
--state NEW -j ACCEPT &>> $OUTFILE )
result=$?
logger -t cloud "$(basename $0): done firewall entry public ip=$publicIp op=$op result=$result"
return $result
}
fw_chain_for_ip() {
local pubIp=$1
if iptables -t mangle -N FIREWALL_$pubIp &> /dev/null
then
logger -t cloud "$(basename $0): created a firewall chain for $pubIp"
(sudo iptables -t mangle -A FIREWALL_$pubIp -j DROP) &&
(sudo iptables -t mangle -I FIREWALL_$pubIp -m state --state RELATED,ESTABLISHED -j ACCEPT ) &&
(sudo iptables -t mangle -I PREROUTING 2 -d $pubIp -j FIREWALL_$pubIp)
return $?
fi
logger -t cloud "fw chain for $pubIp already exists"
return 0
}
static_nat() {
local publicIp=$1
local instIp=$2
local op=$3
local op2="-D"
local rulenum=
local proto="all"
logger -t cloud "$(basename $0): static nat: public ip=$publicIp \
instance ip=$instIp op=$op"
#TODO check error below
fw_chain_for_ip $publicIp
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && static_nat $publicIp $instIp "-D"
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
[ "$op" == "-A" ] && op2="-I"
if [ "$op" == "-A" ]
then
# put static nat rule one rule after VPN no-NAT rule
# rule chain can be used to improve it later
iptables-save -t nat|grep "POSTROUTING" | grep $vpnoutmark > /dev/null
if [ $? -eq 0 ]
then
rulenum=2
else
rulenum=1
fi
fi
local dev=$(ip_to_dev $publicIp)
[ $? -ne 0 ] && echo "Could not find device associated with $publicIp" && return 1
local tableNo=$(echo $dev | awk -F'eth' '{print $2}')
# shortcircuit the process if error and it is an append operation
# continue if it is delete
(sudo iptables -t mangle $op PREROUTING -i $dev -d $publicIp \
-j MARK -m state --state NEW --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t mangle $op PREROUTING -i $dev -d $publicIp \
-m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t mangle $op PREROUTING -s $instIp -i eth0 \
-j MARK -m state --state NEW --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t mangle $op PREROUTING -s $instIp -i eth0 \
-m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t nat $op PREROUTING -i $dev -d $publicIp -j DNAT \
--to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables $op FORWARD -i $dev -o eth0 -d $instIp -m state \
--state NEW -j ACCEPT &>> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t nat $op2 POSTROUTING $rulenum -s $instIp -j SNAT \
-o $dev --to-source $publicIp &>> $OUTFILE || [ "$op" == "-D" ]) &&
(doHairpinNat $publicIp $proto "all" $instIp "0:65535" $op)
result=$?
logger -t cloud "$(basename $0): done static nat entry public ip=$publicIp op=$op result=$result"
return $result
}
rflag=
Pflag=
pflag=
tflag=
lflag=
dflag=
sflag=
Gflag=
op=""
while getopts 'ADr:P:p:t:l:d:s:G' OPTION
do
case $OPTION in
A) op="-A"
;;
D) op="-D"
;;
r) rflag=1
instanceIp="$OPTARG"
;;
P) Pflag=1
protocol="$OPTARG"
;;
p) pflag=1
ports="$OPTARG"
;;
t) tflag=1
icmptype="$OPTARG"
;;
l) lflag=1
publicIp="$OPTARG"
;;
s) sflag=1
cidrs="$OPTARG"
;;
d) dflag=1
dport="$OPTARG"
;;
G) Gflag=1
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
DEV_LIST=$(get_dev_list)
OUTFILE=$(mktemp)
#Firewall ports for one-to-one/static NAT
if [ "$Gflag" == "1" ]
then
if [ "$protocol" == "" ]
then
static_nat $publicIp $instanceIp $op
else
one_to_one_fw_entry $publicIp $instanceIp $protocol $dport $op
fi
result=$?
if [ "$result" -ne 0 ] && [ "$op" != "-D" ]; then
cat $OUTFILE >&2
fi
rm -f $OUTFILE
if [ "$op" == "-D" ];then
result=0
fi
unlock_exit $result $lock $locked
fi
if [ "$sflag" != "1" ]
then
cidrs="0/0"
fi
case $protocol in
tcp|udp)
tcp_or_udp_entry $instanceIp $dport $publicIp $ports $op $protocol $cidrs
result=$?
if [ "$result" -ne 0 ] && [ "$op" != "-D" ];then
cat $OUTFILE >&2
fi
rm -f $OUTFILE
if [ "$op" == "-D" ];then
result=0
fi
unlock_exit $result $lock $locked
;;
"icmp")
icmp_entry $instanceIp $icmptype $publicIp $op
if [ "$op" == "-D" ];then
result=0
fi
unlock_exit $? $lock $locked
;;
*)
printf "Invalid protocol-- must be tcp, udp or icmp\n" >&2
unlock_exit 5 $lock $locked
;;
esac
unlock_exit 0 $lock $locked

View File

@ -1,55 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# getRouterAlerts.sh --- Send the alerts from routerServiceMonitor.log to Management Server
#set -x
filename=/var/log/routerServiceMonitor.log #Monitor service log file
if [ -n "$1" -a -n "$2" ]
then
reqDateVal=$(date -d "$1 $2" "+%s");
else
reqDateVal=0
fi
if [ -f $filename ]
then
while read line
do
if [ -n "$line" ]
then
dateval=`echo $line |awk '{print $1, $2}'`
IFS=',' read -a array <<< "$dateval"
dateval=${array[0]}
toDateVal=$(date -d "$dateval" "+%s")
if [ "$toDateVal" -gt "$reqDateVal" ]
then
alerts="$line\n$alerts"
else
break
fi
fi
done < <(tac $filename)
fi
if [ -n "$alerts" ]; then
echo $alerts
else
echo "No Alerts"
fi

View File

@ -1,250 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# firewall_rule.sh -- allow some ports / protocols to vm instances
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: -a <public ip address:protocol:startport:endport:sourcecidrs> \n" $(basename $0) >&2
printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n"
}
#set -x
#FIXME: eating up the error code during execution of iptables
acl_switch_to_new() {
sudo iptables -D FORWARD -o $dev -d $gcidr -j _ACL_INBOUND_$dev 2>/dev/null
sudo iptables-save | grep "\-j _ACL_INBOUND_$dev" | grep "\-A" | while read rule;
do
rule1=$(echo $rule | sed 's/\_ACL_INBOUND/ACL_INBOUND/')
sudo iptables $rule1
rule2=$(echo $rule | sed 's/\-A/\-D/')
sudo iptables $rule2
done
sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_remove_backup() {
sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -D FORWARD -o $dev -d $gcidr -j _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_remove() {
sudo iptables -F ACL_INBOUND_$dev 2>/dev/null
sudo iptables -D FORWARD -o $dev -d $gcidr -j ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null
}
acl_restore() {
acl_remove
sudo iptables -E _ACL_INBOUND_$dev ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -E _ACL_OUTBOUND_$dev ACL_OUTBOUND_$dev 2>/dev/null
}
acl_save() {
acl_remove_backup
sudo iptables -E ACL_INBOUND_$dev _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -E ACL_OUTBOUND_$dev _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_chain_for_guest_network () {
acl_save
# inbound
sudo iptables -N ACL_INBOUND_$dev 2>/dev/null
# drop if no rules match (this will be the last rule in the chain)
sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null
sudo iptables -A FORWARD -o $dev -d $gcidr -j ACL_INBOUND_$dev 2>/dev/null
# outbound
sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null
}
acl_entry_for_guest_network() {
local rule=$1
local ttype=$(echo $rule | cut -d: -f1)
local prot=$(echo $rule | cut -d: -f2)
local sport=$(echo $rule | cut -d: -f3)
local eport=$(echo $rule | cut -d: -f4)
local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g')
local action=$(echo $rule | cut -d: -f6)
if [ "$sport" == "0" -a "$eport" == "0" ]
then
DPORT=""
else
DPORT="--dport $sport:$eport"
fi
logger -t cloud "$(basename $0): enter apply acl rules for guest network: $gcidr, inbound:$inbound:$prot:$sport:$eport:$cidrs"
# note that rules are inserted after the RELATED,ESTABLISHED rule
# but before the DROP rule
for lcidr in $cidrs
do
[ "$prot" == "reverted" ] && continue;
if [ "$prot" == "icmp" ]
then
typecode="$sport/$eport"
[ "$eport" == "-1" ] && typecode="$sport"
[ "$sport" == "-1" ] && typecode="any"
if [ "$ttype" == "Ingress" ]
then
sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \
--icmp-type $typecode -j $action
else
let egress++
sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \
--icmp-type $typecode -j $action
fi
else
if [ "$ttype" == "Ingress" ]
then
sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \
$DPORT -j $action
else
let egress++
sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \
$DPORT -j $action
fi
fi
result=$?
[ $result -gt 0 ] &&
logger -t cloud "Error adding iptables entry for guest network : $gcidr,inbound:$inbound:$prot:$sport:$eport:$cidrs" &&
break
done
logger -t cloud "$(basename $0): exit apply acl rules for guest network : $gcidr"
return $result
}
dflag=0
gflag=0
aflag=0
Mflag=0
rules=""
rules_list=""
ip=""
dev=""
mac=""
while getopts 'd:i:m:M:a:' OPTION
do
case $OPTION in
d) dflag=1
dev="$OPTARG"
;;
i) iflag=1
ip="$OPTARG"
;;
m) mflag=1
mask="$OPTARG"
;;
M) Mflag=1
mac="$OPTARG"
;;
a) aflag=1
rules="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
if [ "$dflag$iflag$mflag$aflag" != "1111" ]
then
usage
unlock_exit 2 $lock $locked
fi
# override dev with mac address match, if provided
if [[ ! -z "$mac" ]]; then
logger -t cloud "$(basename $0): mac $mac passed, trying to match to device"
for i in `ls /sys/class/net`; do
if grep -q $mac /sys/class/net/$i/address; then
dev=$i
logger -t cloud "$(basename $0): matched dev $i to mac $mac, dev is now $dev"
break
fi
done
fi
gcidr="$ip/$mask"
if [ -n "$rules" ]
then
rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ")
fi
# rule format
# protocal:sport:eport:cidr
#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32
# if any entry is reverted , entry will be in the format <ip>:reverted:0:0:0
# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:ACCEPT:,172.16.92.44:tcp:220:220:0.0.0.0/0:DROP,200.1.1.2:reverted:0:0:0
success=0
acl_chain_for_guest_network
egress=0
for r in $rules_list
do
acl_entry_for_guest_network $r
success=$?
if [ $success -gt 0 ]
then
logger -t cloud "$(basename $0): failure to apply fw rules for guest network: $gcidr"
break
else
logger -t cloud "$(basename $0): successful in applying fw rules for guest network: $gcidr"
fi
done
if [ $success -gt 0 ]
then
logger -t cloud "$(basename $0): restoring from backup for guest network: $gcidr"
acl_restore
else
logger -t cloud "$(basename $0): deleting backup for guest network: $gcidr"
if [ $egress -eq 0 ]
then
sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null
else
sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j DROP 2>/dev/null
fi
acl_switch_to_new
fi
unlock_exit $success $lock $locked

View File

@ -1,316 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# guestnw.sh -- create/destroy guest network
# @VERSION@
source /root/func.sh
source /opt/cloud/bin/vpc_func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage:\n %s -A -M <mac> -d <dev> -i <ip address> -g <gateway> -m <network mask> -s <dns ip> -e < domain> [-f] \n" $(basename $0) >&2
printf " %s -D -d <dev> -i <ip address> \n" $(basename $0) >&2
}
destroy_acl_chain() {
sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $subnet/$mask ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -F ACL_INBOUND_$dev 2>/dev/null
sudo iptables -D FORWARD -o $dev -d $subnet/$mask -j ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X ACL_INBOUND_$dev 2>/dev/null
}
create_acl_chain() {
destroy_acl_chain
sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null
sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -s $subnet/$mask ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -N ACL_INBOUND_$dev 2>/dev/null
# drop if no rules match (this will be the last rule in the chain)
sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null
sudo iptables -A FORWARD -o $dev -d $subnet/$mask -j ACL_INBOUND_$dev 2>/dev/null
}
setup_apache2() {
logger -t cloud "Setting up apache web server for $dev"
cp /etc/apache2/vhostexample.conf /etc/apache2/conf.d/vhost$dev.conf
sed -i -e "s/<VirtualHost.*:80>/<VirtualHost $ip:80>/" /etc/apache2/conf.d/vhost$dev.conf
sed -i -e "s/<VirtualHost.*:443>/<VirtualHost $ip:443>/" /etc/apache2/conf.d/vhost$dev.conf
sed -i -e "s/\tServerName.*/\tServerName vhost$dev.cloudinternal.com/" /etc/apache2/conf.d/vhost$dev.conf
sed -i -e "s/Listen .*:80/Listen $ip:80/g" /etc/apache2/conf.d/vhost$dev.conf
sed -i -e "s/Listen .*:443/Listen $ip:443/g" /etc/apache2/conf.d/vhost$dev.conf
service apache2 restart
sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT
sudo iptables -A INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT
}
desetup_apache2() {
logger -t cloud "Desetting up apache web server for $dev"
rm -f /etc/apache2/conf.d/vhost$dev.conf
service apache2 restart
sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT
}
setup_dnsmasq() {
logger -t cloud "Setting up dnsmasq for network $ip/$mask "
# setup rules to allow dhcp/dns request
sudo iptables -D INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT
sudo iptables -D INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT
sudo iptables -D INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT
sudo iptables -A INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT
sudo iptables -A INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT
sudo iptables -A INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT
# setup static
sed -i -e "/^[#]*dhcp-range=interface:$dev/d" /etc/dnsmasq.d/cloud.conf
echo "dhcp-range=interface:$dev,set:interface-$dev,$ip,static" >> /etc/dnsmasq.d/cloud.conf
# setup DOMAIN
[ -z $DOMAIN ] && DOMAIN="cloudnine.internal"
sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,15.*$/d" /etc/dnsmasq.d/cloud.conf
echo "dhcp-option=tag:interface-$dev,15,$DOMAIN" >> /etc/dnsmasq.d/cloud.conf
service dnsmasq restart
sleep 1
}
desetup_dnsmasq() {
logger -t cloud "Desetting up dnsmasq for network $ip/$mask "
# remove rules to allow dhcp/dns request
sudo iptables -D INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT
sudo iptables -D INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT
sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,option:router.*$/d" /etc/dnsmasq.d/cloud.conf
sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,6.*$/d" /etc/dnsmasq.d/cloud.conf
sed -i -e "/^[#]*dhcp-range=interface:$dev/d" /etc/dnsmasq.d/cloud.conf
service dnsmasq restart
sleep 1
}
setup_passwdsvcs() {
logger -t cloud "Setting up password service for network $ip/$mask, eth $dev "
sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT
sudo iptables -A INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT
nohup bash /opt/cloud/bin/vpc_passwd_server $ip >/dev/null 2>&1 &
}
desetup_passwdsvcs() {
logger -t cloud "Desetting up password service for network $ip/$mask, eth $dev "
sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT
pid=`ps -ef | grep passwd_server_ip.py | grep $ip | grep -v grep | awk '{print $2}'`
if [ -n "$pid" ]
then
kill -9 $pid
fi
}
create_guest_network() {
# need to wait for eth device to appear before configuring it
timer=0
# match dev based on mac, if passed
if [[ ! -z "$mac" ]]; then
logger -t cloud "$(basename $0): mac $mac passed, trying to match to device"
while [ ! $timer -gt 15 ]; do
for i in `ls /sys/class/net`; do
if grep -q $mac /sys/class/net/$i/address; then
dev=$i
logger -t cloud "$(basename $0): matched dev $i to mac $mac, dev is now $dev"
timer=15
break
fi
done
sleep 1;
timer=$[timer + 1]
done
else
while ! `grep -q $dev /proc/net/dev` ; do
logger -t cloud "$(basename $0):Waiting for interface $dev to appear, $timer seconds"
sleep 1;
if [ $timer -gt 15 ]; then
logger -t cloud "$(basename $0):interface $dev never appeared"
break
fi
timer=$[timer + 1]
done
fi
logger -t cloud " $(basename $0): Create network on interface $dev, gateway $gw, network $ip/$mask "
# setup ip configuration
sudo ip addr add dev $dev $ip/$mask brd +
sudo ip link set $dev up
sudo arping -c 3 -I $dev -A -U -s $ip $ip
echo 1 > /proc/sys/net/ipv4/conf/$dev/rp_filter
# restore mark from connection mark
local tableName="Table_$dev"
sudo ip route add $subnet/$mask dev $dev table $tableName proto static
sudo iptables -t mangle -D PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark
sudo iptables -t nat -D POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip
sudo iptables -t mangle -A PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark
# set up hairpin
sudo iptables -t nat -A POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip
create_acl_chain
setup_dnsmasq
setup_apache2
setup_passwdsvcs
#enable rps, rfs
enable_rpsrfs $dev
}
enable_rpsrfs() {
if [ -f /etc/rpsrfsenable ]
then
enable=$(cat /etc/rpsrfsenable)
if [ $enable -eq 0 ]
then
return 0
fi
else
return 0
fi
proc=$(cat /proc/cpuinfo | grep "processor" | wc -l)
if [ $proc -le 1 ]
then
return 0
fi
dev=$1
num=1
num=$(($num<<$proc))
num=$(($num-1));
echo $num;
hex=$(printf "%x\n" $num)
echo $hex;
#enable rps
echo $hex > /sys/class/net/$dev/queues/rx-0/rps_cpus
#enble rfs
rps_flow_entries=$(cat /proc/sys/net/core/rps_sock_flow_entries)
if [ $rps_flow_entries -eq 0 ]
then
echo 256 > /proc/sys/net/core/rps_sock_flow_entries
fi
echo 256 > /sys/class/net/$dev/queues/rx-0/rps_flow_cnt
}
destroy_guest_network() {
logger -t cloud " $(basename $0): Create network on interface $dev, gateway $gw, network $ip/$mask "
sudo ip addr del dev $dev $ip/$mask
sudo iptables -t mangle -D PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark
sudo iptables -t nat -D POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip
destroy_acl_chain
desetup_dnsmasq
desetup_apache2
desetup_passwdsvcs
}
#set -x
iflag=0
mflag=0
nflag=0
dflag=
gflag=
Cflag=
Dflag=
Mflag=
op=""
while getopts 'CDn:m:M:d:i:g:s:e:' OPTION
do
case $OPTION in
C) Cflag=1
op="-C"
;;
D) Dflag=1
op="-D"
;;
n) nflag=1
subnet="$OPTARG"
;;
m) mflag=1
mask="$OPTARG"
;;
M) Mflag=1
mac="$OPTARG"
;;
d) dflag=1
dev="$OPTARG"
;;
i) iflag=1
ip="$OPTARG"
;;
g) gflag=1
gw="$OPTARG"
;;
s) sflag=1
DNS="$OPTARG"
;;
e) eflag=1
DOMAIN="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
vpccidr=$(getVPCcidr)
if [ "$Cflag$Dflag$dflag" != "11" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$Cflag" == "1" ] && [ "$iflag$gflag$mflag" != "111" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$Cflag" == "1" ]
then
create_guest_network
fi
if [ "$Dflag" == "1" ]
then
destroy_guest_network
fi
unlock_exit 0 $lock $locked

View File

@ -1,223 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ipassoc.sh -- associate/disassociate a public ip with an instance
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage:\n %s -A -l <public-ip-address> -c <dev> [-f] \n" $(basename $0) >&2
printf " %s -D -l <public-ip-address> -c <dev> [-f] \n" $(basename $0) >&2
}
add_routing() {
logger -t cloud "$(basename $0):Add routing $pubIp on interface $ethDev"
local tableName="Table_$ethDev"
sudo ip route add $subnet/$mask dev $ethDev table $tableName proto static
sudo ip route add default via $defaultGwIP table $tableName proto static
sudo ip route flush cache
sudo ip route | grep default
if [ $? -gt 0 ]
then
sudo ip route add default via $defaultGwIP
fi
return 0
}
remove_routing() {
return 0
}
add_an_ip () {
# need to wait for eth device to appear before configuring it
timer=0
while ! `grep -q $ethDev /proc/net/dev` ; do
logger -t cloud "$(basename $0):Waiting for interface $ethDev to appear, $timer seconds"
sleep 1;
if [ $timer -gt 15 ]; then
logger -t cloud "$(basename $0):interface $ethDev never appeared"
break
fi
timer=$[timer + 1]
done
logger -t cloud "$(basename $0):Adding ip $pubIp on interface $ethDev"
sudo ip link show $ethDev | grep "state DOWN" > /dev/null
local old_state=$?
sudo ip addr add dev $ethDev $pubIp/$mask brd +
if [ $old_state -eq 0 ]
then
sudo ip link set $ethDev up
fi
sudo arping -c 1 -I $ethDev -A -U -s $pubIp $pubIp
sudo arping -c 1 -I $ethDev -A -U -s $pubIp $pubIp
local tableNo=${ethDev:3}
sudo iptables-save -t mangle | grep "PREROUTING -i $ethDev -m state --state NEW -j CONNMARK --set-xmark" 2>/dev/null
if [ $? -gt 0 ]
then
sudo iptables -t mangle -A PREROUTING -i $ethDev -m state --state NEW -j CONNMARK --set-mark $tableNo 2>/dev/null
fi
enable_rpsrfs $ethDev
add_routing
return $?
}
enable_rpsrfs() {
if [ -f /etc/rpsrfsenable ]
then
enable=$(cat /etc/rpsrfsenable)
if [ $enable -eq 0 ]
then
return 0
fi
else
return 0
fi
proc=$(cat /proc/cpuinfo | grep "processor" | wc -l)
if [ $proc -le 1 ]
then
return 0
fi
dev=$1
num=1
num=$(($num<<$proc))
num=$(($num-1));
echo $num;
hex=$(printf "%x\n" $num)
echo $hex;
#enable rps
echo $hex > /sys/class/net/$dev/queues/rx-0/rps_cpus
#enble rfs
rps_flow_entries=$(cat /proc/sys/net/core/rps_sock_flow_entries)
if [ $rps_flow_entries -eq 0 ]
then
echo 256 > /proc/sys/net/core/rps_sock_flow_entries
fi
if [ $(cat /sys/class/net/$dev/queues/rx-0/rps_flow_cnt) -eq 0 ]
then
echo 256 > /sys/class/net/$dev/queues/rx-0/rps_flow_cnt
fi
}
remove_an_ip () {
logger -t cloud "$(basename $0):Removing ip $pubIp on interface $ethDev"
local existingIpMask=$(sudo ip addr show dev $ethDev | grep -v "inet6" | grep "inet " | awk '{print $2}')
sudo ip addr del dev $ethDev $pubIp/$mask
# reapply IPs in this interface
for ipMask in $existingIpMask
do
if [ "$ipMask" == "$pubIp/$mask" ]
then
continue
fi
sudo ip addr add dev $ethDev $ipMask brd +
done
remove_routing
return 0
}
#set -x
lflag=0
cflag=0
gflag=0
mflag=0
nflag=0
op=""
while getopts 'ADl:c:g:m:n:' OPTION
do
case $OPTION in
A) Aflag=1
op="-A"
;;
D) Dflag=1
op="-D"
;;
l) lflag=1
pubIp="$OPTARG"
;;
c) cflag=1
ethDev="$OPTARG"
;;
g) gflag=1
defaultGwIP="$OPTARG"
;;
m) mflag=1
mask="$OPTARG"
;;
n) nflag=1
subnet="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
if [ "$Aflag$Dflag" != "1" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$lflag$cflag$gflag$mflag$nflag" != "11111" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$Aflag" == "1" ]
then
add_an_ip
unlock_exit $? $lock $locked
fi
if [ "$Dflag" == "1" ]
then
remove_an_ip
unlock_exit $? $lock $locked
fi
unlock_exit 1 $lock $locked

View File

@ -1,229 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# @VERSION@
do_ilb_if_ilb () {
local typ=""
local pattern="type=(.*)"
for keyval in $(cat /var/cache/cloud/cmdline)
do
if [[ $keyval =~ $pattern ]]; then
typ=${BASH_REMATCH[1]};
fi
done
if [ "$typ" == "ilbvm" ]
then
logger -t cloud "$(basename $0): Detected that we are running in an internal load balancer vm"
$(dirname $0)/ilb.sh "$@"
exit $?
fi
}
logger -t cloud "$(basename $0): Entering $(dirname $0)/$(basename $0)"
do_ilb_if_ilb "$@"
source /root/func.sh
source /opt/cloud/bin/vpc_func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: -i <domR eth1 ip> -a <added public ip address ip:port> -d <removed ip:port> -f <load balancer config> -s <stats ip ip:port:cidr> \n" $(basename $0) >&2
}
# set -x
fw_remove_backup() {
sudo iptables -F back_load_balancer 2> /dev/null
sudo iptables -D INPUT -p tcp -j back_load_balancer 2> /dev/null
sudo iptables -X back_load_balancer 2> /dev/null
sudo iptables -F back_lb_stats 2> /dev/null
sudo iptables -D INPUT -p tcp -j back_lb_stats 2> /dev/null
sudo iptables -X back_lb_stats 2> /dev/null
}
fw_remove() {
sudo iptables -F load_balancer 2> /dev/null
sudo iptables -D INPUT -p tcp -j load_balancer 2> /dev/null
sudo iptables -X load_balancer 2> /dev/null
sudo iptables -F lb_stats 2> /dev/null
sudo iptables -D INPUT -p tcp -j lb_stats 2> /dev/null
sudo iptables -X lb_stats 2> /dev/null
}
fw_backup() {
fw_remove_backup
sudo iptables -E load_balancer back_load_balancer 2> /dev/null
sudo iptables -E lb_stats back_lb_stats 2> /dev/null
}
fw_restore() {
fw_remove
sudo iptables -E back_load_balancer load_balancer 2> /dev/null
sudo iptables -E back_lb_stats lb_stats 2> /dev/null
}
fw_chain_create () {
fw_backup
sudo iptables -N load_balancer 2> /dev/null
sudo iptables -A INPUT -p tcp -j load_balancer 2> /dev/null
sudo iptables -N lb_stats 2> /dev/null
sudo iptables -A INPUT -p tcp -j lb_stats 2> /dev/null
}
# firewall entry to ensure that haproxy can receive on specified port
fw_entry() {
local added=$1
local removed=$2
local stats=$3
if [ "$added" == "none" ]
then
added=""
fi
if [ "$removed" == "none" ]
then
removed=""
fi
local a=$(echo $added | cut -d, -f1- --output-delimiter=" ")
local r=$(echo $removed | cut -d, -f1- --output-delimiter=" ")
fw_chain_create
success=0
while [ 1 ]
do
for i in $a
do
local pubIp=$(echo $i | cut -d: -f1)
local dport=$(echo $i | cut -d: -f2)
sudo iptables -A load_balancer -p tcp -d $pubIp --dport $dport -j ACL_INBOUND_$dev 2>/dev/null
success=$?
if [ $success -gt 0 ]
then
break
fi
done
if [ "$stats" != "none" ]
then
local pubIp=$(echo $stats | cut -d: -f1)
local dport=$(echo $stats | cut -d: -f2)
local cidrs=$(echo $stats | cut -d: -f3 | sed 's/-/,/')
sudo iptables -A lb_stats -s $cidrs -p tcp -d $pubIp --dport $dport -j ACCEPT 2>/dev/null
success=$?
fi
break
done
if [ $success -gt 0 ]
then
fw_restore
else
fw_remove_backup
fi
return $success
}
#Hot reconfigure HA Proxy in the routing domain
reconfig_lb() {
logger -t cloud "Reconfiguring loadbalancer using $1"
/root/reconfigLB.sh $1
return $?
}
# Restore the HA Proxy to its previous state, and revert iptables rules on DomR
restore_lb() {
logger -t cloud "Restoring HA Proxy to previous state"
# Copy the old version of haproxy.cfg into the file that reconfigLB.sh uses
cp /etc/haproxy/haproxy.cfg.old /etc/haproxy/haproxy.cfg.new
if [ $? -eq 0 ]
then
# Run reconfigLB.sh again
/root/reconfigLB.sh /etc/haproxy/haproxy.cfg.new
fi
}
iflag=
aflag=
dflag=
fflag=
sflag=
while getopts 'i:a:d:f:s:' OPTION
do
case $OPTION in
i) iflag=1
ip="$OPTARG"
;;
a) aflag=1
addedIps="$OPTARG"
;;
d) dflag=1
removedIps="$OPTARG"
;;
s) sflag=1
statsIp="$OPTARG"
;;
f) fflag=1
cfgfile="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
dev=$(getEthByIp $ip)
if [ "$addedIps" == "" ]
then
addedIps="none"
fi
if [ "$removedIps" == "" ]
then
removedIps="none"
fi
# hot reconfigure haproxy
reconfig_lb $cfgfile
if [ $? -gt 0 ]
then
logger -t cloud "Reconfiguring loadbalancer failed"
unlock_exit 1 $lock $locked
fi
# iptables entry to ensure that haproxy receives traffic
fw_entry $addedIps $removedIps $statsIp
result=$?
if [ $result -gt 0 ]
then
logger -t cloud "Failed to apply firewall rules for load balancing, reverting HA Proxy config"
# Restore the LB
restore_lb
fi
unlock_exit $result $lock $locked

View File

@ -1,126 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: (-A|-D) -r <target-instance-ip> -P protocol (-p port_range | -t icmp_type_code) -l <public ip address> -d <target port> -s <source cidrs> [-G] \n" $(basename $0) >&2
}
#set -x
#Port (address translation) forwarding for tcp or udp
tcp_or_udp_nat() {
local op=$1
local proto=$2
local publicIp=$3
local ports=$4
local instIp=$5
local dports=$6
logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \
instance ip=$instIp proto=$proto port=$port dport=$dport op=$op"
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && tcp_or_udp_nat "-D" $proto $publicIp $ports $instIp $dports
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
# shortcircuit the process if error and it is an append operation
# continue if it is delete
local PROTO=""
if [ "$proto" != "any" ]
then
PROTO="--proto $proto"
fi
local DEST_PORT=""
if [ "$ports" != "any" ]
then
DEST_PORT="--destination-port $ports"
fi
local TO_DEST="--to-destination $instIp"
if [ "$dports" != "any" ]
then
TO_DEST="--to-destination $instIp:$dports"
fi
sudo iptables -t nat $op PREROUTING $PROTO -d $publicIp $DEST_PORT -j DNAT \
$TO_DEST &>> $OUTFILE
local result=$?
logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result"
# the rule may not exist
if [ "$op" == "-D" ]
then
return 0
fi
return $result
}
rflag=
Pflag=
pflag=
lflag=
dflag=
op=""
protocal="any"
ports="any"
dports="any"
while getopts 'ADr:P:p:l:d:' OPTION
do
case $OPTION in
A) op="-A"
;;
D) op="-D"
;;
r) rflag=1
instanceIp="$OPTARG"
;;
P) Pflag=1
protocol="$OPTARG"
;;
p) pflag=1
ports="$OPTARG"
;;
l) lflag=1
publicIp="$OPTARG"
;;
d) dflag=1
dports="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
OUTFILE=$(mktemp)
tcp_or_udp_nat $op $protocol $publicIp $ports $instanceIp $dports
result=$?
unlock_exit $result $lock $locked

View File

@ -1,98 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage:\n %s -A -l <public-ip-address>\n" $(basename $0) >&2
printf " %s -D -l <public-ip-address>\n" $(basename $0) >&2
}
add_snat() {
logger -t cloud "$(basename $0):Added SourceNAT $pubIp on interface $ethDev"
sudo iptables -t nat -D POSTROUTING -j SNAT -o $ethDev --to-source $pubIp
sudo iptables -t nat -A POSTROUTING -j SNAT -o $ethDev --to-source $pubIp
return $?
}
remove_snat() {
logger -t cloud "$(basename $0):Removing SourceNAT $pubIp on interface $ethDev"
sudo iptables -t nat -D POSTROUTING -j SNAT -o $ethDev --to-source $pubIp
return $?
}
#set -x
lflag=0
cflag=0
op=""
while getopts 'ADl:c:' OPTION
do
case $OPTION in
A) Aflag=1
op="-A"
;;
D) Dflag=1
op="-D"
;;
l) lflag=1
pubIp="$OPTARG"
;;
c) cflag=1
ethDev="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
if [ "$Aflag$Dflag" != "1" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$lflag$cflag" != "11" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ "$Aflag" == "1" ]
then
add_snat $publicIp
unlock_exit $? $lock $locked
fi
if [ "$Dflag" == "1" ]
then
remove_snat $publicIp
unlock_exit $? $lock $locked
fi
unlock_exit 1 $lock $locked

View File

@ -1,229 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# vpc_privategw_acl.sh_rule.sh -- allow/block some ports / protocols to vm instances
# @VERSION@
source /root/func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: -a <public ip address:protocol:startport:endport:sourcecidrs> \n" $(basename $0) >&2
printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n"
}
#set -x
#FIXME: eating up the error code during execution of iptables
acl_switch_to_new() {
sudo iptables -D FORWARD -o $dev -j _ACL_INBOUND_$dev 2>/dev/null
sudo iptables-save | grep "\-j _ACL_INBOUND_$dev" | grep "\-A" | while read rule;
do
rule1=$(echo $rule | sed 's/\_ACL_INBOUND/ACL_INBOUND/')
sudo iptables $rule1
rule2=$(echo $rule | sed 's/\-A/\-D/')
sudo iptables $rule2
done
sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_remove_backup() {
sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -D FORWARD -o $dev -j _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j _ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_remove() {
sudo iptables -F ACL_INBOUND_$dev 2>/dev/null
sudo iptables -D FORWARD -o $dev -j ACL_INBOUND_$dev 2>/dev/null
sudo iptables -X ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null
}
acl_restore() {
acl_remove
sudo iptables -E _ACL_INBOUND_$dev ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -E _ACL_OUTBOUND_$dev ACL_OUTBOUND_$dev 2>/dev/null
}
acl_save() {
acl_remove_backup
sudo iptables -E ACL_INBOUND_$dev _ACL_INBOUND_$dev 2>/dev/null
sudo iptables -t mangle -E ACL_OUTBOUND_$dev _ACL_OUTBOUND_$dev 2>/dev/null
}
acl_chain_for_guest_network () {
acl_save
# inbound
sudo iptables -N ACL_INBOUND_$dev 2>/dev/null
# drop if no rules match (this will be the last rule in the chain)
sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null
sudo iptables -A FORWARD -o $dev -j ACL_INBOUND_$dev 2>/dev/null
# outbound
sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null
sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -j ACL_OUTBOUND_$dev 2>/dev/null
}
acl_entry_for_guest_network() {
local rule=$1
local ttype=$(echo $rule | cut -d: -f1)
local prot=$(echo $rule | cut -d: -f2)
local sport=$(echo $rule | cut -d: -f3)
local eport=$(echo $rule | cut -d: -f4)
local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g')
local action=$(echo $rule | cut -d: -f6)
if [ "$sport" == "0" -a "$eport" == "0" ]
then
DPORT=""
else
DPORT="--dport $sport:$eport"
fi
logger -t cloud "$(basename $0): enter apply acl rules on private gateway interface : $dev, inbound:$inbound:$prot:$sport:$eport:$cidrs"
# note that rules are inserted after the RELATED,ESTABLISHED rule
# but before the DROP rule
for lcidr in $cidrs
do
[ "$prot" == "reverted" ] && continue;
if [ "$prot" == "icmp" ]
then
typecode="$sport/$eport"
[ "$eport" == "-1" ] && typecode="$sport"
[ "$sport" == "-1" ] && typecode="any"
if [ "$ttype" == "Ingress" ]
then
sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \
--icmp-type $typecode -j $action
else
let egress++
sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \
--icmp-type $typecode -j $action
fi
else
if [ "$ttype" == "Ingress" ]
then
sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \
$DPORT -j $action
else
let egress++
sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \
$DPORT -j $action
fi
fi
result=$?
[ $result -gt 0 ] &&
logger -t cloud "Error adding iptables entry for private gateway interface : $dev,inbound:$inbound:$prot:$sport:$eport:$cidrs" &&
break
done
logger -t cloud "$(basename $0): exit apply acl rules for private gw interface : $dev"
return $result
}
dflag=0
gflag=0
aflag=0
mflag=0
rules=""
rules_list=""
dev=""
mac=""
while getopts 'd:a:M:' OPTION
do
case $OPTION in
d) dflag=1
dev="$OPTARG"
;;
a) aflag=1
rules="$OPTARG"
;;
M) mflag=1
mac="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
if [ "$dflag$aflag" != "11" ]
then
usage
unlock_exit 2 $lock $locked
fi
if [ -n "$rules" ]
then
rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ")
fi
# rule format
# protocal:sport:eport:cidr
#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32
# if any entry is reverted , entry will be in the format <ip>:reverted:0:0:0
# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:ACCEPT:,172.16.92.44:tcp:220:220:0.0.0.0/0:DROP,200.1.1.2:reverted:0:0:0
success=0
acl_chain_for_guest_network
egress=0
for r in $rules_list
do
acl_entry_for_guest_network $r
success=$?
if [ $success -gt 0 ]
then
logger -t cloud "$(basename $0): failure to apply acl rules on private gateway interface : $dev"
break
else
logger -t cloud "$(basename $0): successful in applying acl rules on private gateway interface : $dev"
fi
done
if [ $success -gt 0 ]
then
logger -t cloud "$(basename $0): restoring from backup on private gateway interface : $dev"
acl_restore
else
logger -t cloud "$(basename $0): deleting backup on private gateway interface : $dev"
if [ $egress -eq 0 ]
then
sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null
else
sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j DROP 2>/dev/null
fi
acl_switch_to_new
fi
unlock_exit $success $lock $locked

View File

@ -1,124 +0,0 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# @VERSION@
source /root/func.sh
source /opt/cloud/bin/vpc_func.sh
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
usage() {
printf "Usage: %s: (-A|-D) -r <target-instance-ip> -l <public ip address> -d < eth device> \n" $(basename $0) >&2
}
#set -x
vpnoutmark="0x525"
static_nat() {
local op=$1
local publicIp=$2
local instIp=$3
local op2="-D"
local tableNo=${ethDev:3}
logger -t cloud "$(basename $0): static nat: public ip=$publicIp \
instance ip=$instIp op=$op"
#if adding, this might be a duplicate, so delete the old one first
[ "$op" == "-A" ] && static_nat "-D" $publicIp $instIp
# the delete operation may have errored out but the only possible reason is
# that the rules didn't exist in the first place
[ "$op" == "-A" ] && op2="-I"
if [ "$op" == "-A" ]
then
# put static nat rule one rule after VPN no-NAT rule
# rule chain can be used to improve it later
iptables-save -t nat|grep "POSTROUTING" | grep $vpnoutmark > /dev/null
if [ $? -eq 0 ]
then
rulenum=2
else
rulenum=1
fi
fi
# shortcircuit the process if error and it is an append operation
# continue if it is delete
(sudo iptables -t nat $op PREROUTING -d $publicIp -j DNAT \
--to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) &&
# add mark to force the package go out through the eth the public IP is on
#(sudo iptables -t mangle $op PREROUTING -s $instIp -j MARK \
# --set-mark $tableNo &> $OUTFILE || [ "$op" == "-D" ]) &&
(sudo iptables -t nat $op2 POSTROUTING $rulenum -o $ethDev -s $instIp -j SNAT \
--to-source $publicIp &>> $OUTFILE )
result=$?
logger -t cloud "$(basename $0): done static nat entry public ip=$publicIp op=$op result=$result"
if [ "$op" == "-D" ]
then
return 0
fi
return $result
}
rflag=
lflag=
dflag=
op=""
while getopts 'ADr:l:' OPTION
do
case $OPTION in
A) op="-A"
;;
D) op="-D"
;;
r) rflag=1
instanceIp="$OPTARG"
;;
l) lflag=1
publicIp="$OPTARG"
;;
?) usage
unlock_exit 2 $lock $locked
;;
esac
done
ethDev=$(getEthByIp $publicIp)
result=$?
if [ $result -gt 0 ]
then
if [ "$op" == "-D" ]
then
removeRulesForIp $publicIp
unlock_exit 0 $lock $locked
else
unlock_exit $result $lock $locked
fi
fi
OUTFILE=$(mktemp)
static_nat $op $publicIp $instanceIp
result=$?
unlock_exit $result $lock $locked