I am using Spring MVC for developing my web application.My problem is ,when I have done APPSCAN of my web application,it report BLIND SQL INJECTION in many of parameters in my SPRING MVC form.I am using bean for fetching data from SPRING MVC form and save() function in Spring framework for saving data to database.How I can resolve my ploblem?
My sample code is below..
Login.jsp contains link
<script>
function openUserReg(){
window.open("/ma/UserReg.nic");
}
</script>
<body>
<form:form>
Producer/ Dealer Registration(Public)
</form>
</body>
configuration of UserReg.nic is
<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="UserReg.nic">UserRegController</prop>
</props>
</property>
</bean>
<bean id="UserRegController" class="nic.mams.web.UserRegController">
<property name="commandName"><value>userReg</value></property>
<property name="commandClass"><value>nic.mams.web.beans.UserRegBean</value></property>
<property name="validator" ref ="UserRegValidator"/>
<property name="userRegService" ref="UserRegService"/>
<property name="pages">
<list>
<value>userRegistration.jsp</value>
<value>successRegistration.jsp</value>
</list>
</property>
</bean>
userRegistration.jsp contains
<form:input path="name" id="name" cssClass="control" maxlength="25" onclick="hidErMsg('er01');hidErMsgInnerHtml('err1');" autocomplete="off"/>
And the controller class contains the code
public class UserRegController extends AbstractWizardFormController{
UserRegService userRegService;
protected Map referenceData(HttpServletRequest req, Object obj, Errors er, int page) throws Exception {.....
return map;
}
protected ModelAndView processFinish(HttpServletRequest req,HttpServletResponse res, Object obj, BindException be) throws Exception {
UserRegBean bean = (UserRegBean)obj;
Applicant app=new Applicant();
...
app.setName(bean.getName());
userRegService.saveApp(app);
}
}
saveApp(app) function in UserRegService contains the code
saveApp(app){
String success = "No";
Session session=getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
try {
getHibernateTemplate().save(app);
tx.commit();
session.close();
success = "Yes";
}
catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
if (success.equals("Yes")){
return getHibernateTemplate().find("SELECT DISTINCT l.applicantLoginId,l.username,a.appServiceId,a.name,a.panNo " +
"FROM ApplicantLogin as l INNER JOIN l.applicants as a " +
"WHERE l.applicantLoginId=? AND l.applicantLoginId=a.applicantLogin AND a.applicantStatus is null " +
"AND a.transferType is null AND a.registrationStatus is not null ",applntlg.getApplicantLoginId());
}
return null;
}
Appscan results this
[17 of 26] Blind SQL Injection
Severity: High
Test Type: Application
Vulnerable URL: UserReg.nic (Parameter: name)
CVE ID(s): N/A
CWE ID(s): 89
Remediation Tasks: Review possible solutions for hazardous character injection
Any one any suggestion please provide me.
Related
I'm using Hibernate 4 to write data to an H2 embedded in-memory database and there seems to be a problem with transactions. The application already uses Oracle and H2 has been added with a separate DataSource, SessionFactory, and TransactionManager. The original TransactionManager is marked as default and the H2 TransactionManager has the qualifier memTransactions
The following code - specifically the load function - correctly populates the memEvents variable at the end with the written data.
#Repository
#Transactional(transactionManager = "memTransactions")
public class EventMemDaoHibernate implements EventMemDao {
#Autowired
#Qualifier(value = "memSessionFactory")
private SessionFactory memSessionFactory;
#Override
public List<EventMem> getEvents() {
return memSessionFactory.getCurrentSession().createCriteria(EventMem.class).list();
}
#Override
public void load(List<Event> allEvents) {
Session session = memSessionFactory.getCurrentSession();
for (Event e : allEvents) {
EventMem memEvent = new EventMem(e);
session.save(memEvent);
}
List<EventMem> memEvents = getEvents(); // correct
}
}
However the following code produces an empty memEvents list
#Autowired
private EventMemDao eventMemDao;
List<Event> allEvents = eventDao.getAllEvents();
eventMemDao.load(allEvents); // calls the load function shown above
List<EventMem> memEvents = eventMemDao.getEvents(); // empty
I assume this is related to transaction management (e.g.: data is not auto-committed after the call to .save()). However when I tried explicitly beginning and committing a transaction within EventMemDaoHibernate#load, I receive this error:
nested transactions not supported
So, from what I can tell the TransactionManager is working.
My TransactionManager and related bean definitions are shown below.
<bean
id="memTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="memSessionFactory" />
<qualifier value="memTransactions"/>
</bean>
<bean id="hDataSource" class="org.h2.jdbcx.JdbcDataSource">
<property name="url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:scripts/init-h2.sql'" />
<property name="user" value="sa" />
<property name="password" value="" />
</bean>
<bean
id="memSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="hDataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
This was due to my configuration error (of course). I didn't fully grasp that the connection URL was evaluated every time a session was opened against H2 and that means init-h2.sql was executed repeatedly. init-h2.sql included a truncate followed by an insert so it was dropping and recreating data every time Hibernate opened a session.
I have created my Interceptor class and have overridden only the afterCompletion method.
When ever the system throws an error ( 500, 404 ), the system breaks and does not reach afterCompletion method of my interceptor. Is there any way so that the request can reach the afterCompletion method with the exception occured.
Interceptor class
public class ClassName extends HandlerInterceptorAdapter {
#Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (ex != null) {
//do somthing here
}
}
}
interceptor declaration
<mvc:interceptors>
<bean class="x.y.z.ClassName" />
</mvc:interceptors>
Can anyone guide me one this.
I am using SWF + MVC and realized different ways of registering interceptors ,
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="DataCollectorFlowRegistry" />
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
</bean>
This works for me.
Why transaction management is failing in spring with the following configuration. The transaction is not rolled back even though a RuntimeException is thrown. Well, i am manually throwing it for learning purposes.
My Dao class:
#Transactional(rollbackFor=ArithmeticException.class)
public class TransactionAnnotationDaoImpl extends JdbcDaoSupport implements JdbcDao {
public void create(Student student) {
try {
String sql = "insert into student values (?,?,?)";
getJdbcTemplate().update(sql,student.getAge(), student.getName(), student.getId());
String marksSql="insert into marks values (?,?,?)";
int i=2/0; //added to depict roll back behaviour of the transaction when exception occurs
getJdbcTemplate().update(marksSql,student.getId(),student.getSubject(),student.getMarks());
System.out.println("transaction committed");
} catch (RuntimeException e) {
e.printStackTrace();
System.out.println("transaction rolled back");
}
}
}
My spring configuration file contents:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"></property>
<property name="url" value="jdbc:derby://localhost:1527/db;create=true"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="annotationTransactionDaoImpl" class="org.sujay.springjdbc.dao.TransactionAnnotationDaoImpl">
<property name="dataSource" ref="dataSource"></property></bean>
I am making call to dao from main method with the following call:
JdbcDao annotationDao = context.getBean("annotationTransactionDaoImpl", JdbcDao.class);
annotationDao.create(new Student(25, "p", 4, 19, "cn2"));
But the transaction is not rolled back. There is an entry in the student table but marks table doesnt have which means transaction is failing. Please help me with this issue.
Because you catched the exception.
Remove the try catch or rethrow the exception:
try{
...
} catch (RuntimeException e) {
e.printStackTrace();
System.out.println("transaction rolled back");
throw e; //rethrow so spring will recognize it
}
I am working in broadleaf which is based on spring-mvc.
there are 3-4 blCustomPersistenceHandlers bean definition in different xml file based on project module.
<bean id="blCustomPersistenceHandlers" class="org.springframework.beans.factory.config.ListFactoryBean" scope="prototype">
<property name="sourceList">
<list>
<bean class="org.broadleafcommerce.admin.server.service.handler.CategoryCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.admin.server.service.handler.CustomerPasswordCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.openadmin.server.security.handler.AdminUserCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.admin.server.service.handler.CustomerCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.admin.server.service.handler.ProductCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.admin.server.service.handler.ChildCategoriesCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.admin.server.service.handler.SkuCustomPersistenceHandler"/>
</list>
</property>
</bean>
below in different xml files
<bean id="blCustomPersistenceHandlers" class="org.springframework.beans.factory.config.ListFactoryBean" scope="prototype">
<property name="sourceList">
<list>
<bean class="org.broadleafcommerce.cms.admin.server.handler.PageTemplateCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.StructuredContentTypeCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.SandBoxItemCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.PendingSandBoxItemCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.TimeDTOCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.RequestDTOCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.StructuredContentItemCriteriaCustomPersistenceHandler"/>
<bean class="org.broadleafcommerce.cms.admin.server.handler.PageItemCriteriaCustomPersistenceHandler"/>
</list>
</property>
</bean>
Above definitions reside into jar files that we included.
Now i want to replace one of this handler , for example ProductCustomPersistenceHandler,
I need to change some functionality regarding that handler, so I changed that handler as below in my xml file.
<bean id="org.broadleafcommerce.admin.server.service.handler.ProductCustomPersistenceHandler"
class="com.mycompany.server.service.handler.HCProductCustomPersistenceHandler" />
and also put bean defination into xml files
<bean id="blCustomPersistenceHandlers" class="org.springframework.beans.factory.config.ListFactoryBean"> <!-- scope="prototype" -->
<property name="sourceList">
<list>
<bean class="com.mycompany.server.service.handler.HCProductCustomPersistenceHandler"/>
</list>
</property>
</bean>
ProductCustomPersistenceHandler class
public class ProductCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {
#Resource(name = "blCatalogService")
protected CatalogService catalogService;
private static final Log LOG = LogFactory.getLog(ProductCustomPersistenceHandler.class);
#Override
public Boolean canHandleAdd(PersistencePackage persistencePackage) {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
String[] customCriteria = persistencePackage.getCustomCriteria();
return !ArrayUtils.isEmpty(customCriteria) && "productDirectEdit".equals(customCriteria[0]) && Product.class.getName().equals(ceilingEntityFullyQualifiedClassname);
}
#Override
public Boolean canHandleUpdate(PersistencePackage persistencePackage) {
return canHandleAdd(persistencePackage);
}
#Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Product adminInstance = (Product) Class.forName(entity.getType()[0]).newInstance();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Product.class.getName(), persistencePerspective);
adminInstance = (Product) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
adminInstance = (Product) dynamicEntityDao.merge(adminInstance);
CategoryProductXref categoryXref = new CategoryProductXrefImpl();
categoryXref.setCategory(adminInstance.getDefaultCategory());
categoryXref.setProduct(adminInstance);
if (adminInstance.getDefaultCategory() != null && !adminInstance.getAllParentCategoryXrefs().contains(categoryXref)) {
categoryXref = (CategoryProductXref) dynamicEntityDao.merge(categoryXref);
adminInstance.getAllParentCategoryXrefs().add(categoryXref);
}
//Since none of the Sku fields are required, it's possible that the user did not fill out
//any Sku fields, and thus a Sku would not be created. Product still needs a default Sku so instantiate one
if (adminInstance.getDefaultSku() == null) {
Sku newSku = catalogService.createSku();
adminInstance.setDefaultSku(newSku);
adminInstance = (Product) dynamicEntityDao.merge(adminInstance);
}
//also set the default product for the Sku
adminInstance.getDefaultSku().setDefaultProduct(adminInstance);
dynamicEntityDao.merge(adminInstance.getDefaultSku());
return helper.getRecord(adminProperties, adminInstance, null, null);
} catch (Exception e) {
LOG.error("Unable to add entity for " + entity.getType()[0], e);
throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
}
}
#Override
public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Product.class.getName(), persistencePerspective);
Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
Product adminInstance = (Product) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
adminInstance = (Product) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
adminInstance = (Product) dynamicEntityDao.merge(adminInstance);
CategoryProductXref categoryXref = new CategoryProductXrefImpl();
categoryXref.setCategory(adminInstance.getDefaultCategory());
categoryXref.setProduct(adminInstance);
if (adminInstance.getDefaultCategory() != null && !adminInstance.getAllParentCategoryXrefs().contains(categoryXref)) {
adminInstance.getAllParentCategoryXrefs().add(categoryXref);
}
return helper.getRecord(adminProperties, adminInstance, null, null);
} catch (Exception e) {
LOG.error("Unable to update entity for " + entity.getType()[0], e);
throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
}
}
}
I just extend this handler and make my new handler , as it runs only core handler is executing, I want to execute my handler.
But this is not working.
I can't change into core part, so I just need to replace handler with my handler.
How can I do that?
Is that possible in spring?
For custom persistence handlers specifically, you can remove the core handlers by using the blCustomPersistenceHandlerFilters bean. So in your case you would define your beans like this:
<bean id="blCustomPersistenceHandlerFilters" class="org.springframework.beans.factory.config.ListFactoryBean" scope="prototype">
<property name="sourceList">
<list>
<bean class="org.broadleafcommerce.openadmin.server.service.handler.DefaultCustomPersistenceHandlerFilter">
<property name="filterCustomPersistenceHandlerClassnames">
<list>
<value>org.broadleafcommerce.admin.server.service.handler.ProductCustomPersistenceHandler</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
Then you can add your own CPH to the list like you were doing before:
<bean id="blCustomPersistenceHandlers" class="org.springframework.beans.factory.config.ListFactoryBean"> <!-- scope="prototype" -->
<property name="sourceList">
<list>
<bean class="com.mycompany.server.service.handler.HCProductCustomPersistenceHandler"/>
</list>
</property>
</bean>
And now the BLC Product custom persistence handler will not run but yours will.
This is probably a little too complex for your simple purposes of wanting to replace the out-of-the-box one with your custom one. It's possible that there is a good reason why we did it like this, but I added a GitHub Issue for it to investigate further.
I'm using Spring 3.1.0.RELEASE with Hibernate 4.0.1.Final. I'm trying to use the Spring transaction manager but am having an issue where Spring is returning old data for a find method. In my Spring application, I call a save method, and then a find method. After I call save, I can see the changes in the database, but when I call the find, it is returning the old state of the object. Here is the controller methods ...
// method to save
#RequestMapping(method = RequestMethod.POST)
public String saveUserEventFeeds(final HttpServletRequest request,
#ModelAttribute("eventFeeds") final Set<EventFeed> eventFeeds) {
final String nextPage = "user/eventfeeds";
try {
final String[] eventFeedIds = request.getParameterValues("userEventFeeds");
final Set<EventFeed> userEventFeeds = new HashSet<EventFeed>();
if (eventFeedIds != null) {
for (final String eventFeedId : eventFeedIds) {
final EventFeed eventFeed = getEventFeed(eventFeeds, Integer.parseInt(eventFeedId));
userEventFeeds.add(eventFeed);
} // for
} // if
final Registration currentUser = (Registration) securityContextFacade.getContext().getAuthentication().getPrincipal();
userService.saveUserEventFeeds(currentUser.getId(), userEventFeeds);
} catch (Exception exc) {
LOG.error(exc.getMessage(), exc);
} // try
return nextPage;
} // saveUserEventFeeds
// method to retrieve user
#ModelAttribute("user")
public UserDetails getUser() {
final Registration reg = (Registration) securityContextFacade.getContext().getAuthentication().getPrincipal();
final int id = reg.getId();
final Registration foundUser = userService.findUserById(id);
return (UserDetails) foundUser;
} // getUser
and here is the service where i declare everything transactional ...
#Transactional(rollbackFor = Exception.class)
#Component("userService")
public class UserServiceImpl implements UserService {
...
#Override
public void saveUserEventFeeds(Integer userId, Set<EventFeed> eventFeeds) {
final Registration searchUser = new Registration();
searchUser.setId(userId);
final Registration user = usersDao.getUser(searchUser);
if (user != null) {
user.setUserEventFeeds(eventFeeds);
usersDao.saveUser(user);
} else {
throw new RuntimeException("User with id " + userId + " not found.");
} // if
}
#Override
public Registration findUserById(Integer id) {
final Registration searchUser = new Registration();
if (id != null) {
searchUser.setId(id);
} // if
return usersDao.getUser(searchUser);
}
Below is the transaction manager I've declared in my application context file. If you can see how I can configure things differently so that I can get the most current data on my finds, please let me know.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myproj"/>
<property name="username" value="myproj"/>
<property name="password" value="password"/>
<property name="maxActive" value="10"/>
<property name="minIdle" value="5"/>
<!-- SELECT 1 is a simple query that returns 1 row in MySQL -->
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.myco.myproj.domain.Registration</value>
<value>com.myco.myproj.domain.Role</value>
<value>com.myco.myproj.domain.EventFeed</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="show_sql">true</prop>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<tx:annotation-driven />