Language Enhancements in ColdFusion Splendor - Promoting built-in CF function to first class

April 15, 2014 / Awdhesh Kumar

A while ago I started a series of blog posts on Language Enhancements in ColdFusion Splendor and today, taking it forward, I am going to write about built-in ColdFusion functions being promoted to first class objects.

A first class object is the one which could be passed as an argument to a function call, assigned to a variable or returned as a result of a function invocation. So by promoting built-in functions to first class objects, you will be able to treat ColdFusion functions (structInsert, arrayLen, listFind) as objects and hence you can:

Here is a very simple example showing how you can pass built-in functions as an argument:

 <cfscript>
	function convertCaseForArray(Array array, function convertor)
	{
		for (var i=1; i <= arrayLen(array); i++){
        	array[i] = convertor(array[i]);
                }
		return array;
	}
       
     // lcase built-in function is being passed as callback.
	resultantArray = convertCaseForArray(['One', 'Two','Three'],  lcase);	
	writedump(resultantArray);
</cfscript>

In the above example, lcase built-in function is directly being passed as an argument to convertCaseForArray, which was not allowed till ColdFusion10. Now, let's see an example where the lcase and ucase built-in functions are being returned from the getConvertFunc function based on the type:

<cfscript>
	function convertCaseArray(Array array, String caseTo)
	{
		caseConvertFunc = getConvertFunc(caseTo);
		for (var i=1; i <= arrayLen(array); i++){
        	array[i] = caseConvertFunc(array[i]);
    	}
		return array;
	}
	
	function getConvertFunc(String caseType)
	{
	  if(caseType == 'lower')
	  	return lcase;
	   else
                return ucase;
	}
	
	resultantArray_lower = convertCaseArray(['One', 'Two','Three'], "lower");
	resultantArray_upper = convertCaseArray(['One', 'Two','Three'], "upper");
	
	writedump(resultantArray_lower);
	writedump(resultantArray_upper);

</cfscript>

In the above example, getConvertFunc returns the convertor for the right case. 

Stay tuned for more posts on language enhancements!


Slides of e-seminar - Everything about Mobile Application Development

April 11, 2014 / Ram Kulkarni

  Thunder | Adobe ColdFusion | Adobe ColdFusion Builder | e-seminar | Mobile | Splendor

I presented an e-seminar, Everything about Mobile Application Development, on 10th April. Some of the attendees had asked me to share the presentation and source code of the application. So here are the links

I had added a few useful links at the end of the presentation, but the PDF (linked above) of slides does not show those links. So here they are - 

Downloads

ColdFusion Documentation

CFMobile related Blogs

CFMobile related Videos

Recently PhoneGap Build made some changes in the way they pick up PhoneGap plugins. Because of this if you package the application (CFMobileExpenseTracker) using Public Beta builds, then image attachement feature would not work. We have fixed this issue post public beta. However there is a work around in public beta build- In the PhoneGap project properties of ColdFusion Thunder, select 'Load the configuration from XML' option and use this config.xml.




You can find the recording of this e-seminar here.

-Ram Kulkarni

Adobe ColdFusion Summit 2014

April 11, 2014 / Elishia

  Adobe ColdFusion | Adobe ColdFusion 10 | Announcements | CF Summit | ColdFusion | ColdFusion 11 | General

We are pleased to officially announce the next Adobe ColdFusion Summit to be held October 16th and 17th at Aria Resort & Casino, Las Vegas, Nevada.  It's going to be even better than last year and pricing remains very low at $299 early bird rate through July!

Read More


Language Enhancements in ColdFusion Splendor - Elvis operator

April 08, 2014 / Awdhesh Kumar

The Elvis operator (?:) is a small but elegant feature added in Splendor. I am going to show you how it shortens your conditional code and  makes it look simpler. But before I get into the details, here is the list of language features added in ColdFusion Splendor.

The Elvis operator assigns the ‘right default’ for a variable or an expression. In an expression, if the resultant value is not defined, then the object will be assigned to the left most part of the expression otherwise a default value (define at the right most part) will be assigned.

Consider a conditional case where the displayname is populated with username variable, if the later is defined otherwise a default value "anonymous" needs to be assigned to the displayname variable. The code snippet shown below display both the syntaxes: one with Elvis operator and other without it:
 
Without Elvis
<cfscript>
   if(isdefined('username')){
       displayName = username;
   }
   else {
    displayName = "anonymous";
   }
</cfscript>

With Elvis operator

   displayName = username ?: "anonymous";

The support for Elvis operator has been provided for function calls and expressions too. Some of the expression cases are: 

 securityNumber = securityStruct[‘Joe’] ?: -1;  // Retrieving from a struct
 colourCode = colourArray[index] ?: "black";   // Retrieving from an array
 employeeName = getEmployeeName(ID) ?: “Joe”;  // A function call

Security Enhancements in ColdFusion Splendor - PBKDF2 and AntiSamy

April 07, 2014 / Pavankumar

  Security | ColdFusion 11 | Splendor | web application security

ColdFusion 11 added few more security functions to the rich set of coldfusion security functions. Some of them includes protection against XSS using AntiSamy framework, PBKDF2 key derivation etc. In this blog post we will introduce you to the Antisamy and PBKDF2 key derivation functions added in coldfusion Splendor.

AntiSamy Support:

