Archive

Author Archive

Simulating Slow Connections in OS X or Linux

April 10th, 2013 Comments off

Simulating Slow and Laggy Connections

 

Do you want to simulate how it feels to load your site from a mobile connection (If it’s AT&T just turn off your network for an accurate simulation- I kid, don’t sue. But seriously AT&T, figure it out.) or from a laggy network? In OS X or Linux, you’ve got everything you need already installed: ipfw (IP firewall and traffic shaper control).

Create a Pipe

Configure a pipe with the appropriate bandwidth (I’ve also added a 200 ms response delay in this example).

sudo ipfw pipe 1 config bw 16bit/s delay 200ms

Attach the Pipe

In this example we’re going to use port 80, but you can also use port 443 or any other port that you may be testing communication on. Additionally, you can attach the pipe to multiple ports.

sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 2 pipe 1 dst-port 80

That’s it!

Wait a second, you say! Now your network connection is completely throttled and everything is running terribly! You need to delete both ipfw entries and the pipe that were previously created.

Here’s how you undo what you’ve just done:

sudo ipfw delete 1
sudo ipfw delete 2
sudo ipfw pipe 1 delete
Categories: Linux, Tutorial Tags: , , , ,

Subversion: Merging a Branch to Trunk

April 1st, 2013 Comments off

Merging a Subversion Branch Back to Trunk

So, you’ve successfully branched code and have a great new feature set you need to get back to trunk, but how? Easy!

Get the latest revision number of the branch you want to merge

If you already have the branch checked out, cd to that directory and svn update it.

 svn update 
svn log --stop-on-copy 

Alternatively, if you don’t have (or don’t want to have) the branch checked out locally, you can do it remotely.

svn log --stop-on-copy https://url/to/branch

The last line returned contains the first revision of that branch, it’ll look something like this:

$ svn log --stop-on-copy 

... more lines like the one below ...

Subversion commit message. 
------------------------------------------------------------------------ 
rXXXX | mustafaashurex | 2013-04-01 09:50:03 -0700 (Mon, 01 Apr 2013) | 1 line 

Check out trunk

svn co https://url/to/trunk

Alternatively, you can just update trunk if you have it checked out

Change to the trunk working directory and do the following:

svn update

You should see output like this:

$ svn update 
At revision YYYY.

This will update your copy of trunk to the most recent version and tell you the revision you are at. Make note of that number as well (should say “At revision YYYY”; where YYYY is the second number you’ll need to remember).

Perform the merge

Now you’ve got the details you need; the revision at which the branch started and the most current revision.

Change directory to the trunk

svn merge -rXXXX:YYYY https://url/to/branch

Check in the results:

svn ci -m "[MERGE XXXX:YYYY] Merging mySvnProject [branchname] -r[XXXX]:[YYYY] back to trunk."

Final thoughts

Described above is how to perform the act of merging a branch back to the trunk, there are however many things I didn’t cover. Before you perform this operation you should do a review of all the changes and potential conflicts if the trunk was also receiving active development.

In a team environment, this would be a great time for a peer/mentor code review as well as an approach review for the bugs/featured covered in the branch.

Deploying New Relic on AWS Elastic Beanstalk with Tomcat

August 8th, 2012 Comments off

It’s relatively straightforward and New Relic’s docs show you how to do it just fine for Tomcat 6. First, go look over New Relic’s documentation, I’m not going to repeat all the details they show there.
The only difference is the following:
At the Container JVM Command Line Options field, instead of the -javaagent string New Relic recommends, put this in instead

-javaagent:/opt/tomcat7/webapps/ROOT/WEB-INF/lib/newrelic.jar

Setting the Logging Environment Name

You can also set the logging environment name in the same line. After the -javaagent string you justed enter, put in this:

-Dnewrelic.environment=your_environment_name

If you read through the newrelic.yml file, you can see all the different options that switching environments can give to you besides just a different name in the New Relic dashboard.

