Thursday, January 8, 2015

The Beginner’s Guide to iptables

About iptables

iptables is a command-line firewall utility that uses policy chains to allow or block traffic. When a connection tries to establish itself on your system, iptables looks for a rule in its list to match it to. If it doesn’t find one, it resorts to the default action.
iptables almost always comes pre-installed on any Linux distribution. To update/install it, just retrieve the iptables package:
sudo apt-get install iptables
There are GUI alternatives to iptables like Firestarter, but iptables isn’t really that hard once you have a few commands down. You want to be extremely careful when configuring iptables rules, particularly if you’re SSH’d into a server, because one wrong command can permanently lock you out until it’s manually fixed at the physical machine.

Types of Chains

iptables uses three different chains: input, forward, and output.
Input – This chain is used to control the behavior for incoming connections. For example, if a user attempts to SSH into your PC/server, iptables will attempt to match the IP address and port to a rule in the input chain.
Forward – This chain is used for incoming connections that aren’t actually being delivered locally. Think of a router – data is always being sent to it but rarely actually destined for the router itself; the data is just forwarded to its target. Unless you’re doing some kind of routing, NATing, or something else on your system that requires forwarding, you won’t even use this chain.
There’s one sure-fire way to check whether or not your system uses/needs the forward chain.
iptables -L -v

The screenshot above is of a server that’s been running for a few weeks and has no restrictions on incoming or outgoing connections. As you can see, the input chain has processed 11GB of packets and the output chain has processed 17GB. The forward chain, on the other hand, has not needed to process a single packet. This is because the server isn’t doing any kind of forwarding or being used as a pass-through device.
Output – This chain is used for outgoing connections. For example, if you try to ping howtogeek.com, iptables will check its output chain to see what the rules are regarding ping and howtogeek.com before making a decision to allow or deny the connection attempt.
The caveat
Even though pinging an external host seems like something that would only need to traverse the output chain, keep in mind that to return the data, the input chain will be used as well. When using iptables to lock down your system, remember that a lot of protocols will require two-way communication, so both the input and output chains will need to be configured properly. SSH is a common protocol that people forget to allow on both chains.

Policy Chain Default Behavior

Before going in and configuring specific rules, you’ll want to decide what you want the default behavior of the three chains to be. In other words, what do you want iptables to do if the connection doesn’t match any existing rules?
To see what your policy chains are currently configured to do with unmatched traffic, run the iptables -L command.

As you can see, we also used the grep command to give us cleaner output. In that screenshot, our chains are currently figured to accept traffic.
More times than not, you’ll want your system to accept connections by default. Unless you’ve changed the policy chain rules previously, this setting should already be configured. Either way, here’s the command to accept connections by default:
iptables --policy INPUT ACCEPT
iptables --policy OUTPUT ACCEPT
iptables --policy FORWARD ACCEPT
By defaulting to the accept rule, you can then use iptables to deny specific IP addresses or port numbers, while continuing to accept all other connections. We’ll get to those commands in a minute.
If you would rather deny all connections and manually specify which ones you want to allow to connect, you should change the default policy of your chains to drop. Doing this would probably only be useful for servers that contain sensitive information and only ever have the same IP addresses connect to them.
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

Connection-specific Responses

With your default chain policies configured, you can start adding rules to iptables so it knows what to do when it encounters a connection from or to a particular IP address or port. In this guide, we’re going to go over the three most basic and commonly used “responses”.
Accept – Allow the connection.
Drop – Drop the connection, act like it never happened. This is best if you don’t want the source to realize your system exists.
Reject – Don’t allow the connection, but send back an error. This is best if you don’t want a particular source to connect to your system, but you want them to know that your firewall blocked them.
The best way to show the difference between these three rules is to show what it looks like when a PC tries to ping a Linux machine with iptables configured for each one of these settings.
Allowing the connection:

Dropping the connection:

Rejecting the connection:

Allowing or Blocking Specific Connections

