Archive for April, 2010

Step by Step Guide for Authenticating WCF Service with Username and Password over SSL

Here is a short step by step guide on how to get your WCF service to perform Message and Transport level security over SSL with user name and password. I ran into this recently and thought should document it along with source code to provide reference for the rest of us.

1. If your development machine is XP (or 2K3 server) and you need dev SSL cert installed on it, follow the instructions mentioned in the articles here. The SelfSSL makes it real easy to do self signed certificates, literally one statement.

Setting up SSL with a SelfSSL certificate on Windows Server 2003 (and XP)

Create a self-signed SSL certificate with IIS 6.0 Resource Kit SelfSSL

2. Create a WCF Service Project. Name the service and contracts appropriately. In my sample it is a simple contract like follows.

   [ServiceContract]
    public interface IWcfService
    {
        [OperationContract]
        string GetData(int value);
    }

Make sure you make the appropriate config changes matching with your service contract.

2. Add a custom validator class in your service. You can create a separate file for it. In this example I have added it to the main service file WcfService.svc.cs. You are going to need to add the reference (not just adding these lines at the top, go to add-reference and add the corresponding dll’s to the project)

using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;

and the custom validator code.

public class CustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName == "test" && password == "test")
                return;
            throw new SecurityTokenException(
                "Unknown Username or Password");
        }
    }

You probably want to make this user name and password moved to a more secure location or point to your database/authentication store for security and maintainability perspective.

3. Now the code part is done. Move to config file. Enable custom errors so you know details about the errors happening.

<customErrors mode=”Off” defaultRedirect=”GenericErrorPage.htm”>

4. Add a new bindings attribute in the config called SafeServiceConf which will specify the TransportWithMessageCredential type of security. You can add this right before </system.serviceModel>

<bindings>
<wsHttpBinding>
<binding name="SafeServiceConf" maxReceivedMessageSize="65536">
<readerQuotas maxStringContentLength="65536" maxArrayLength="65536"
maxBytesPerRead="65536" />
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<bindings>       <wsHttpBinding>          <binding name="SafeServiceConf" maxReceivedMessageSize="65536">             <readerQuotas maxStringContentLength="65536" maxArrayLength="65536"                maxBytesPerRead="65536" />             <security mode="TransportWithMessageCredential">                <message clientCredentialType="UserName" />             </security>          </binding>       </wsHttpBinding>    </bindings>

5. Modify your end point address to refer to this binding configuration

			<endpoint address="" binding="wsHttpBinding" contract="MySamples.IWcfService" bindingConfiguration="SafeServiceConf">

also modify your metadata exchange endpoint to use mexHttpsBinding

				<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

6. Modify your service behavior to look like this

				<behavior name="WcfService.Service1Behavior">
					<serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <userNameAuthentication
                 userNamePasswordValidationMode="Custom"
                 customUserNamePasswordValidatorType="MySamples.CustomValidator,WcfService"
                                                                          />

          </serviceCredentials>
        </behavior>

It’s recommended that “Include exception in faults” should be disabled when moved to production.

7. Now you are almost ready to run the service however before you do this, make sure that you are running it in the IIS AND you have the SSL enabled on the server as specified in step 1 otherwise you’ll run into WCF error stating that there is no HTTPS endpoint available.

Setup Virtual Directory in IIS from Visual Studio

Setup Virtual Directory in IIS from Visual Studio

You should be able to run and see the service end point as follows.

Running WCF Service over SSL

Running WCF Service over SSL

Running WCF Service over SSL 2

Running WCF Service over SSL 2

8. Now that the service is done, let’s move towards building the client. Add the service reference to the service end point. You can do it either via entering the entire URL or using the discover feature.

Add WCF Reference

Add WCF Reference

9. Name your reference “Client” or modify your code appropriately. Following is the code for client implementation.

       private static void Main(string[] args)
        {
           ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                delegate { return true; });

            var client = new WcfServiceClient();
            GetCredentials();
            client.ClientCredentials.UserName.UserName = username;
            client.ClientCredentials.UserName.Password = password;
            Console.Write(client.GetData(1));
            client.Close();
            Console.Read();
        }

The RemoteCertificateValidationCallback part is used to programatically avoid the following warning which would popup due to self signed cert usage.

Certificate Warning

Self signed Certificate Warning

10. Now run the program.

Running WCF client

Running WCF client

You can see that for the right credentials, service will run just fine. Otherwise a security exception will be thrown.

Source code can be downloaded from here.WCFAuthSample

Feel free to drop me an email or comment here if you have any questions.

References and Further Readings:

How to: Authenticate with a User Name and Password

WCF Service over HTTPS with custom username and password validator in IIS

Chapter 5 – Authentication, Authorization and Identities in WCF

How to: Use Transport Security and Message Credentials

SecurityMode Enumeration

WCF: Could not establish trust relationship for the SSL/TLS secure channel with authority

Deploying an Internet Information Services-Hosted WCF Service

How messages are encrypted when security mode is “Message”?