Categories: AWS Tags: , , , ,

Encrypting a tar or gz (gzip) File with OpenSSL

July 17th, 2012 3 comments

When you have sensitive data that you need to transmit but want to make it easy to encrypt and decrypt it, use some standard tools to get the job done!

I recently had an issue where a client was using OS X laptops running an Admin panel written in PHP on MAMP in an environment that may or may not have an internet connection. The problem was that they needed to be able to dump their database data into an encrypted file so that they could send the data off when they get a connection (via email, upload, who knows). My initial response was to use gpg to encrypt the file and hand out the keys to the people who would eventually be reading the data.

Turns out, this was going to be a nightmare and I needed something ‘easier’. How about encrypting a tar file with OpenSSL? Bingo! This solution uses utilities that are already on the machine and no installations need to be performed. The reason this was such a big deal is because the laptops running this software will be all over the world with various levels of technical acumen and it will be a nightmare to make sure every single laptop has been updated correctly.

Encrypting Your File

tar and gzip the file, then encrypt it using des3 and a secret key.

tar cvzf - mysql_dump.sql | openssl des3 -salt -k #YOUR PASSWORD# | dd of=encrypted_mysql_dump

That simple!

Decrypting Your File

dd if=encrypted_mysql_dump |openssl des3 -d -k #YOUR PASSWORD# |tar xvzf -

Essentially, just call all the commands in the reverse order.

Download the Utility Scripts

Download them!

Securing Passwords, One Way Hashes, PBKDF2, PHP and You

June 8th, 2012 2 comments

Plain text passwords and simple one way hashes are not enough to protect your users. You need salt, pepper, and peanut butter. Am I crazy you ask? Maybe, but read on.

It happens to big huge companies (LinkedIn, Last.fm, eHarmony), the little guys, and everything in between. Databases get breached and passwords get hacked. It always surprises me when I hear about how many thousands of users had the password “password”, or that the target’s password hashes were cracked in a matter of hours or days- or worse, their passwords were plain text. At this point, it is so easy to make passwords pretty secure with just basic knowledge of cryptography and hashing. As a matter of fact, as a competent developer, you don’t need to know much at all about the how’s and why’s of crypto to secure your users’ data.

First, do not think you are safe because you run your passwords through MD5 or SHA-256. MD5 has been cracked and SHA-256 is barely better than storing their passwords in plain text. Cryptograhic hash functions are NOT password hash functions!

One Way Hashing

A one way hash performs a bunch of mathematical operations that transform input into a (mostly) unique output, called a digest. Because these operations are one way, you cannot ‘decrypt’ the output- you can’t turn a digest into the original input. Good cryptographic hash functions should not generate digests that are the same for different input. Additionally, when the input is changed, just slightly, the resulting digest should be very different.

A typical use case would be when a user signs up for a website and creates a password. The conscientious developer takes the plain text password, runs it through a hashing function (let’s say, MD5) and stores the result in the database. When the user goes to log in the next time they enter their password and the authentication mechanism runs it through MD5 and compares the result against what is stored in the database.

That sounds pretty safe, right? Wrong. It’s akin to locking the door and leaving the window open. If the database was stolen it might make it harder to infer anything about the passwords just by looking at the data, but it doesn’t really make it any harder to guess or “crack” the password.

Password Hash Functions

… are not the same as cryptographic hash functions

Just using a cryptographic function on a plain text password doesn’t defend it very well. There a number of major problems and threats that are not being avoided. The two biggest are speed and recognizability of hashes.

Hashing Speed

Cryptographic hash functions are used for lots of things, most of them have to do with fingerprinting and verifying data. They are designed to be very fast so that the encryption processes isn’t slowed down. This presents a big problem for password hashing. Speed. The faster a function creates a digest, the more frequently an attacker can guess the password and compare the output. MD5, for instance, is so fast that on basic hardware you could guess over 5 billion times per second. Think about it for a second, do you need that speed to allow your users to log in? When it takes 15 seconds to enter your username and password, a few second to log in, and a few seconds of perceived page load time, will they notice the difference between .000001 seconds or 1 second for the authentication mechanism? The answer is no, not to enough of a degree to degrade their experience. For password hashing, slower is good.