With your policy chains configured, you can now configure iptables to allow or block specific addresses, address ranges, and ports. In these examples, we’ll set the connections to DROP, but you can switch them to ACCEPT or REJECT, depending on your needs and how you configured your policy chains.
Note: In these examples, we’re going to use iptables -A to append rules to the existing chain. iptables starts at the top of its list and goes through each rule until it finds one that it matches. If you need to insert a rule above another, you can use iptables -I [chain] [number] to specify the number it should be in the list.
Connections from a single IP address
This example shows how to block all connections from the IP address 10.10.10.10.
iptables -A INPUT -s 10.10.10.10 -j DROP
Connections from a range of IP addresses
This example shows how to block all of the IP addresses in the 10.10.10.0/24 network range. You can use a netmask or standard slash notation to specify the range of IP addresses.
iptables -A INPUT -s 10.10.10.0/24 -j DROP
or
iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP
Connections to a specific port
This example shows how to block SSH connections from 10.10.10.10.
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP
You can replace “ssh” with any protocol or port number. The -p tcp part of the code tells iptables what kind of connection the protocol uses.  If you were blocking a protocol that uses UDP rather than TCP, then -p udp would be necessary instead.
This example shows how to block SSH connections from any IP address.
iptables -A INPUT -p tcp --dport ssh -j DROP

Connection States

As we mentioned earlier, a lot of protocols are going to require two-way communication. For example, if you want to allow SSH connections to your system, the input and output chains are going to need a rule added to them. But, what if you only want SSH coming into your system to be allowed? Won’t adding a rule to the output chain also allow outgoing SSH attempts?
That’s where connection states come in, which give you the capability you’d need to allow two way communication but only allow one way connections to be established. Take a look at this example, where SSH connections FROM 10.10.10.10 are permitted, but SSH connections TO 10.10.10.10 are not. However, the system is permitted to send back information over SSH as long as the session has already been established, which makes SSH communication possible between these two hosts.
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -d 10.10.10.10 -m state --state ESTABLISHED -j ACCEPT

Saving Changes

The changes that you make to your iptables rules will be scrapped the next time that the iptables service gets restarted unless you execute a command to save the changes.  This command can differ depending on your distribution:
Ubuntu:
sudo /sbin/iptables-save
Red Hat / CentOS:
/sbin/service iptables save
Or
/etc/init.d/iptables save

Other Commands

List the currently configured iptables rules:
iptables -L
Adding the -v option will give you packet and byte information, and adding -n will list everything numerically. In other words – hostnames, protocols, and networks are listed as numbers.
To clear all the currently configured rules, you can issue the flush command.
iptables -F

Friday, September 12, 2014

Why do you need to use a VPN?

Here are three words for you: Virtual Private Network (more commonly referred to as VPN). If you've never heard of the term, or aren't sure about its exact nature in our info tech world, then chances are you've never utilized one. A VPN is facilitated for several reasons, by individuals and the business sector alike. Anyone who initiates one for their time on the internet will have a variety of reasons. They can vary according to the individual’s needs and wants;  scaling from minimal personal usage to access international television programs not available in their region, to encryption and security during time spent in cyberspace. In essence, a VPN is used to secure and encrypt communications when using an untrusted network which is in the public domain.

The latter is the more common theme. In this day and age where big brother seems to lurk in every corner of our internet browser, more and more people, and companies, are resorting to the use of a VPN provider. In fact, as people are educating themselves on the realms of the digital jungle that is fast becoming a second home, the VPN is becoming a common household name. And why not? With hackers at the ready to steal your sensitive information, and government regimes watching and monitoring your every move, the VPN is now an essential addition to add to our daily internet rituals. In essence, public networks are cesspits, and if we dwell in them too long, without the correct protective elements, then we tend to ‘pick up’ those bugs which dwell in them.

When you use a VPN, the usual presentation is to launch a VPN client on your personal computer. You log in; your computer then “exchanges trusted keys with a server,” and once both systems have been authentically verified, your communication on the internet is secure.

However, not all VPNs are created equally. When searching for the right VPN for your own use, it is important to know what it is you are signing up for, and who with. You need to take into consideration connectivity protocols, features and server locations. The best VPNs will offer a good selection on these criteria. Most importantly, the VPN Provider should have a so called ‘no-logging policy’ which ensures that no user activity will be logged.

You need to be aware of other considerations such as trusting your provider with your data. In other words, what do they log? Everything outside of your VPN server is secure from eavesdropping, but those sharing the same provider may have access to your data. Some VPN providers keep logs in case a government requests them, so decide what is acceptable to you when it comes to logging. 