If there is a need to accept HTML/CSS input from the user then there is high possibility that the input containing XSS. In this case We can not use encoding functions as the HTML/CSS as the input need to be rendered by the browser. AntiSamy API provides an input validation technique which helps programmer to verify user-driven HTML/CSS input markup using a whitelist policy to ensure the input does not contain XSS. Antisamy validates using a policy file in which we can specify which HTML tags, attributes, css properties are allowed in the given input. The policy gives us more control on input validation/sanitization by providing directives,  regular expressions, rules for htmt tags and css properties . AntiSamy provides some example policy files which can be downloaded from here. They can be modified to suit your own project requirements. Check AntiSamy developer guide to know more about policy files.

Two new functions isSafeHTML and getSafeHTML were added which validates and cleans the given unsafe html as per the given policy.

isSafeHTML can be used to know whether the given input markup is in accordance with the rules specified in the antisamy policy. Returns true if valid else false if any violations are found.

getSafeHTML sanitizes the given input based on the the rules specified in an antisamy policy file. Returns cleanHTML string by cleaning the input against the defined policy.

The function syntax as below:

getSafeHTML(input [, PolicyFile ], throwOnError])
isSafeHTML(input [, PolicyFile ])
where

input      The HTML input markup text to sanitize/validate.

PolicyFile (Optional)      Specify the path to the AntiSamy policy file. Given path can be an absolute path or a relative to the Application.cfc/cfc.Given path can be an absolute path or a relative to the Application.cfc/cfc.In case if not specified, there is a provision to set this at application level. Else the default policy file shipped with ColdFusion will be used. Default policy antisamybasic.xml can be found in the lib directory.

throwOnError (Optional)       If set to true and given input violates the allowed HTML rules specified in the policy file an exception will be thrown. The exception message contains the list of violations raised because of the input. If set to false ignores the exception returns the HTML content filtered, cleaned according to the policy rules. Defaults to false.

Policy file can be set at application level using the key this.security.antisamypolicy in Application.cfc. The value must be an absolute path to the policy file or relative to the Application.cfc/cfm.

<cfcomponent>
<cfset this.security.antisamypolicy = "antisamy.xml">
</cfcomponent>

Here is a simple example which uses antisamy-tinymce.xml policy which allows many text formatting tags ,simple css properties and disallows javascript.

<!--- I am just using static input in this example when using this replace it with the relevant form parameter --->
<cfset unsafeHTML = "<script>alert('lorem ipsum lorem ipsum');</script><b>lorem ipsum lorem ipsum</b>">
<cfset isSafe = isSafeHTML(unsafeHTML)>
<cfset SafeHTML = getSafeHTML(unsafeHTML , "", false)>
 
<!--- returns No and provides the clean html as <b>lorem ipsum lorem ipsum</b> removes script from input  --->
<cfoutput> is Safe : #isSafe# Safe HTML : #SafeHTML# </cfoutput>
<cftry>
    <cfset SafeHTML = getSafeHTML(unsafeHTML , "", true)>
<cfcatch type="Application">
<!--- if throwOnError is true get the erros as specified below --->
<cfoutput>
    Errors in the input: <br/> #cfcatch.detail#
</cfoutput>
</cfcatch>
</cftry>

More detailed information and examples on antisamy can be found from here.

PBKDF2 Key Derivation:

PBKDF2 (Password based key derivation function) is a key derivation function which can be used to derive a cryptographic random key of desired key size from the humany-manageable passwords. PBKDF2 is widely used for generating random cryptography keys which can be used as key to encryption and HMAC algorithms. The function syntax as below

GeneratePBKDFKey(algorithm, inputString, salt, iterations, keysize)

algorithm
The encryption algorithm used to generate the encryption key. Supported algorithms are PBKDF2WithHmacSHA1, PBKDF2WithSHA1, PBKDF2WithSHA224,  PBKDF2WithSHA256,PBKDF2WithSHA384, PBKDF2WithSHA512.

inputString
Specify the input string (password/pass-phrase) which will be used for deriving the encryption key.

salt
Random cryptographic salt. Recommended length is 64 bits (8 characters) and must be randomly generated using a pseudo random number generator.

iterations
Desired Number of Iterations to perform the cryptographic operation. The minimum recommended number of iterations is 1000.

keySize
Desired arbitrary key length size in bits.

Below example shows how to derive a 192 bit encryption key from the given password. Then we are using key to encrypt and decrypt the data using AES algorithm. No need to store the encryption key as it will be derived from the password.

salt="A41n9t0Q";
        <!--- hard coding the password but in real password should be from some form parameter ---> 
	password = "Password@123";
	PBKDFalgorithm = "PBKDF2WithSHA224";
	dataToEncrypt= "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
	encryptionAlgorithm = "AES";
	derivedKey = GeneratePBKDFKey(PBKDFalgorithm ,password ,salt,4096,192);
	writeOutput("Generated PBKDFKey (Base 64) : " & derivedKey);
	encryptedData = encrypt(dataToEncrypt, derivedKey, encryptionAlgorithm, "BASE64");
	writeoutput("Data After Encryption: " & encryptedData);

        
	salt="A41n9t0Q";
	password = "Password@123";
	PBEalgorithm = "PBKDF2WithSHA224";
	derivedKey = GeneratePBKDFKey(PBKDFalgorithm ,password ,salt,4096,192);
	decryptedData = decrypt(encryptedData, derivedKey, encryptionAlgorithm, "BASE64");
	writeoutput("Data After Decryption: " & decryptedData);


More information and examples on PBKDF2 can be found from here.


Blue Mango Theme Design By Mark Aplet

Super Powered by Mango Blog