Simple WCF – X509 Certificate

Windows HTTP Services Certificate Configuration Tool (WinHttpCertCfg.exe)

Setting up SSL with a SelfSSL certificate on Windows Server 2003 (and XP)

Create a self-signed SSL certificate with IIS 6.0 Resource Kit SelfSSL

Share

The Fizz-Buzz Programming Test

A lot has been said about the FizzBuzz programming test used in interviews. It’s a decent litmus test measure of testing a few key capabilities in a developer i.e. (a) knowledge of programming constructs (iterations/conditionals) (b) algorithm / logic and (c) thinking process

The problem statement goes as follows.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”

Here are few scenarios how it may play out during interviews.

Scenario A.

Interviewer: States the problem statement.

Applicant: hmmm….How do I do multiples?

Interviewer: (grrrr.. Out!.) You’ll be hearing from our hiring manager. Nice meeting you.

Scenario B

Applicant: well, I think in the loop .. if (number * 3 = 5) print something

Interviewer: (Out!) You’ll be hearing from our hiring manager. Nice meeting you.

Scenario C

Applicant:     

for(int i=1; i<=100; i++)

{ if (i % 3 == 0)

{ Console.WriteLine("Fizz");

if (i % 5 == 0) Console.WriteLine("Buzz");

if (i % 3 == 0 && i % 5 == 0)

Console.WriteLine("FizzBuzz");

else

Console.WriteLine(i);}};

Interviewer: (well, I suppose you get points for trying but NO, it won’t work. Will print Fizz Buzz FizBuzz for 15.) You’ll be hearing from our hiring manager. Nice meeting you.

Scenario D

Applicant:      

for(int i=1; i<=100; i++)
{

if (i % 3 == 0 && i % 5 == 0)

Console.WriteLine("FizzBuzz!");

else if (i % 3 == 0) Console.WriteLine("Fizz");

else if (i % 5 == 0) Console.WriteLine("Buzz");

else Console.WriteLine(i);

}

Interviewer: It works! Cool.

Scenario E

Applicant:

for(int i=1; i<=100; i++)

Console.WriteLine( ((i%3 == 0 && i%5 == 0) ? "FizzBuzz" : ( (i % 3 == 0) ? "Fizz": (i % 5 == 0) ? "Buzz" : i.ToString())));

Interviewer: hmmm… terse and concise but readability / maintainability?

Hired / needs more review? Your thoughts?

Related:

Coding Horror: Why Can’t Programmers.. Program?

Scott Hanselman – You Can’t Teach Height – Measuring Programmer

Coding Horror: FizzBuzz: the Programmer’s Stairway to Heaven

Share

SGV.NET User Group Meeting – Learning Silverlight 4 w/ Volkan Uzun – Wed 4/21/2010

Abstract: Silverlight 4 enhances the building of business applications, media applications, and applications that reach beyond the browser. New features include printing support, significant enhancements for using forms over data, full support in the Google Chrome web browser, WCF RIA services, modular development with MEF, full support in Visual Studio 2010, bi-directional text, web camera and microphone support, rich text editing, improved data binding features, HTML support, MVVM and commanding support, new capabilities for local desktop integration running in the new “Trusted Application” mode such as COM automation and local file access.

While Silverlight turns into a mainstream RIA technology for enterprise level applications; this presentation will focus on and demonstrate a selected group of Silverlight 4 features to highlight its potential. The content will include useful pointers for further study and experimentation.
About the Speaker: Volkan is currently working at California State University as an Information Technology Consultant. He has a passion for creating accessible and secure applications and loves to share his knowledge with the developer community. He was the instructor for the IEDOTNETUG ASP.NET Web Forms class in 2008 and this year he taught teaching ASP.NET MVC. Volkan is holding a MS degree in Computer Science from California State University.
He has been developing softtware since 1999; former companies he worked for include Wincor-Nixdorf and Denizbank; where he was involved in systems engineering and programming. He is certified as MCTS on SQL Server 2005 and MCTS on ASP.NET Web development.
Read Volkan’s blog at http://www.msnetprogrammer.net/blog.

for further details, please check out the San Gabriel Valley .net user group website

Share

OWASP Top 10 FINAL 2010 – Web Application Security Risks

OWASP Top 10 Web Application Security Risks 2010 has been released today 4/19 as FINAL.

The OWASP Top 10 Web Application Security Risks for 2010 are:

  • A1: Injection
  • A2: Cross-Site Scripting (XSS)
  • A3: Broken Authentication and Session Management
  • A4: Insecure Direct Object References
  • A5: Cross-Site Request Forgery (CSRF)
  • A6: Security Misconfiguration
  • A7: Insecure Cryptographic Storage
  • A8: Failure to Restrict URL Access
  • A9: Insufficient Transport Layer Protection
  • A10: Unvalidated Redirects and Forwards

Click here to download the OWASP Top 10 – 2010

Share

Startups For the Rest of Us – A Podcast by Rob Walling

I wanted to pass along a bit of info about Rob Walling, the co-founder of San Gabriel Valley .NET Developers group newest project. a podcast!.