Wednesday, September 10, 2014

Apple’s first crack on the release!

Let’s start with some general observations that apply to both the iPhone 6 and the iPhone 6 Plus. The iPhone 5 and 5S both had flat fronts, sides, and backs with well-defined edges, but those are gone in the iPhone 6. The glass on the front now curves down slightly all the way around the edge to meet the newly-curved sides and back of the phone. It sort of recalls the iPhone 3G or 3GS, which had similar curves but used plastic all the way around instead of aluminum and glass. 

The back of the phones are made out of aluminum with some clearly visible cutouts made to allow wireless signals in and out. The design as a whole is more reminiscent of the 2012 iPod Touch than current iPhones, an observation that extends to the slightly protruding camera lens. You won’t notice this bulge if you keep your phone in a case or sit it on a soft surface, but if you set the phone on a hard table it definitely will wobble a bit in place. Both phones feel lighter than you’d expect them to—4.55 ounces for the 6 and 6.07 ounces for the 6 Plus, compared to 5.64 ounces for the 5-inch HTC One M8 or 5.08 ounces for the new Moto X—but they still feel as sturdy as you’d expect from an Apple product.

The new screen is the star of the show here—the iPhone 6 has a 1334×750 display that retains the 326 PPI density of older Retina iPhones, it just fits more on the screen at once than the iPhone 5 or 5S can. All apps that have been optimized for the larger display can show more stuff at once than they could before, which is obvious if you open Safari or even the Settings app. Icons and buttons remain the same size they were before, in accordance with Apple’s best practices for app design—the Home screen can fit one additional horizontal row of icons than the iPhone 5 can, but you can still only fit in four icons per row.

To make one-handed usage easier on both phones, Apple has introduced a feature called “Reachability.” Double tap the TouchID button and the contents of the screen will shift downward, letting you reach the top half of your app’s contents even if you can only reach the bottom half of the phone’s actual screen. Once you’ve entered Reachability mode, you can also pull down from the top of the “window” to bring up the Notification Center.

We suspect that many iPhone 6 users (especially iPhone 6 Plus users) will simply adjust to using two hands more often with their iPhones, possibly without even realizing it. But Reachability feels like something best used only when you don’t have that option, rather than a great, easy way to handle all your navigation.

Sunday, July 20, 2014

BitLocker issues for Windows Phone Cyan Update

The Lumia Cyan Update has only just started rolling out for the Lumia 625 and Lumia 925, but already we're seeing some of the first bugs come to light. According to a lengthy thread on the Nokia support forum, consumers are experiencing issues after upgrading their Lumia Windows Phones running the 8.1 Preview for Developers and using BitLocker full disk encryption.
The BitLocker encryption appears to cause the smartphone to hang on boot, making it unusable. All that's presented to the user is a message to connect the device to a PC. Luckily, there's a solution, but it requires a full reset the Windows Phone using Nokia's software suite.

To recover this drive, plug in the USB drive that has the BitLocker recovery key:

BitLocker needs your recovery key to unlock your drive because the trusted platform module is not accessible.

For more information on how to retrieve this key, go to http://windows.microsoft.com/recoverykeyfaq from another PC or mobile device.

Press Enter to Reboot and try again

Press Esc or the windows key for other recovery options"

As noted above, there is a solution to this problem, which is to completely reset the device using Nokia's software recovery suite. This should return everything back to normal. According to reports on the same thread (as well as elsewhere), those who upgrade from Windows Phone 8.0 Update 3 to Windows Phone 8.1 and Lumia Cyan have no issues.

It is important to note that regular consumer level devices are not having this problem as BitLocker is an optional security tool enabled through corporate device policies. Although this may be a headache for an IT department, it should not affect the majority of consumers. Indeed, Windows Phone Central has not been flooded with tips on this yet.
 

Wednesday, June 18, 2014

Pinch To Zoom functionality in Windows Phone

If you're building a WP8 exclusive app you can use the new ManipulationDeltaEventArgs.PinchManipulation for pinch & zoom effects. Here's a basic example of how to use ManipulationDeltaEventArgs.PinchManipulation data to scale, move and rotate an image.
 
