Stat Tracker

Monday, January 24, 2011

SQL / SOQL Injection

This past weekend I was hanging out with some friends and we came up on the topic of SQL injection. Yeah, we are nerds. Anyway, I was giving my buddy a hard time because he wasn't parametizing his SQL statement in PHP. Really I didn't even dig in his code that much, just glanced at it and wanted to give him a hard time since I was stressed about the Bears game. And for good reason, since we lost! Ah, but its all in good fun!

Anyhoot, I've played around in a lot of languages, but not PHP. There was some minor back and forth about this as another buddy shared his thoughts. I stated that I've never seen any language or database that takes a query and automatically escapes it for you once you call it. The standard defense against SQL injection that I've always used, and most often seen implemented in production has been SQL parametrization.

My friend stated that in PHP you can call built in escape string function on the SQL string and it will take care of it for you.  (Note: You can't escape the whole query string, you have to escape each individual input field and then use those escaped string in the query string).

I stated that generally as a developer you want to prevent SQL injection by using parametrization or persistence frameworks if possible. This set off some discussions, and then the Bears game got started so the discussion kind of died as my heart rate ramped up for the (disappointing) game. However, during lunch today I decided to write up on the topic.

You can checkout the SQL Injection wikipedia entry here, parametrization is the first method recommended. Escaping strings is also mentioned as a solution for PHP, although the ability to forget to escape a field makes this method error prone and cumbersome. Another SQL Injection site here recommends using escape string methods only when necessary as it creates frail code.

In Java using straight JDBC drivers you usually use parametrization of the query AKA prepared statements. (Java noobs click here). Some persistence frameworks like Hibernate will take care of parametization for you by default, but are still vulnerable to additional injection attacks you need to guard against. If your a glutten for pain your probably an Adobe Flex developer, and you also parametrize the SQL query. Shiver. I'm not a fan of developing in Adobe Flex. I spent about 6 months working with it and decided it wasn't for me!

In Force.com, we use parametization by using the bind ( :varName) ability of SOQL in Apex. Per the Force.com Documenation, "To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. "

For example:

List<String> idList = new List<String>{'XXXXXXXXX','YYYYYYYYY','ZZZZZZZZZZZ'};
List<Account> accounts = [Select Id, Name from Account where Id in :idList];

You can escape the user input, per Force.com documentation "If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input.". But they strongly recommend parametrization of queries.

Furthermore, Salesforce and Apex developers should be using the Force.com Security Scanner to check their code base for security holes like SOQL injection. Using the scanner is very easy, all you need to do is provide your login address to the security scanner at http://security.force.com/sourcescanner. It will automatically generate a pretty sweet code analysis report in PDF format and email it to your email address associated with the login address. It also gives you the solution on how to re-factor your code to solve the hole, which saves you time researching the solution. Pretty slick!

Tuesday, January 18, 2011

Using Visual Flow in Salesforce Spring 11

NOTE: As of Spring 12 all Orgs will have Visual Flow for FREE! SWEET! Also, this post is a little old, there is already an update with the new Cloud Flow Designer.

You know what can be tedious to work with? Wizards. And I’m not talking about wizards like Gandolf who can shoot lighting and carry swords with a +10 mana regeneration rate.  I’m talking about wizards that navigate a user through a flow or decision making process. Many programming languages and platforms provide setup wizards in their IDE’s that allow you to create a wizard framework quickly. This frees the developer from manually creating all the framework code to build one. 

As of Salesforce Winter 11, this was something that was lacking in Salesforce and Force.com platform.

You’d have to manually create a bunch of Visualforce Pages and Apex Controller and flow the user through them manually, which was a pain!

In Spring 11 however, we are getting Visual  Flows GA (Generally Available). This was previously available in Pilot for Winter 11 release under the name “Visual Process Manager”. This allows you to build business processes quickly by drag, dropping, and connecting items in the Flow Designer tool. In my Spring 11 Release org I’ve been playing around with it and it’s pretty sweet. You can even invoke Apex methods from the flows for reusable / complex logic.

Use Case: New Account Wizard

This use case will create a new account using the Visual Flow tool. To create a Visual Flow, we need to do a few things first. 
  1. Gain access to a Salesforce Pre-Release Spring 11 Org. https://www.salesforce.com/form/signup/prerelease-spring11.jsp
  2. Enable the user as a “Force.com Flow user”. You can access this in Setup -> Manage Users -> Edit A user. Check the “Force.com Flow User” box.
  3. Download the Flow Designer tool from Developer Tools and install. You can access this in Setup -> Create -> Workflows & Approvals - > Flows. The download link is on the screen.
Once we have our environments setup and our user configured as a Flow user, we can create a flow. I recommend following the User Manual PDF provided in the Flow Designer tool to learn how to create a beginning flow (Help -> User Manual). It contains a pretty decent quick tutorial, but it’s a little lightweight. For example, the flow tutorial only provides a flow which does a calculation. It does not utilize the Lookup or Update elements which are critical to a lot of workflows. But it does introduce you to the concepts.

After following the tutorial, I updated my flow to use the Data Update element and the Send Email element to perform an Account insert as well as email me a confirmation email that the account was created. I am including my test flow file so you can use it in your org. 

You can grab the complete test flow file here: Google Code - TestFlow File.

When I finished, my flow looked like this in the Flow Editor:


To test this flow, I created a homepage component that linked to the flow allowing the user to execute it from their homepage. As you can see, the flow will execute in a new window and the user can go through the generated screens and create a new Account.

1. User clicks the Homepage Component to execute the wizard:
 2. Wizard starts up and user goes through the prompts to create the record.


And finally we can see the account record created in the Accounts Detail Page:

You can also embed these flows inside Visualforce Mashups so maybe I’ll play around with that next.

Overall, this is pretty exciting for developers and even administrators of Salesforce. I can see a lot of efficiency by building all sorts of custom wizards quickly using this tool. This will probably be heavily utilized in all those call center applications. 

Friday, January 14, 2011

Generating a Barcode in a Visualforce Page using Javascript

You can generate a barcode in a Visualforce Page using Javascript pretty easily. Some folks forget that you can execute Javascript in a Visualforce page. This opens you up to a lot of the goodies you can do with the client browser.

The trick is to find the right Javascript library which provides the type of barcode you want to generate, or you could always write your own.

At a highlevel, the steps you need to do are:

1. Upload a JS Library (someJSLib.js) to your Static Resources in Salesforce.
2. Reference the JS Library in your Visualforce page by using the <apex:includeScript> tag.
3. Execute the Javascript functions to generate the barcode content and display in your page.

For this example, I am using a Barcode 39 Javascript library provided by http://www.codeproject.com/KB/HTML/Code-39-Barcode.aspx.

1. First I upload the JS Library to my Static Resources:
  

2. After I have uploaded the library, I embed the JS file in my VF Page using the <apex:includeScript> tag:
<apex:includeScript value="{!$Resource.BarcodeScript}"/>

3. I execute javascript in the Visualforce page to generate the barcode (Full VF Page Code):
<apex:page standardController="Position__c">
    <apex:includeScript value="{!$Resource.BarcodeScript}"/>
    <apex:detail relatedList="false"></apex:detail>
    <br/>
    <br/>
    <div id="inputdata">{!Position__c.Name}</div>
    <div id="externalbox" style="width:5in"></div>
    <script type="text/javascript">
    /* <![CDATA[ */
      function get_object(id) {
      alert('Executed');
       var object = null;
       if (document.layers) {
        object = document.layers[id];
       } else if (document.all) {
        object = document.all[id];
       } else if (document.getElementById) {
        object = document.getElementById(id);
       }
       return object;
      }
      get_object("inputdata").innerHTML=DrawCode39Barcode(get_object("inputdata").innerHTML,1);
     /* ]]> */
    </script>
</apex:page>


4. When I view this page it will take the Name field from my Position__c object and encode it in the Barcode:

That's all it takes!

The only challenging part really is finding JS Libraries that are opensource and support your barcode format.

Here are some websites that have JS Libraries available:

EAN-13: http://www.parkscomputing.com/barcode.html
Barcode 39: http://www.codeproject.com/KB/HTML/Code-39-Barcode.aspx
Barcode 39: http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx