Some Nerdy Stuff

February 2, 2010

Retrying on exception conditionally.

Filed under: Uncategorized — Tags: — aaronls @ 3:27 pm

This is a C# utility class I created for situations where you might receive an exception, perhaps from a failed network operation, and want to retry the operation.  You could use it in a variety of ways, maybe pausing between each exception, prompting the user to correct an issue or with a “Retry?” prompt.  The Example() method below shows usage of the class(you should delete the example method before trying to use this class in your own code).   Basically it is structured much like a try/catch block, the first delegate is the potentially error throwing code you want to try, and the second block handles the exception, deciding whether to retry again or give up, which is signaled by returning true to retry again or false to give up.  The class could be improved by changing this return value to an enum with a Retry.Continue and Retry.Cancel values, or maybe even changing the OnException to be an event with a ExceptionEventArgs class that has would allow the developer to do something like args.Cancel=true.

  public class RetryOnError
  {
      static void Example()
      {
        string endOfLineChar = Environment.NewLine;
        RetryOnError.RetryUntil<string>(delegate()
        {
            //attempt some potentially error throwing operations here

            //you can access local variables declared outside the the Retry block:
            return "some data after successful processing" + endOfLineChar;
        },
        new RetryOnError.OnException(delegate(ref Exception ex, ref bool rethrow)
        {
            //respond to the error and
            //do some analysis to determine if a retry should occur
            //perhaps prompting the user to correct a problem with a retry dialog
            bool shouldRetry = false;

            //maybe log error
            log4net.Error(ex);

            //maybe you want to wrap the Exception for some reason
            ex = new Exception("An unrecoverable failure occurred.", ex);
            rethrow = true;//maybe reset stack trace

            return shouldRetry;//stop retrying, normally done conditionally instead
        }));
      }

    /// <summary>
    /// A delegate that returns type T
    /// </summary>
    /// <typeparam name="T">The type to be returned.</typeparam>
    /// <returns></returns>
    public delegate T Func<T>();

    /// <summary>
    /// An exception handler that returns false if Exception should be propogated
    /// or true if it should be ignored.
    /// </summary>
    /// <returns>A indicater of whether an exception should be ignored(true) or propogated(false).</returns>
    public delegate bool OnException(ref Exception ex, ref bool rethrow);

    /// <summary>
    /// Repeatedly executes retryThis until it executes successfully with
    /// an exception, maxTries is reached, or onException returns false.
    /// If retryThis is succesful, then its return value is returned by RetryUntil.
    /// </summary>
    /// <typeparam name="T">The type returned by retryThis, and subsequently returned by RetryUntil</typeparam>
    /// <param name="retryThis">The delegate to be called until success or until break condition.</param>
    /// <param name="onException">Exception handler that can be implemented to perform logging,
    /// notify user, and indicates whether retrying should continue.  Return of true indicates
    /// ignore exception and continue execution, and false indicates break retrying and the
    /// exception will be propogated.</param>
    /// <param name="maxTries">Once retryThis has been called unsuccessfully <c>maxTries</c> times, then the exception is propagated.
    /// If maxTries is zero, then it will retry forever until success.
    /// </param>
    /// <returns>The value returned by retryThis on successful execution.</returns>
    public static T RetryUntil<T>(Func<T> retryThis, OnException onException, int maxTries)
    {
      //loop will run until either no exception occurs, or an exception is propogated(see catch block)
      int i = 0;
      while(true)
      {
        try
        {
          return retryThis();
        }
        catch ( Exception ex )
        {
          bool rethrow =false;//by default don't rethrow, just throw; to preserve stack trace
          if ( (i + 1) == maxTries )
          {//if on last try, propogate exception
            throw;
          }
          else if (onException(ref ex, ref rethrow))
          {
            if (maxTries != 0)
            {//if not infinite retries
              ++i;
            }
            continue;//ignore exception and continue
          }
          else
          {
            if (rethrow)
            {
              throw ex;//propogate exception
            }
            else
            {//else preserve stack trace
              throw;
            }
          }
        }
      }
    }

    /// <summary>
    /// Repeatedly executes retryThis until it executes successfully with
    /// an exception, or onException returns false.
    /// If retryThis is succesful, then its return value is returned by RetryUntil.
    /// This function will run infinitly until success or onException returns false.
    /// </summary>
    /// <typeparam name="T">The type returned by retryThis, and subsequently returned by RetryUntil</typeparam>
    /// <param name="retryThis">The delegate to be called until success or until break condition.</param>
    /// <param name="onException">Exception handler that can be implemented to perform logging,
    /// notify user, and indicates whether retrying should continue.  Return of true indicates
    /// ignore exception and continue execution, and false indicates break retrying and the
    /// exception will be propogated.</param>
    /// <returns></returns>
    public static T RetryUntil<T>(Func<T> retryThis, OnException onException)
    {
      return RetryUntil<T>(retryThis, onException, 0);
    }
  }

 

February 1, 2010

Are self-signed certificates with https less secure than http alone?

Filed under: Uncategorized — aaronls @ 8:27 am

I was hoping to find a way to use a self-signed certificate over https to prevent eaves dropping.  I do understand that this is vulnerable to man-in-the-middle attacks.  Unfortunately, browsers seem to view this as less secure than http, because they display many alarming warnings that a user must click through that otherwise are not present when accessing an http website.  This sends a clear message to the user that a site with a self-signed certificate is significantly less secure than a http website.  I would argue these warnings are unwarranted, and at a minimum, a self-signed certificate site over https should appear to be no less secure than a regular http website.

I suppose if you are on a network where someone has managed to spoof a major banks website and use a self signed certificate, you’d want lots of red flags to go up to alert users.  However, if they have been able to compromise the DNS or have one of their own on the network that traffic is using, allowing them to redirect requests for the bank’s website, then they are just as capable of leaving the user on an http connection(because most users don’t type the https in the URL and rely on a redirection from the website) logging the traffic, and performing the SSL handshake with the destination website.   Thus the user will get no warnings at all(other than the lack of subtle visual cues, but these are nothing compared to big red warnings boxes).  So I feel like the warnings present for self-signed certificates really only have the impact of adding a few more relatively simple(compared to how far they’ve already come to perpetrate the attack) steps for the hacker.  Therefore, I would say that the warnings presented for websites using self-signed certificates do not significantly reduce the scenarios in which a connection can be compromised.

As an example, let’s say I would like to setup a website that is a casual online game.  I will be collecting non-sensitive data, but I would like to at least eliminate scenarios where a malicious party could eaves drop on the connection and use that to steal the user’s account for the game.  With a self-signed certificate and SSL, I can at least provide protection against eaves dropping scenarios.

So, in conclusion, I would have hoped that a website that uses a self-signed certificate would raise no more red flags than a regular http website.  Let me make clear that I don’t expect them to get the “this website is secure” seal of approval and visual cues that you get for secure websites, but I strongly believe the alarming warnings are very inappropriate.

However, johnath feels the warnings are appropriate because there are point and click programs that can log encrypted traffic by spoofing self-signed certificates. I don’t see how this makes such a scenario warrant warnings when the same logging can occur over http.  I feel that if one applied the same logic to http connections, then you would be displaying the same alarming warnings.  Maybe you believe that your average user knows http: means that the site is alarmingly insecure, and therefore alarming warnings are unnecessary.  As johnath points out though, you can get free certificates from StartSSL.com that will not give you warnings in Firefox 3 because the root certificate is included.  I’m skeptical as to what the catch might be with these free certificates though, if there is a catch.

Create a free website or blog at WordPress.com.