First, we'll create a basic image hovering in the middle of a grid:
 
<Grid x:Name="ContentPanel">
<Image Source="Assets\Headset.png" Width="200" Height="150" ManipulationDelta="Image_ManipulationDelta" x:Name="img" >
<Image.RenderTransform>
<CompositeTransform CenterX="100" CenterY="75" />
</Image.RenderTransform>
</Image>
</Grid>
 
Next, we'll handle the ManipulationDelta event, check if it's a Pinch Manipulation and apply the correct Silverlight transformations on our UIElement.
 
private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
if (e.PinchManipulation != null)
{
        
var transform = (CompositeTransform)img.RenderTransform;
 
// Scale Manipulation
transform.ScaleX = e.PinchManipulation.CumulativeScale;
transform.ScaleY = e.PinchManipulation.CumulativeScale;
 
// Translate manipulation
var originalCenter = e.PinchManipulation.Original.Center;
var newCenter = e.PinchManipulation.Current.Center;
transform.TranslateX = newCenter.X - originalCenter.X;
transform.TranslateY = newCenter.Y - originalCenter.Y;
 
// Rotation manipulation
transform.Rotation = angleBetween2Lines(
e.PinchManipulation.Current,
e.PinchManipulation.Original);
 
// end
 
e.Handled = true;
 
}
}
 

public static double angleBetween2Lines(PinchContactPoints line1, PinchContactPoints line2)
{
if (line1 != null && line2 != null)
{
double angle1 = Math.Atan2(line1.PrimaryContact.Y - line1.SecondaryContact.Y, line1.PrimaryContact.X - line1.SecondaryContact.X);
double angle2 = Math.Atan2(line2.PrimaryContact.Y - line2.SecondaryContact.Y, line2.PrimaryContact.X - line2.SecondaryContact.X);
return (angle1 - angle2) * 180 / Math.PI;
}
else
{
return 0.0;
}
}



Scaling: PinchManipulation actually tracks scaling for us, so all we had to do is apply PinchManipulation.CumulativeScale to the scaling factor.

Transform: PinchManipulation tracks the original center and the new center (calculated between the two touch points). By subtracting the new center from the old center we can tell how much the UIElement needs to move and apply that to a translate transform. Note that a better solution here would also account for multiple Manipulation sessions by tracking cumulative original centers which this code doesn't.

Rotation: We figured out the angle between the two touch points and applied it as the rotation transform.
 
 

Monday, June 9, 2014

Find listbox item after tap and hold

First, make sure to put your gesture listener not under the ListBox itself, but in the top level container of the ListBox's data template (the StackPanel in this example):


<ListBox>  
    <ListBox.ItemTemplate>  
        <DataTemplate>   
            <StackPanel>   
                <toolkit:GestureService.GestureListener>   
                    <toolkit:GestureListener Hold="ListItem_Hold"/>   
                </toolkit:GestureService.GestureListener>   
                <TextBlock Text="{Binding LineOne}"/>   
                <TextBlock Text="{Binding LineTwo}"/>   
            </StackPanel>   
        </DataTemplate>  
    </ListBox.ItemTemplate>  
</ListBox> 

In the Hold event handler, the sender will be the StackPanel of the current ListBoxItem. The DataContext of the StackPanel is the view model item (it is like listbox.SelectedItem when an item is selected, however note that a hold gesture won't actually cause an item to be selected).

private void ListItem_Hold(object sender, GestureEventArgs e) 
        { 
            // sender is the StackPanel in this example 
            var holdItem = (sender as StackPanel).DataContext; 
 
            // holdItem has the type of the view model 
        } 

Sunday, June 8, 2014

Clearing backstack in NavigationService

You can use NavigationService.RemoveBackEntry:
For instance, to remove all entries from the stack:
while (this.NavigationService.BackStack.Any())
{
   this.NavigationService.RemoveBackEntry();
}

Also, if you want to remove only the previous page after checking its URI:
var previousPage = this.NavigationService.BackStack.FirstOrDefault();

if (previousPage != null && previousPage.Source.ToString().StartsWith("/MainPage.xaml"))
{
    this.NavigationService.RemoveBackEntry();
}