Recognizability of Hashes

What happens when 10,000 people all use “password” as their password? Their hashes are all the same! If you just get one account cracked, you automatically crack everyone else with the same hash. If an attacker has a huge, precomputed list of hashes (called a rainbow table), they can scan your database looking for any hashes that match. They’ve already cracked accounts without even guessing a password yet! They could have a huge percentage of your system’s passwords before ever once making a guess.

Fortunately though, there are a few relatively easy things you can do to make their life harder. You don’t need to do anything heroic and the code isn’t even that tricky. Heck, most of it already exists and is free to use.

Salting

Talk about low hanging fruit. All you have to do is add some random characters to their password (and keep track of them). A salt is a random sequence of data which is added to the hash function or the password string itself. Say you generated a salt “12345″ and had a password “password”, you could put them together “password12345″ and run that through your hash function to produce a digest that wouldn’t be so easily given up. Every password should have its own salt and should be at minimum, 32 characters or more to make it harder to guess the digest.

This is a basic salt generation algorithm. Do NOT use this function for generating salts where you are trying to protect details like credit card numbers, or even email addresses for that matter. It’s a pretty poor implementation, really.

public static function CreateSalt($length = 128, $validChars = null)
{
    $salt = '';
    list($usec, $sec) = explode(' ', microtime());

    $seed = ((float)$sec + ((float)$usec * 100000)) * ((float)microtime() * 1000000);
    mt_srand($seed);

    $inputs = array_merge(range('z','a'), range(0,9), range('A','Z'), array('@','!','#','%','&','*','+','_','-','~','?','.'));

    $inputsLength = count($inputs) - 1;

    for($i = 0; $i < $length; $i++)
        $salt .= $inputs{mt_rand(0, $inputsLength)};

    return $salt;
}

When we create a user password we’ll generate a salt, add it to the password string, hash the password to get a digest, then store the salt and digest in the database. To log the user in subsequently we could use functions like the following:

function HashPassword($password, $salt)
{
    return hash('sha256', $password . $salt);
}

function IsValidPassword($password, $salt, $digest)
{
    return (HashPassword($password, $salt) == $digest);
}

Password Stretching

Stretching is creating a digest of a digest (of a digest of a digest … of a digest … you get it.) If you create a digest of a password, then create a digest of that X number of times you can no longer simply create a digest (from a rainbow table or otherwise) and compare it directly to the digest that is stored in the database. To compare passwords you’ll have to run the exact same number of iterations if hashing digests to compare passwords. This is useful on multiple fronts: it slows things down and (in conjunction with salted passwords) your hashes no longer look the same as everyone else’s. It stands to reason that if hashing a password once takes X amount of time, hashing it twice will take approximately 2X. You’ve just cut in half the number of times an attacker can guess your passwords. Congratulations! A good system takes so long to process a single digest that guessing a password using brute force will take more than a lifetime.

Let’s modify our password hashing function:

function HashPassword($password, $salt, $iterations = 1024)
{
    // Create the first digest
    $output = hash('sha256', $password . $salt);
    for($i = 0; $i < $iterations; $i++)
    {
        // Re-salt every hash for extra randomization
        $output = hash('sha256', $output . $salt);
    }
}

Notice that I have re-salted every hash to add extra randomization to the digest… just another wrinkle to throw at an attacker.

Pepper

Additionally, you can have an application wide salt, called a pepper. Think of it as a salt for the salt, except this salt is unique only to the application, server, environment, or database.
You could use it like that hash('sha256', $pepper . $password . $salt);

Adaptive Key Derivation

Adaptive key derivation functions generate digests from passwords while applying salts and stretching. They implement many more wrinkles and are tested against attack vectors you may never think of- which is the important part. They are tested against attack vectors. Rolling your own cryptographic functions introduce a lot of unnecessary exposure and take more time than using generally accepted libraries, implementations and functions. I’m going to focus on the one I know best, PBKDF2. There are others such as bcrypt and mcrypt

Peanut Butter Keeps Dogs Friendly Too

PBKDF2 (Password-Based Key Derivation Function) is probably the most widely used derivation function. It is a container for a hash function, e.g. SHA-1 or RIPEMD,. For each input it applies a salt and iterates the hash many times in such a way that not much entropy (length and randomness) is lost. Primarily, it is done in such a way that it is SLOW to generate a single digest. The US government and NSA use this for generating strong encryption keys.

Adaptive keys are great first step, but remember, this is one tiny piece of securing user data.

Below is a very basic class I created that can be used for generating salts and digests through a variety of ways. You can download it here. This file will be updated regularly, so stay in touch!

<?php
/**
 * PasswordUtil.php
 * @package AC
 */

 /**
  * AC_PasswordUtil
  *
  * Password hashing and generation utilities
  * @package AC
  * @category Security
  * @version $Id:$
  * @author Mustafa Ashurex <[email protected]>
  */
class AC_PasswordUtil
{
    /**
     * @var int Default hash key length
     */
    const DEFAULT_KEY_LENGTH = 256;
    /**
     * @var int Default number of times to iterate a hash
     */
    const DEFAULT_ITERATIONS = 1024;
    /**
     * @var string Default hash algorithm to use for PBKDF2
     */
    const DEFAULT_PBKDF2_ALGO = 'SHA256';
    /**
     * @var string PBKDF2 algorithm name
     */
    const ALGO_PBKDF2 = 'PBKDF2';
    /**
     * @var string Whirlpool algorithm name
     */
    const ALGO_WHIRLPOOL = 'WHIRLPOOL';


    /**
     * Return the default characters to use for generating salts.
     * @static
     * @return string[] Default characters to use for generating salts.
     */
    public static function DefaultSaltChars()
    {
        return array_merge(range('z','a'), range(0,9), range('A','Z'), array('@','!','#','%','&amp;amp;amp;amp;amp;','*','+','_','-','~','?','.'));
    }

    /**
     * Returns the supported text hashing algorithm names
     * @static
     * @return string[] Supported text hashing algorithm names
     */
    public static function PasswordHashAlgorithms()
    {
        return array(
            self::ALGO_PBKDF2,
            self::ALGO_WHIRLPOOL,
        );
    }


    /**
     * Hashes a plaintext password using the parameters defined. If provided, $pepper
     * will be appended to the beginning of $password and $salt will be used in every hash
     * iteration in various ways (depending on the hash method used).
     * @static
     * @param string $password Plaintext password to hash.
     * @param string $salt A random sequence of bytes to add to the hash function.
     * @param string $pepper Another random sequence of bytes to add an extra secret to the hash generation.
     * @param string $algorithm Password hashing algorithm to use.
     * @param int $keyLength The number of bytes to return.
     * @param int $iterations The number of times to hash the text before returning the value.
     * @return string Returns $keyLength bytes of hashed $password.
     */
    public static function HashPassword($password, $salt, $pepper = null, $algorithm = self::ALGO_PBKDF2,
        $keyLength = self::DEFAULT_KEY_LENGTH, $iterations = self::DEFAULT_ITERATIONS)
    {
        if(strlen(trim($pepper)) > 0)
            $password = $pepper . $password;

        switch($algorithm)
        {
            case self::ALGO_WHIRLPOOL:
                return AC_PasswordUtil::WhirlpoolHash($password, $salt, $keyLength, $iterations);
            case self::ALGO_PBKDF2:
                // Base64 encode the output of PBKDF2 because it's binary
                return base64_encode(AC_PasswordUtil::PBKDF2($password, $salt, $keyLength, $iterations));
            default:
                throw new Exception('Unknown hash algorithm (' . $algorithm . ')!');
        }
    }

    /**
     * Create a random salt string
     * @static
     * @param int $length Number of bytes to return.
     * @param string[] $validChars Array of characters to use for the salt, overrides the default.
     * @return string Randomized salt string of $length bytes.
     */
    public static function CreateSalt($length = 128, $validChars = null)
    {
        $salt = '';
        list($usec, $sec) = explode(' ', microtime());

        $seed = ((float)$sec + ((float)$usec * 100000)) * ((float)microtime() * 1000000);
        mt_srand($seed);

        if(is_array($validChars))
            $inputs = $validChars;
        else
            $inputs = self::DefaultSaltChars();

        $inputsLength = count($inputs) - 1;

        for($i = 0; $i < $length; $i++)
            $salt .= $inputs{mt_rand(0, $inputsLength)};

        return $salt;
    }


    /**
     * Hashes the provided plaintext password using Whirlpool hash and provided parameters.
     * If the Whirlpool algorithm is not present on the system, it will fall back to MD5 if allowed which
     * is not nearly as effective. If not allowed, an exception will be thrown.
     * @static
     * @param string $password
     * @param string $salt
     * @param int $keyLength
     * @param int $iterations
     * @param bool $fallBack
     */
    public static function WhirlpoolHash($password, $salt, $keyLength = self::DEFAULT_KEY_LENGTH, $iterations = self::DEFAULT_ITERATIONS, $fallBack = false)
    {
        $hashMethod = 'whirlpool';

        if($iterations <= 0)
            throw new Exception('Iterations must be greater than 0.');
        elseif($keyLength <= 0)
            throw new Exception('Key length must be greater than 0.');
        elseif(!in_array($hashMethod,hash_algos(),true))
            $hashMethod = 'md5';

        if((!$fallBack)&amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;($hashMethod == 'md5'))
            throw new Exception('Whirlpool hash algorithm not found! Either allow for fallback to MD5 or install Whirlpool.');

        // First thing, stretch the password
        // md5 is used because it is the only hashing function that can be guaranteed to be on a majority of systems
        $output = md5($password . $salt);

        // Hash the output repeatedly
        for($i = 0; $i < $iterations; $i++)
            $output = hash($hashMethod, $output . $salt);

        // If the requested key length is too long, shrink the requested key length
        if(strlen($output) < $keyLength)
            $keyLength = strlen($output);

        return substr($output, 0, $keyLength);
    }


    /**
     * Password-Based Key Derivation Function using PBKDF2
     * as described by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
     * Note: You will want to run base64_encode on the output of this method to use it
     * as text as the output is binary.
     * @static
     * @param string $password The plaintext password to hash.
     * @param string $salt A salt that is unique to the password.
     * @param int $keyLength The length of the derived key in bytes.
     * @param string $iterations The number of times to hash the password before returning.
     * @param string $algorithm The hash algorithm to use.
     * @return Binary string of $keyLength bytes, derived from the provided $password and $salt.
     */
    public static function PBKDF2($password, $salt, $keyLength, $iterations = self::DEFAULT_ITERATIONS, $algorithm = self::DEFAULT_PBKDF2_ALGO)
    {
        $algorithm = strtolower($algorithm);

        if(!in_array($algorithm, hash_algos(), true))
            throw new Exception($algorithm . ' is not found.');
        elseif($iterations <= 0)
            throw new Exception('Iterations must be greater than 0.');
        elseif($keyLength <= 0)
            throw new Exception('Key length must be greater than 0.');

        // Determine the length of the specified hash
        $hashLength = strlen(hash($algorithm, null, true));

        // The number of iterations of the hash necessary to fill $keyLength characters
        // IE: If $keyLength is 256 but $hashLength is only 128, we'd need 2 blocks
        // to fill our $keyLength. If $keyLength was 128 and $hashLength is 256, we'd just
        // take a subset of $output when we're done.
        $blockCount = ceil($keyLength / $hashLength);

        $output = '';

        for($i = 1; $i <= $blockCount; $i++)
        {
            // Beginning hash for this block/iteration
            $iterate = $block = hash_hmac($algorithm, $salt . pack('N', $i), $password, true);

            // Hash each block the specified number of times
            for($j = 1; $j < $iterations; $j++)
            {
                // XOR each iterate
                $iterate ^= ($block = hash_hmac($algorithm, $block, $password, true));
            }
            // Block is completed, append to the output and move on to the next
            $output .= $iterate;
        }

        // Return up to $keyLength characters
        return substr($output, 0, $keyLength);
    }
}
Categories: PHP, Programming Tags: , , , ,