The podcast is called Startups for the Rest of Us. Rob’sco-host is Mike Taber, the guy behind SingleFounder.com.

The focus of the podcast is bootstrapped startups and Micropreneurs. A new episode every Tuesday. The first episode is live at the podcast website and you can listen to it in your browser or download the MP3. It also provide full written transcripts of each episode in the show notes. Episodes will be concise and run 20-30 minutes so you can listen during a jog, a short commute or part of a lunch hour.

Check it out if you’re the podcasting type:

If you listen and like it, find it in iTunes using the link above, rate it and post a comment.

Share

KDD 2010 Educational Data Mining Challenge

KDD data mining challenge has we have decided to push back the challenge start date to Monday, April 19 at 2pm EDT due to feedback on development datasets. They are trying to validate the challenge data sets and also have pushed back the competition end date to Tuesday, June 8 at 2pm EDT.

Following is the KDD Data Mining challenge details via the homepage https://pslcdatashop.web.cmu.edu/KDDCup/

This year’s challenge

How generally or narrowly do students learn? How quickly or slowly? Will the rate of improvement vary between students? What does it mean for one problem to be similar to another? It might depend on whether the knowledge required for one problem is the same as the knowledge required for another. But is it possible to infer the knowledge requirements of problems directly from student performance data, without human analysis of the tasks?

This year’s challenge asks you to predict student performance on mathematical problems from logs of student interaction with Intelligent Tutoring Systems. This task presents interesting technical challenges, has practical importance, and is scientifically interesting.

Read more

Task description

At the start of the competition, we will provide 5 data sets: 3 development data sets and 2 challenge data sets. Each of the data sets will be divided into a training portion and a test portion. Student performance labels will be withheld for the test portion of the challenge data sets but available for the development data sets. The competition task will be to develop a learning model based on the challenge and/or development data sets, use this algorithm to learn from the training portion of the challenge data sets, and then accurately predict student performance in the test sections. At the end of the competition, the actual winner will be determined based on their model’s performance on an unseen portion of the challenge test sets. We will only evaluate each team’s last submission of the challenge sets.

Read more

Share

OWASP and ISSA-LA Meetings

Topic: The intersection of social and technical attacks in Web 2.0 applications
Speakers: Mike Bailey and Mike Murray
OWASP April meeting is at 7:30PM on April 21st, at Symantec in Culver City. There will be pizza.

More info: http://www.owasp.org/index.php/Los_Angeles
RSVP: http://owaspla.eventbrite.com/

ISSA-LA also has monthly lunch meeting on April 21st.
http://www.issa-la.org/Default.aspx?id=1086

ISSA-LA is planning “2nd Annual Information Security Summit:
Unleashing The Power of Collaboration”. It is a full day conference on June 16th at UCLA.
http://www.issa-la.org/Default.aspx?id=1086

Last but not least, OWASP AppSec USA 2010 is from September 7-10 at UC
Irvine. Early registration will be open soon. Volunteers are still needed.
http://www.appsecUSA.org

via Tin Zaw.

Share

P=NP

These CMU guys did the poll on P=?NP and totally forgot to call me.
May be the letter is in the mail but I am going to go out on a limb here and stating that it’s going to be…wait for it

There, I said it! P=NP

Let’s go all Nostradamus here. I know I am in minority here but I strongly believe this will happen; time-frame would be before 2050 and the techniques will involve high-order multidimensional reduction with sieve plucking. The exact technique used is currently unknown in the field and it better not be a algebric-geometric proof.

In coming years (2010-2019) we will have an example when there will be a polynomial time solution of SAT without knowing its complexity. Then we will actually have a proof before 2050.
May be that’s what Knuth is going to talk about on June 30th, in his earthshaking announcement.

And hereby this sets a $0.01 bet premise with Jeff Bergman, adjusted to the inflation et al, who strongly considers P!=NP and he SHALL be proven wrong.

Ref:
SIGACT News Complexity Theory Column 36

Share

‘Eureka machine’ works out laws of nature | Science | guardian.co.uk

‘Eureka machine’ works out laws of nature | Science | guardian.co.uk.

We’ve reached a point in science where there’s a lot of data to deal with. It’s not Newton looking at an apple, or Galileo looking at heavenly bodies any more, it’s more complex than that,” said Hod Lipson, the computer engineer who led the project. …

Share

The cost of inaction

Seth Godin blogged couple of days ago titled “Failure, success and neither”

It was so well said that I am compelled to quote it hear with all due credits.

The math is magical: you can pile up lots of failures and still keep rolling, but you only need one juicy success to build a career.

The killer is the category called ‘neither’. If you spend your days avoiding failure by doing not much worth criticizing, you’ll never have a shot at success. Avoiding the thing that’s easy to survive keeps you from encountering the very thing you’re after.

And yet we market and work and connect and create as if just one failure might be the end of us.

Beautiful!

This is also very true for the cost of inaction in Entrepreneurship.

Share
Go to Top