Tuesday, August 12, 2014

Is everything in WCS v7 is BOD???? ................ BOD vs SOI !!!

SOI and BOD service modules

SOI and BOD service modules are both used in the WebSphere Commerce Web 2.0 store, and the Management Center.
The following table shows which service module is used by different parts of WebSphere Commerce.

SOI
BOD
Presentation layer
WebSphere Commerce Struts framework
Business logic layer
Get design pattern
Process design pattern
Change design pattern
Sync design pattern
Persistence layer
Error handling

WebSphere Commerce service module types by component

Service module
Store services (Web 2.0 store)
Authoring services (Management Center)
Catalog
SOI
BOD
Marketing
BOD
BOD
Promotion
SOI
BOD
Order
SOI
SOI
Member
SOI
SOI
Infrastructure
SOI
SOI
Price
SOI
SOI
Contract
SOI
SOI
Note: Only services using the Business Object Document (BOD) programming model can use the JDBCQueryService class.


Wednesday, May 14, 2014

Some Important Links,Troubleshooting and reference points for Config files


Make Development little bit easy, By pass ACP !!

DISABLE ACCESS CONTROL CHECK WHILE DEVELOPMENT PERIOD 

Go to  wc-server.xml
follow below screen  or find BootstarpMulti in wc-server and add ' AccessControlUnitTest="true" ' before this tag.
Restart the server and you will be able to run the command and there will be no access check. In some case you will see message in console saying User is not authorize to run this command but we can ignore this, it is just a message, but the command will run.


Important Links

Managment center (CMC) 
https://localhost:8000/lobtools - wcsadmin/wcsadmin
Accelerator   
https://localhost:8000/webapp/wcs/tools/servlet/ToolsLogon?XMLFile=common.mcLogon&storeId=0 
Admin Console

https://localhost:8002/webapp/wcs/admin/servlet/ToolsLogon?XMLFile=adminconsole.AdminConsoleLogon&storeId=0Org Admin Console 
https://localhost:8004/webapp/wcs/orgadmin/servlet/ToolsLogon?XMLFile=buyerconsole.BuyAdminConsoleLogon&storeId=0

Dynacache

https://localhost:9043/cachemonitor/ 
WasAdminConsole 

https://hostname:9043/ibm/console

Config Files 

WC config 
[Toolkit Folder]/xml/config/wc-server.xml

Promotion Engine Configuration
[Toolkit Folder]/xml/PromotionEngineConfiguration/WCSPromotionEngineConfig.xml 

Folders 

Log Files
[Toolkit folder]/wasprofile/logs/server1/*.log

Temp folder
[Toolkit folder]/wasprofile/temp 

Changing DB 
 
Go to WCTK\bin
Execute the following command -

setdbtype oracle C:\oracle\product\10.2.0\db_1 <ServiceName> <DBAName> <DBAPwd> <DBUserID> <DBUserPwd> <DBHost> <DBServerPort>

Troubleshooting

CONFLICT ON PORT 8880, WHILE STARTING WAS SERVER

This happens when there are other application which is also using the port 8880. So to resolve the issue, we need to find which application is using the port 8880 through 'netstat' command in command prompt or update our WAS server to not use 8880.

We can update the WAS server through these steps:

1) Shut down WAS.

2) Browse to or search for the serverIndex.xml, for example, at "C:\WAS\AppServer\config\yourNode\nodes\yourNode\serverindex.xml"

3) Open the file and locate the following lines:
              endPointName="SOAP_CONNECTOR_ADDRESS">

4) Change "port 8880" to an available port

5) Save the serverindex.xml and restart WAS

We Might get these TCP error, port 80 nad 443 already in use and TCP_2 initialization failed
The socket bind failed for host * and port 80. The port may already be in use.
The socket bind failed for host * and port 443. The port may already be in use.
_______________
Sometimes we are getting the above errors in console and application won't work properly.
Reasons for the error : 
  a) It clearly says port 80 and 443 is already used by some other application.
  b) or the virtual host configuration in commerce server may be not functioning properly.
Soln :
  We can follow the below link of info center  'http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.developer.doc/refs/rdetbde.htm'  or run 'netstat-aon'  to check which application is suing the port 80,
  most of the cases 'skype' is using the poty 80 and 443 which causes issue, either kill skype or check skype   to uncheck the common property which uses port 80 and 443.

  sometimes vmware application if installed, it uses port 443.
  and sometimes system PID 4 is usng the port 80, to fix this, go to Device Manager -- > Non-plug and Play   Driver --> http and disable this and reboot the system.


Enabling Traces  

Tracing log into wasconsole 
Right click on the server -> goto admin console
Upon logging in go to  Servers  -> Application Servers
Click Server 1 
Click "Logging and Tracing" under Troubleshooting.
Click "Change Log Detail Level"
Enter the following and click Ok.

*=info:enable.trace.log.*=all:
com.ibm.websphere.commerce.WC_USER=all:
com.ibm.websphere.commerce.WC_SERVER=all:
com.ibm.websphere.commerce.WC_ACCESSCONTROL=all


Tracing SQL logs into wasconsole 
Follow the above steps and add following 
*=info: com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement=all 

EJB Tracing 
*=info:EJBContainer=all:PMGR=all.

Promotion Engine Tracing
Go to folder WCTK -> xml -> PromotionEngineConfiguration
Open WCSPromotionEngineConfig.xml 

Set <Debug>true</Debug>

Enabling CMC ( open laszlo logs ) 
Right-click LOBTools and click Properties. Select OpenLaszlo Settings.
Click Enable the debug console check box. Click Apply.


Important SQLs

Roles of user
select u.logonid,r.name,org.orgentityname from mbrrole mbr, userreg u,orgentity org,role r where mbr.member_id=u.users_id and org.orgentity_id=mbr.orgentity_id
and mbr.role_id=r.role_id
and u.logonid ='wcsadmin';

1) RESET THE PASSWORD FOR BUSINESS TOOLS 
(Commerce Accelerator, Administration Console ......... )

Run the below query, this will reset the password to initial password wcsadmin.
             update userreg set logonpassword = x'74434f61354f51593862415655304d5268424e54723865685653356151374a2b353163506c4261363730633d202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020' where logonid='wcsadmin';
             update userreg set salt = 'hsdbacehyoyn' where logonid='wcsadmin'; 
             update userreg set status = 1 where logonid='wcsadmin'; 
             update userreg set passwordexpired = 1 where logonid='wcsadmin';


Start Dev Environment
startWCToolkit.bat in [Toolkit Folder]\bin 

IBM WCS tips file
[Toolkit Folder]\hintsandtips.html

Friday, April 25, 2014

Landing pages defined for given Search term

Specify landing pages for search terms in WCS FEP2+

From FEP2+ IBM provides a feature in management center where the user can specify specific landing pages for certain keywords entered. For example,

search term                                             landing page
help                                                         HelpContactUsView

My requirement was to technically display the same view (ContentDisplayView) but with different parameters based on different search terms like for search term "Terms and Conditions" it should be ContentDisplayView?emsName=xxx where as for "privacy policy" it should be 
ContentDisplayView?emsName=yyy 

I tried to configure a relative path by passing in the parameters but it doesn't work. And then I figured out that the landing page can be an absolute URL with url query parameters like shown below


For example, instead of ContentDisplayView as the landing page, you can have http://hostname/webapp/wcs/stores/servlet/ContentDisplayView?storeId=nnn&catalogId=xxx&emsName=zzz

This solves my requirement of associating the same landing page with different search terms and different URL parameters.
reference
http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/index.jsp?topic=%2Fcom.ibm.commerce.developer.doc%2Fconcepts%2Fcsdsearchindexschema.htm

Wednesday, April 23, 2014

Snapshot of high level concepts of Oracle DB for WCS Commerce Developer

Commerce Developer : Working with ORACLE

As a commerce developer working with Oracle back end, it is very important to have good understanding of SQL.

I am not a DBA, but the way I have learned was to started with basic Insert/Update/Delete, Select commands and using group by, order by
but progressively learned some handy SQL commands.

Refresh local schema for development.
I would use the script below for creating tablespace/schema/assign grants and import schema. Replace wcsatdev with the schema name of your choice.

drop tablespace atdata including contents and datafiles;
drop tablespace atindx including contents and datafiles;

create tablespace atdata
datafile 'C:\oracle\product\ORCL10G\atdata_01.dbf' size 250m reuse autoextend on;

create tablespace atindx
datafile 'C:\oracle\product\ORCL10G\atindx_01.dbf' size 250m reuse autoextend on;

drop user wcsatdev cascade;

create user wcsatdev identified by wcsatdev
default tablespace atdata
temporary tablespace temp
quota unlimited on atdata
quota unlimited on atindx;

grant connect,resource,create materialized view to wcsatdev;

grant create view to wcsatdev;

grant create synonym to wcsatdev;

create or replace directory dpdumpdir as 'C:\projects\db';

create or replace directory dplogdir as 'C:\projects\db';

GRANT READ, WRITE ON DIRECTORY DPDUMPDIR TO wcsatdev;

GRANT READ, WRITE ON DIRECTORY DPLOGDIR TO wcsatdev;

Using data pump in Oracle 10g, faster way to import.
impdp system/oracle@orcl10g dumpfile=DPDUMPDIR:export.dmp logfile=DPLOGDIR:from_wcsatdev_10g.log REMAP_SCHEMA=from_schema:to_schema PARALLEL=8 CONTENT=ALL



When ever you have a larger database on your local database, it is a good idea to run DB stats once in a while to improve performance.

exec dbms_stats.GATHER_SCHEMA_STATS(ownname=>'WCSATDEV',estimate_percent=>dbms_stats.auto_sample_size, CASCADE=>TRUE, DEGREE=>4)

Where degree will invoke the 4 parallel slaves, cascade is required for indexes.

Size of the Tables: Run this command in the schema

select SEGMENT_NAME,sum(BYTES)/(1024) size_in_kil from user_extents where segment_type='TABLE' group by SEGMENT_NAME order by size_in_kil desc;


Dropping Stage prop Triggers: Stage prop is a completely new discussion but on my local I run this for better performance.

set pages 0 lines 100 ;
spool drop_trigger1.sql ;
select 'drop trigger '||trigger_name||' ;' from user_triggers where trigger_name like '%STG_%' or trigger_name = 'STGLOG_STGRESERVED1' ;
spool off;
@drop_trigger1.sql;



Issues and Fixes:

java.sql.SQLException: ORA-01000: maximum open cursors exceeded

check for this. select count(*) from v$open_cursor;

Login with system previleges and type show parameter OPEN_CURSOR

Alter cursors
ALTER SYSTEM SET OPEN_CURSORS=4000 SCOPE=BOTH;

Soln: restart DB


Error: ORA-12514: TNS: listener does not currently know of service requested in connect descriptor.

I made these changes and since then i did not see the problem.
ORACLE_HOME\network\admin\listener.ora, Please look for HOST and change that to
HOST=Windows hostname
ORACLE_HOME\network\admin\tnsnames.ora
For the 10g local instance tnsentry: give localhost instead of the windows hostname
HOST=localhost


Sources: Raj Sangavi

Extending OOB framework for frontned error handling !!

Out of the box these 2 are good Articles:

http://publib.boulder.ibm.com/infocenter/wchelp/v6r0m0/topic/com.ibm.commerce.developer.doc/concepts/csdcommanderror.htm

http://publib.boulder.ibm.com/infocenter/wchelp/v6r0m0/topic/com.ibm.commerce.developer.doc/concepts/csdjsperror.htm

Essentially there are following elements:
1. ECSystemException and ECApplicationException classes, that are used to throw exceptions from inside the controller.
2. Extending the ECMessage and ECMessageKey
3. The errors are intercepted by the ExtStoreErrorDataBean and mapped to resource bundles
4. Errors are displayed in JSP.

Define the property in ExtMessages_en_CA.properties (
_ERR_RESTRICTED_PROD = This item is restricted for delivery.


Extending ECMessage and ECMessageKey:

public interface EXTMessageKey extends ECMessageKey{
public static final String _ERR_RESTRICTED_PROD = "_ERR_RESTRICTED_PROD";

public static final String _ERR_MAX_NUM_OF_OF_CARTS_REACHED = "_ERR_MAX_NUM_OF_OF_CARTS_REACHED";

}

public class EXTMessage extends ECMessage{
//this file structure needs to be created inside toolkit properties folder
for com/ext/common/messages/EXTMessages.propertie

public final static String EXT_MESSAGES_RESOURCE_BUNDLE = "com.ext.common.messages.EXTMessages";

// final constants
public static final int USER = ECMessageType.USER;
public static final int SYSTEM = ECMessageType.SYSTEM;

// message severities
public static final long ERROR = ECMessageSeverity.ERROR;
public static final long WARNING = ECMessageSeverity.WARNING;
public static final long STATUS = ECMessageSeverity.STATUS;
public static final long INFO = ECMessageSeverity.INFO;

public EXTMessage(long msgSeverity, int msgType, String msgKey)
{
super(msgSeverity, msgType, msgKey, EXT_MESSAGES_RESOURCE_BUNDLE);
}

//system
public static final EXTMessage _ERR_MAX_NUM_OF_OF_CARTS_REACHED = new EXTMessage(ERROR, SYSTEM, EXTMessageKey._ERR_MAX_NUM_OF_OF_CARTS_REACHED);

public static final EXTMessage _ERR_PROCESSING_REQUEST = new EXTMessage(ERROR, SYSTEM, EXTMessageKey._ERR_PROCESSING_REQUEST);

//user
public static final EXTMessage _ERR_LOGIDPWDPSID_NOT_PRESENT = new EXTMessage(ERROR, USER, EXTMessageKey._ERR_LOGIDPWDPSID_NOT_PRESENT);

public static final EXTMessage _ERR_RESTRICTED_PROD = new EXTMessage(ERROR, USER, EXTMessageKey._ERR_RESTRICTED_PROD);
}


In the controller command, The error needs to be thrown as an exception for example:

throw new ExtendedApplicationException( EXTMessage._ERR_RESTRICTED_PROD,
CLASSNAME,
METHOD_NAME,
ORDER_SHOP_CART_VIEW,
true);

Developer overview on Access Control Policies !!

There are 2 levels of access controls provided for WebSphere Commerce.
1. WAS protects EJB's and Servlets.
2. WebSphere Commerce provides low level fine grained access control  framework based on access control policies to various types of users (registered/guest/customer service rep/sales managers).
and
3. It is always recommended to guard a WebSphere Commerce Server is always by a Firewall that will help internet clients from not being able to directly access resource in WebSphere Commerce.

WebSphere Application Server layer security and access control: 

1. Servlets and EJB's are configured to be invoked only by a chosen identity through declarative security and hence during EJB creation, we select use identity of EJB server and using identity of EJB server field ensures that all EJB beans run under the same identity for security.
2. WAS provides multiple security features such as 1. Global Security. 2. security domains can be configured with different scope 3. WAS utilizes SSL for secure connection between client and server and hence any third party integration's requires certificates to be installed. 4. In cases where standard authentication is not sufficient, WAS supports JAAS for higher level of security.

WebSphere Commerce Access Control Framework: Authorization model

Info center provides a good read on users/actions/resources//relationships but i am going to start with the practical case. There are always cases when we need to implement a custom access policy but most of the times, when adding access control in *ACP.xml. There are 2 levels of access control
  •    Command Level access control
  •    Resource Level access control
"Access control policies are enforced by the access control Policy Manager. 
In general, when a user attempts to access a protected resource, the access control policy manager first determines what access control policies are applicable for that user 
and then, based upon the applicable access control policies, it determines if the user is allowed to perform the requested operation on the given resource".

Most developers need to get the basic view and command level entries right, which is explained below and only on few times, would get an opportunity to implement custom access policy.


1. We create actions for views and commands
<Action Name="ABCItemExtView" CommandName="ABCItemExtView" />
<Action Name="ABCSyncPersonControllerCmd" CommandName="ABCSyncPersonControllerCmd" />
<Action Name="com.custom.soi.member.commands.ABCSyncPersonControllerCmd" CommandName="com.custom.soi.member.commands.ABCSyncPersonControllerCmd"></Action>
2. Assign actions to action groups as ActionGroupAction for views 
E.g. action groups
<ActionGroup Name="ProductManagersViews" OwnerID="RootOrganization">
<ActionGroup Name="AllSiteUsersViews" OwnerID="RootOrganization">
<ActionGroup Name="RegisteredUserViews" OwnerID="RootOrganization">
<ActionGroup Name="CustomerServiceRepresentativeViews" OwnerID="RootOrganization">
Assignment example:
<ActionGroup Name="ProductManagersViews" OwnerID="RootOrganization">
      <ActionGroupAction Name="ABCItemExtView"/>
     </ActionGroup>

<ActionGroup Name="RegisteredUserViews" OwnerID="RootOrganization">
       <ActionGroupAction Name="ABCSyncPersonControllerCmd" />
</ActionGroup&gt

3. Creating resource categories for commands
ResourceBeanClass="com.custom.soi.member.commands.ABCSyncPersonControllerCmd">

4. Assigning resource category to resource groups for commands as ResourceGroupResource

e.g. Resource groups
<ResourceGroup Name="AllSiteUserCmdResourceGroup" OwnerID="RootOrganization">
<ResourceGroup Name="CustomerServiceRepCmdResourceGroup" OwnerID="RootOrganization">
<ResourceGroup Name="RegisteredUserCmdResourceGroup" OwnerID="RootOrganization">

<ResourceGroup Name="BecomeUserCmdsResourceGroup" OwnerID="RootOrganization">
Assignment example:
<ResourceGroup Name="AllSiteUserCmdResourceGroup" OwnerID="RootOrganization">
<ResourceGroupResource Name="com.custom.soi.member.commands.ABCSyncPersonControllerCmdResourceCategory" />
</ResourceGroup>

Run acpload or in V7, dataloader will take care of it as it would internally run the ACPLoad
CMD:
select * from acresgrp where acresgrp_id in
(
select acresgrp_id from acresgpres where acrescgry_id =
(select acrescgry_id from acrescgry where resclassname like '%ABCSyncPersonControllerCmd%')
)

VIEWS:
select * from acpolicy where acactgrp_id in (select acactgrp_id
from acactactgp where acaction_id
in (select ACACTION_ID from ACACTION where ACTION = 'ABCItemExtView'))

select groupname from ACACTACTGP a, ACACTGRP b where acaction_id = (select acaction_id from ACACTION where action like '%ABCItemExtView%')
and a.acactgrp_id = b.acactgrp_id


Reference:
http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/index.jsp?topic=/com.ibm.commerce.data.doc/refs/rdmattrdict.htm

Acronyms:
WAS: WebSphere Application Server
SSL : Secure Socket Layer
JAAS: Java Authenticating and Authorization services

Optimistic locking implementation in Websphere Commerce (WCS)

Optimistic locking implementation in EJB

If you are using EJB's in WCS and optimistic locking avoids database deadlocks and helps lower locks placed on the database and allows more applications to run concurrently against the database.Optimistic locking is implemented by creating OPTCOUNTER column for each table.

1) Add OPTCOUNTER column in the table and optCounter CMP field with unchecked getter\setter methods option in creating new field in CMP bean.
2) Map the table OPTCOUNTER to the optCounter field as a CMP managed field, I see this step missing for all EJB's currently implemented so I did not add optCounter mapping either for the new EJB.
3) Adding this.initializeOptCounter(new XCustomKey(this.customId))  in ejbCreate method()
4) Adding optimistic locking in DeploymentDescriptor --> Bean tab, by checking the Concurrency Control (Enable Optimistic locking)
 5) Adding triggers for optCounter and also a file to add these.

CREATE or REPLACE TRIGGER perf_xcustom_1 before update ON XCUSTOM for each row
WHEN ((new.optcounter is null) or (new.optcounter = old.optcounter))
begin if (:old.optcounter < 32767) then :new.optcounter := :old.optcounter + 1; else :new.optcounter := 1; end if; END;

From Infocenter explanation for implementing trigger:
For optimistic locking to work properly, every query that updates a database table row must increment the OPTCOUNTER column value, or reset it to 1 when the current value is 32767. The WebSphere Commerce server uses this technique. However, if database table rows are updated by other code or manual procedures that do not update the OPTCOUNTER column values, then the database triggers defined in the WC_installdir/schema/db_type/wcs.perf.trigger.sql (where db_type is the database type (DB2, Oracle)) schema files ensure that the OPTCOUNTER column values are incremented properly.

Reference:
http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.admin.doc/concepts/cpmoptlock.htm

Integrating BING MAPS (NOT google maps) with WCS v7

Bing provides an interesting to alternative to Google maps for integration and if you want to integrate using Jquery. Please copy paste the example in a .html file and test it with a zip-code or city.

The key that I have in the example below will expire in 90 days so please use the below link to create a new key:
http://www.microsoft.com/maps/

Copy the below section after this line in a .html  file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Use Bing Maps REST Services with jQuery to build an autocomplete box and find a location dynamically</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .ui-autocomplete-loading
        {
            background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
        }
        #searchBox
        {
            width: 25em;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#searchBox").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "http://dev.virtualearth.net/REST/v1/Locations",
                        dataType: "jsonp",
                        data: {
                            key: "AlJKmxkiJg2u0CIDEyaTM6CWC9jQ_q1pf4_xzxPdEJoaT_KsgKRy73ksHyl24oe5",
                            q: request.term
                        },
                        jsonp: "jsonp",
                        success: function (data) {
                            var result = data.resourceSets[0];
                            if (result) {
                                if (result.estimatedTotal > 0) {
                                    response($.map(result.resources, function (item) {
                                        return {
                                            data: item,
                                            label: item.name + ' (' + item.address.countryRegion + ')',
                                            value: item.name
                                        }
                                    }));
                                }
                            }
                        }
                    });
                },
                minLength: 1,
                change: function (event, ui) {
                    if (!ui.item)
                        $("#searchBox").val('');
                },
                select: function (event, ui) {
                    displaySelectedItem(ui.item.data);
                }
            });
        });

        function displaySelectedItem(item) {
            $("#searchResult").empty().append('Result: ' + item.name).append(' (Latitude: ' + item.point.coordinates[0] + ' Longitude: ' + item.point.coordinates[1] + ')');
        }
    </script>
</head>
<body>
    <div>
        <div class="ui-widget">
            <label for="searchBox">
                Search:
            </label>
            <input id="searchBox" />
        </div>
        <div id="searchResult" class="ui-widget" style="margin-top: 1em;">
        </div>
    </div>
</body>
</html>

OWASP TOP 10, How WCS OOB addresses these vulnerabilities or provides frameworks to help

How WCS OOB addresses these vulnerabilities or provides frameworks to help.
The goal of this blog is to explain how the OWASP top 10 are protected in WCS out of the box.

OWASP (Open Web Application Security Project)is used to educate web application architects\developers\testers\managers regarding the most common security vulnerabilities.

Always abide these common security principles:
Accept known good.
Default Deny.
Principle of least privileges.
Using Layered Security or Defense in Depth.

The OWASP Top 10 is a list updated by OWASP every year of the top 10 security risks.

A1 - Cross Site Scripting (XSS)
A2 - Injection Flaws
A3 - Malicious File Execution
A4 - Insecure Direct Object Reference
A5 - Cross Site Request Forgery (CSRF)
A6 - Information Leakage and Improper Error Handling
A7 - Broken Authentication and Session Management
A8 - Insecure Cryptographic Storage
A9 - Insecure Communications
A10 - Failure to Restrict URL Frequently,

A1: XSS is caused by vulnerabilities such as introduce worms,hijack sesssions, etc in the sites that allow user supplied data that is not encoded and validated properly.

WCS Protection:
In wc-server.xml starting 6.0.0.4 the XSS could be specified at every module
and prohibited characters can be specified in the list.
It is a good to have a whilte list for input validation and there is a black list in wc-server.xml for restricting.
e.g.
<XSiteScriptingProtection
display="false"
enabled="true" name="Cross Site Scripting Protection">
<ProhibitedAttrs display="false"/>
<ProhibitedChars display="false">
<Character
display="false" name="&lt;SCRIPT"/>
<Character
display="false" name="&lt;%"/>
<Character
display="false" name="&amp;lt;%"/>
<Character
display="false" name="SCRIPT>"/>
<Character
display="false" name="&amp;lt;SCRIPT"/>
<Character
display="false" name="JAVASCRIPT:"/>
<Character
display="false" name="&amp;#x73;&amp;#x63;&amp;#x72;&amp;#x69;&amp;#x70;&amp;#x74;"/>
</ProhibitedChars>

it provides the input validation framework that can be used to validate the input text by regular expressions.

In JSP you can use the UIUtil to validate:
<%@page import="com.ibm.commerce.tools.util.UIUtil"%>
<%=UIUtil.toJavaScript(java.lang.String.valueOf(pageContext.getAttribute("storeId")))%>

It is always recommended to validate data on the server side, client side validation can be broken by hackers.


A2 - Injection Flaws could result in is caused modifying, deleting or viewing unauthorized data.when user specified data is passed to SQL interpreter as a command.

WCS Protection:In WCS and J2EE in general using prepared statements with specific parameters and validating the parameters is a generally used practice.
Dynamic query front end should be minimized for customer facing applications.

A3 - Malicious File Execution could result in server compromise and virus attacks and this is caused by Remote file inclusion and remote code execution that allows applications to accept files that could result in include hostile files and data.

WCS Protection: WCS being a J2EE App is executed in a JVM run by a sandbox protected by a security manager. It is very important to configure the security manger and the app is demanding permissions appropriately.
Strong user input validation helps even this vulnerability.
Firewalls for web servers should be protected and have a exact or a whitelist of ports and IP addresses that it can allow connections from.
At the OS level, a good idea to segment the file system in production and having an appropriate demarcation.


A4 - Insecure Direct Object Reference could cause unauthorized access to data and files hosted in a web application and this is caused by having direct references such as file, directory, a database key such as orderId, userId exposed in the web application html code or cookies.

WCS Protection:: It has Access controls in place for protection when exposing database keys OrderId,UserId..etc. It has a cookie WC_AUTHENTICATION_148499839 and the value is appended with a uniquely generated code.
148499839%2csFggXZ6m06QiSRLRI9c8DuYlQPc%3d
Access controls for commands and views are protected in commerce by a ACPolicy.xml and all custom commands\views\resources should be correctly defined in these files.

A5 - Cross Site Request Forgery (CSRF): It could compromise the authorized users data and using his credentials exploit other system vulnerabilities as an authorized user. This is mainly caused by remotely taking control of user's session and forging requests from the victim's browser.
XSRF could use the XSS vulnerability to exploit other system vulnerabilities.
Each request a valid unique token that is passed back and forth.

WCS Protection: WCS offers out of the box protection against this vulnerability starting with WCS FixPack 6.0.0.8.
Please find below the configuration and code required to address. The action needs to be updated in struts-config-ext.xml with csrfProtected attribute.

<action parameter="com.ibm.commerce.usermanagement.commands.UserRegistrationUpdateCmd" path="/UserRegistrationUpdate" type="com.ibm.commerce.struts.BaseAction"><set-property property="https" value="0:1"><set-property property="authenticate" value="0:0">
<set-property property="csrfProtected" value="10101:1">
</set-property>
# Edit the JSP file that invokes this action to include the authToken URL parameter.
For example:
<input name="authToken" value="${authToken}" id="WC_UserRegistrationUpdateForm_FormInput_authToken_In_Register_1" type="hidden">

Do use HTTP Post when sending sensitive data.
WCS also has configurable transaction LoginTimeout in wc-server.xml.

A6 - Information Leakage and Improper Error Handling: It could result in powerful attacks and the web application details such as configuration information, internal workings, etc can be leaked via html outputs or long error messages

WCS Protection: Out of the box provides ECApplicationException and ECSystemException and it allows all the errors generated to be forwarded to a common view.
The detailed messages can be disabled and commerce provides a framework to define user friendly messages for these exception using ECMessage and ECMessageHelper.
Making sure all the coders follow the common exception flow handling.
Also if you are using custom logging framework make sure all the sensitive data is masked in the logs.
This framework and exceptions can be extended to incorporate custom features. Some websites also tend to send the user back to home page on any system exception.


A7 - Broken Authentication and Session Management, this vulnerability could lead to breaking into user\admin passwords and also violating privacy laws. This is caused by flaws in authentication mechanisms and poor session management.

WCS Protection: It uses one way hash for the password protection and it protects the passwords from being decrypted.
WCS Commerce admin console provides an interface to define password policy and account policy and this policy is configurable and can be modified on a periodical basis.
WCS allows configuration using struts configuration to define URL's that require authentication.
WCS uses secure authentication cookie (WC_AUTHENTICATION_ID) to manage authentication data
All administrative functions are hosted on applications such as Accelerator\Admin Console\Org admin console and these are open on ports 8000,8002,8004. These ports should not be open to internet and all these users who have access to these internal applications should be governed by good password and account policies just like external users.


A8 - Insecure Cryptographic Storage
This could lead to compliance violations such as PCI and also sensitive data such as credit card information could be leaked. This is mostly caused by weak cryptographic algorithms and the key management.


WCS Protection:
WCS uses strong triple DES algorithm for encryption. That meets the PCI DSS standards.
WCS also provides KLF framework to change the encryption key periodically and allows to re encrypt the sensitive data using the new key.
Do not create new cryptographic algorithms use standard API e.g. bouncycastle.
Store private keys with extreme care.


WCS out of the box introduces keyword krypto on protected sensitive information.

e.g. Out of the box in wc-server.xml
<ProtectedParameters name="Protected Parameters">
<Parameter display="false" name="cardNumber"/>
<Parameter display="false" name="password"/>
<Parameter display="false" name="passwordVerify"/>
<Parameter display="false" name="passwordOld"/>
</ProtectedParameters>

Also there are 2 other elements that should be defined appropriately ProtectedMultiValuedParameters and NonEncryptedParameters

A9 - Insecure Communications
This would result in compliance failures and could expose the private data for spoofing.
This is resulted from not using encrypted network traffic. Opening your webservers to a limited blacklists of Port and IP Addresses.

WCS Protection:
Using SSL when transmitting sensitive data can be achieved by configuring the corresponding actions and views
e.g.
<set-property property="authenticate" value="0:1"/>
<set-property property="https" value="0:1"/>

For back end applications communicating with external applications, make sure the firewall is opened for specific IP Addresses any communication required.

A10 - Failure to Restrict URL Frequently, could result in exposing a certain function or data to unauthorized users. This could be resulted from not having access control checks to protect resources\urls

WCS Protection: out of the box offers access control mechanism and also roles for segmenting authorized content. The access control matrix should be included as a apart of the design and development and URL's and Actions are appropriately protected.

The access control framework: It divides Views and Commands that require authentication and authorization is handled by the access control policies.


This was the list from earlier to 2010.

2010 has a couple more vulnerabilities
A10:

Unvalidated Redirects and Forwards

Add a URLRedirectFilter element in the Module element as shown in the following example:
<module contextpath="/webapp/wcs/stores" fileservletenabled="false" name="Stores" urlmappingpath="/servlet" webalias="/wcsstore">
<initparameters adapters="XML/HTTP, BrowserAdapter" contextsetname="Store" handledoubleclick="true">
<urlredirectfilter enable="true">
<allowedhost name="www.mycompany1.com">
<allowedhost name="www.mycompany2.com">
<alloweddomain name="mycompany3.com">
</alloweddomain>
</allowedhost>

A6: Security Misconfiguration :

Applying the latest patches at OS\DB\Application server and Commerce server and making sure the security configuration is correctly done.



ref:
http://www.owasp.org/index.php/Main_Page