Measuring Download Speed from Linux Command Line

April 16th, 2012 Comments off

I recently needed to test the network speed of the ISP from my Ubuntu 10.04 LTS server. I was trying to think of a better way to test it than going out to a Linux Distro's web site and downloading an ISO from them. I stumbled across this post on StackOverflow that had a URL to a speedtest.net test file and my speedtest scripts were born. I created two scripts, one utilizing wget and on utilizing curl. A lot of machines don't come with curl by default, but it has a lot more output than wget does while downloading.

 

What Do They Do?

The scripts utilize wget or curl to download the speedtest.net 500M test file and you can view the speed results in real time. This is an entirely unscientific method of testing your speed, but much better than say, going to Ubuntu and downloading their latest ISO via wget. Finally, the output is set to go to /dev/null, which means it simply throws away everything it downloads (no cleanup).

 

The Code

Download both scripts here

speedtest-wget.sh

#!/bin/bash
wget --output-document=/dev/null http://speedtest.wdc01.softlayer.com/downloads/test500.zip

speedtest-curl.sh

#!/bin/bash
curl -o /dev/null http://speedtest.wdc01.softlayer.com/downloads/test500.zip	
Categories: Linux Tags: , , , ,

Changing Created By or Author Property in SharePoint 2007

April 12th, 2012 Comments off

After a frustrating experience, I’d like to share the ‘secret’ of updating the Created By and/or Author SPListItem system property. I was trying set the Created By and/or Author SPListIem system property but found that the changes didn’t take and my object’s values were reset after calling SPListItem.Update();

The Wrong Way

If you’re like me, you probably assumed something similar to this would work just fine:

...
SPUser user = ...
SPListItem spListItem = ...
spListItem["Created By"] = user.ID;
spListItem.Update();
...

Not so fast my friend! If you trace/quickwatch your variables you’ll notice that your Created By property is reset after the update. Why? Because you didn’t set all the necessary properties. Oh, you didn’t know you had to set other properties at the same time to get Created By or Author to stick? Neither did I, until now…

The Right Way

Maybe not the correct way, but the way I got it to work:

...
SPUser user = ...
SPListItem spListItem = ...
spListItem["Created By"] = user.ID;
spListItem["Modified By"] = spListItem["Modified By"];
spListItem["Modified"] = DateTime.Now;
spListItem.UpdateOverwriteVersion();
...

That’s right, to successfully save the Created By property you must also set the Modified By and Modified properties AND call SPListItem.UpdateOverwriteVersion() to get the Created By property to actually save your new value. Hopefully you find this post sooner than I found my answer.

Categories: Programming Tags: , ,

Creating an SSH Proxy Tunnel with PuTTY

March 15th, 2012 Comments off

This tutorial is aimed at Windows users and focuses on PuTTY as our SSH client of choice.

Are you stuck behind a firewall or looking to add some privacy to your browsing? Whenever I’m off my own network I fire up an SSH tunnel back to my own servers and send all my browsing information through it. Why? Because big brother may be watching, but I can bet you someone even worse is trying to. Also, it could be incriminating if people knew how often I was checking my 9th (out of 10) place Fantasy Football team stats.

What is Tunneling? The Over Simplified Definition

When your browser (or other client) requests a webpage (or anything off the Internet) it sends a request from your computer through a series of routers, switches, firewalls, and servers owned and monitored by other people, companies, and ISPs until it reaches its destination, then follows the same (or similar) path back to your machine with the kitten pictures you asked for.

Tunneling bypasses some of the rules that these companies or ISPs may be enforcing on you by creating a direct, encrypted, connection to your tunnel server that can’t be easily peered into by prying eyes. This means that web pages that are blocked can be seen and passwords that are sent can’t be looked at.

For a much better definition, please see Wikipedia

Install PuTTY

There are other SSH clients and tools that are designed specifically for SSH tunneling and SOCKS proxying. I prefer this way because PuTTY also gives you an SSH client, which you should no doubt be in possession of anyways.

  1. Download PuTTY here (choose the archive version)
  2. Make a new directory at C:\bin
  3. Extract the contents of the putty archive into C:\bin
  4. An extra step that’s not really necessary- Add C:\bin to your Windows system path (if you don’t know how, skip this or google it)

Configuring PuTTY

  1. Fire up the client and enter the hostname and portPuTTY Hostname
  2. Type in a title under Saved Sessions and press Save
  3. On the left side, go to Connection->SSH->Tunnels
  4. In Source Port enter 8080 (this can be configured to be whatever you want, just remember it)
  5. Choose the Dynamic radio button under DestinationPuTTY Tunnel
  6. Press Add, you should then see D8080 in the box above
  7. Go back to Session on the left side and then press Save to save the changes

SOCKS Proxy

To utilize the tunnel to its full benefit, you need to set up a SOCKS proxy in your browser. Will describe how to use the FoxyProxy proxy switching plugin. It works for both FireFox and Chrome on Windows, which are really the only browsers you should be using.

  1. Download FoxyProxy for your browser here.
  2. Once installed, go to the FoxyProxy optionsFoxy Proxy
  3. Click Add New
  4. Click the General tab and enter a name in the Proxy Name box
  5. Make sure Perform remote DNS lookups on hostnames loading through this proxy is checked – we’ll discuss this a little later
  6. Select the Proxy Details tab
  7. Enter localhost in the Host box
  8. Enter 8080 in the Port box
  9. Check SOCKS Proxy? and make sure the SOCKS v5 radio is checked
  10. Press Ok to save
  11. At the Select Mode drop down, choose your freshly created SOCKS Proxy

Conclusion

So long as your PuTTY SSH connection remains connected your proxy tunnel will be open and you will be browsing the internet just as you had before, except without a lot of restrictions placed by firewalls and greater security.

Final Note: Secure DNS Resolution

As far as I understand it Chrome will automatically use your SOCKS proxy for DNS resolution, but Firefox doesn’t by default. This means that firewalls or DNS servers could still block requests to certain websites because they will refuse to tell your browser or client how to look the remote server up. FoxyProxy should fix this due to the installation steps we took, but it doesn’t guarantee that your IM messenger, other browsers, or other internet clients will be able to securely resolve DNS requests when using the SOCKS proxy. For more information on exactly what DNS is, browse over to Wikipedia

I recommend a 3rd party DNS service like OpenDNS to further enhance the safety, speed, and security of your DNS lookups. They can protect from malware and other bad things, but they can also provide you with a ‘less restricted’ internet.

NSLog Conditionally in Debug Mode and NSLog Macros

March 6th, 2012 Comments off

Using Objective-C Macros to Conditionally Log

During the course of developing and debugging my first iOS apps I’ve realized that there has to be at least a semi-decent way of using log statements for debugging messages as well as error messages without a lot of code overhead and manual changes when switching between building for Release and Debug.

Using macros and compiler settings, you too can quickly separate the statements out and streamline your debugging/logging code.

Creating Your Macros

Find the -Prefix.pch header file for your project and open it for editing. If your project’s name is MyProject you will look for MyProject-Prefix.pch.

Add the following lines to the end of your Prefix header file:

// Macro wrapper for NSLog only if debug mode has been enabled
#ifdef MA_DEBUG
    #define AshDebugLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]);
#else
    // If debug mode hasn't been enabled, don't do anything when the macro is called
    #define AshDebugLog(...)
#endif 

// Log using the same parameters above but include the function name and source code line number in the log statement
#ifdef MA_DEBUG
    #define AshDebugLogDetailed(fmt, ...) NSLog((@"Func: %s, Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
    #define AshDebugLogDetailed(...)
#endif

// This macro will create a detailed log message and run even during a production build
#define AshDetailedLog(fmt, ...) NSLog((@"Func: %s, Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

What We Did

I have prefixed each macro with Ash so that there is no confusing them as macros I created. As you can also see, we have created a few different ways to log. We have a standard wrapper for NSLog that we will call instead of NSLog that will only fire if we’ve built using a debug mode flag. We also have two different methods for creating detailed log messages on the fly that will include our log message along with the function and line number the message originates from. The nice thing about these macros is that you can easily change the string format to log in any way that you want.

XCode Settings

  1. Select your project in the Xcode explorer/left pane

    XCode Project

    Xcode 4.2

     
  2. Select Build Settings in the Xcode center window
  3. Search for preprocessor in the Build Settings section and add DEBUGGING as a Debug Preprocessor Macro.

    Xcode Preprocessor Build Settings

    Set the Debug preprocessor settings

Becoming an iOS Developer

February 22nd, 2012 Comments off

I found a nice, straightforward post by Josh Smith about becoming an iOS developer with a background in other technology stacks. He did a great job laying out the basics; I’m not going to really re-hash it, but add my feelings on the matter.

As someone with a background in .NET and Java (among others) I can definitely feel where he’s coming from when he says:

I warn that it will take a considerable amount of time, effort, and patience to get over the learning curve. If you think that going from WinForms to WPF requires a major mental adjustment, you ain’t seen nothin’ yet.

He’s not lying! Through my years of application development experience I’ve become completely comfortable with the whole MVC pattern and many abstract concepts of ‘good’ application design. I’ve found that all (or at least a lot) still apply to the iOS development world, but the execution is so far different than what you’ve done on (probably) any platform that it’d almost be better starting from scratch. Almost… maybe.

I bounce between Visual Studio, Komodo IDE, and Eclipse every day for various languages and products. I use vim, Notepad++, and TextWrangler just about every day (I dual boot Win7 and OS X and bounce between both, all my servers are Linux). Getting used to yet another IDE seemed like a pain, but Xcode 3 was pretty okay. Nothing though, threw me for a loop like the upgrade from Xcode 3 to Xcode 4; with the introduction of segues, moving Interface Builder into the IDE, ARC, and a number of other things. I’m still finding new things every day. It’s a much better IDE than Xcode 3, yet still hasn’t got much in the way of going toe to toe with Visual Studio.

Apple expects developers to be smarter than Microsoft does. Microsoft works hard to ensure that programming technologies are usable by as broad a range of people as possible. Their tooling and documentation assume you aren’t quite sure what you’re doing. Apple, on the other hand, is not nearly as helpful and pandering.

Whether it is that Apple wants to weed out some of those VB6 types, or just assumes that you’ll figure it out- they certainly do a lot less pandering to the least common denominator.

Final Thought

I love developing for iOS. It is a pretty homogeneous environment, Objective C lets me flex some of those C muscles I haven’t flexed in years, I can pretty rapidly get test ideas and wireframes alive enough to experiment with, and it’s another feather in my cap.

If you’re just starting out, turn off ARC, get used to managing memory on your own, and prepare for a lot of initial frustration if you’re used to picking up languages as easy as I have.

Categories: Interesting Tags: ,