Removing unused code and separating deprecated files
authorZofia Abramowska <z.abramowska@samsung.com>
Mon, 18 Feb 2013 12:44:57 +0000 (13:44 +0100)
committerGerrit Code Review <gerrit2@kim11>
Thu, 21 Feb 2013 16:32:01 +0000 (01:32 +0900)
[Issue#] SSDWSSP-98
[Feature] N/A
[Cause] Removal of unwanted files from security-server
[Solution] N/A
[Verification] Successful build

Change-Id: I27fbd9ca4d597c71b65400c4ed71458b406f557b

82 files changed:
CMakeLists.txt
src/CMakeLists.txt
src/client/security-server-client.c [new file with mode: 0644]
src/communication/security-server-comm.c [new file with mode: 0644]
src/daemon/dbus/org.tizen.SecurityDaemon.service [deleted file]
src/daemon/dbus/security_daemon_dbus_config.h [deleted file]
src/daemon/dbus/security_dbus_service.cpp [deleted file]
src/daemon/dbus/security_dbus_service.h [deleted file]
src/daemon/security_daemon.cpp [deleted file]
src/daemon/security_daemon.h [deleted file]
src/daemon/sockets/api/callback_api.h [deleted file]
src/daemon/sockets/security_daemon_socket_config.h [deleted file]
src/daemon/sockets/security_socket_service.cpp [deleted file]
src/daemon/sockets/security_socket_service.h [deleted file]
src/include/SLP_security-model_PG.h [new file with mode: 0644]
src/include/SLP_security-server_PG.h [new file with mode: 0644]
src/include/security-server-comm.h [new file with mode: 0644]
src/include/security-server-common.h [new file with mode: 0644]
src/include/security-server-cookie.h [new file with mode: 0644]
src/include/security-server-password.h [new file with mode: 0644]
src/include/security-server-util.h [new file with mode: 0644]
src/include/security-server.h [new file with mode: 0644]
src/main.cpp [deleted file]
src/mw-list [new file with mode: 0644]
src/security-serverd [new file with mode: 0644]
src/security-srv/CMakeLists.txt [deleted file]
src/security-srv/client/security-server-client.c [deleted file]
src/security-srv/communication/security-server-comm.c [deleted file]
src/security-srv/include/SLP_security-model_PG.h [deleted file]
src/security-srv/include/SLP_security-server_PG.h [deleted file]
src/security-srv/include/security-server-comm.h [deleted file]
src/security-srv/include/security-server-common.h [deleted file]
src/security-srv/include/security-server-cookie.h [deleted file]
src/security-srv/include/security-server-password.h [deleted file]
src/security-srv/include/security-server-util.h [deleted file]
src/security-srv/include/security-server.h [deleted file]
src/security-srv/mw-list [deleted file]
src/security-srv/security-serverd [deleted file]
src/security-srv/server/security-server-cookie.c [deleted file]
src/security-srv/server/security-server-main.c [deleted file]
src/security-srv/server/security-server-password.c [deleted file]
src/security-srv/util/security-server-util-common.c [deleted file]
src/security-srv/util/security-server-util.c [deleted file]
src/server/security-server-cookie.c [new file with mode: 0644]
src/server/security-server-main.c [new file with mode: 0644]
src/server/security-server-password.c [new file with mode: 0644]
src/services/ace/ace_server_api.h [deleted file]
src/services/ace/ace_service.cpp [deleted file]
src/services/ace/dbus/ace_server_dbus_interface.cpp [deleted file]
src/services/ace/dbus/ace_server_dbus_interface.h [deleted file]
src/services/ace/dbus/api/ace_server_dbus_api.h [deleted file]
src/services/ace/logic/acf_consts.h [deleted file]
src/services/ace/logic/attribute_facade.cpp [deleted file]
src/services/ace/logic/attribute_facade.h [deleted file]
src/services/ace/logic/security_controller.cpp [deleted file]
src/services/ace/logic/security_controller.h [deleted file]
src/services/ace/logic/security_logic.cpp [deleted file]
src/services/ace/logic/security_logic.h [deleted file]
src/services/ace/logic/simple_roaming_agent.cpp [deleted file]
src/services/ace/logic/simple_roaming_agent.h [deleted file]
src/services/ace/socket/ace_service_callbacks.cpp [deleted file]
src/services/ace/socket/ace_service_callbacks.h [deleted file]
src/services/ace/socket/api/ace_service_callbacks_api.h [deleted file]
src/services/caller/security_caller.cpp [deleted file]
src/services/caller/security_caller.h [deleted file]
src/services/ocsp/dbus/api/ocsp_server_dbus_api.h [deleted file]
src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp [deleted file]
src/services/ocsp/dbus/ocsp_server_dbus_interface.h [deleted file]
src/services/ocsp/ocsp_server_api.h [deleted file]
src/services/ocsp/ocsp_service.cpp [deleted file]
src/services/ocsp/socket/api/ocsp_service_callbacks_api.h [deleted file]
src/services/ocsp/socket/ocsp_service_callbacks.cpp [deleted file]
src/services/ocsp/socket/ocsp_service_callbacks.h [deleted file]
src/services/popup/dbus/popup_response_dbus_interface.cpp [deleted file]
src/services/popup/dbus/popup_response_dbus_interface.h [deleted file]
src/services/popup/popup_ace_data_types.h [deleted file]
src/services/popup/popup_response_server_api.h [deleted file]
src/services/popup/socket/api/popup_service_callbacks_api.h [deleted file]
src/services/popup/socket/popup_service_callbacks.cpp [deleted file]
src/services/popup/socket/popup_service_callbacks.h [deleted file]
src/util/security-server-util-common.c [new file with mode: 0644]
src/util/security-server-util.c [new file with mode: 0644]

index ca0a4ba2cf2703e1c40b00ba21397d372e7cd987..740aa896528d8c19cff0a2f38d9098384526d4c0 100644 (file)
@@ -41,36 +41,16 @@ SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -std=c++0x -g")
 SET(CMAKE_C_FLAGS_CCOV         "-O2 -g --coverage")
 SET(CMAKE_CXX_FLAGS_CCOV       "-O2 -std=c++0x -g --coverage")
 
-#SET(SMACK_ENABLE ON)
-
-#OPTION(DPL_LOG "DPL logs status" ON)
-#IF(DPL_LOG)
-#    MESSAGE(STATUS "Logging enabled for DPL")
-#    ADD_DEFINITIONS("-DDPL_LOGS_ENABLED")
-#ELSE(DPL_LOG)
-#    MESSAGE(STATUS "Logging disabled for DPL")
-#ENDIF(DPL_LOG)
-
 # If supported for the target machine, emit position-independent code,suitable
 # for dynamic linking and avoiding any limit on the size of the global offset
 # table. This option makes a difference on the m68k, PowerPC and SPARC.
 # (BJ: our ARM too?)
 ADD_DEFINITIONS("-fPIC")
 
-# Set the default ELF image symbol visibility to hidden - all symbols will be
-# marked with this unless overridden within the code.
-#ADD_DEFINITIONS("-fvisibility=hidden")
 
 # Set compiler warning flags
-#ADD_DEFINITIONS("-Werror")                      # Make all warnings into errors.
 ADD_DEFINITIONS("-Wall")                        # Generate all warnings
 ADD_DEFINITIONS("-Wextra")                      # Generate even more extra warnings
-#ADD_DEFINITIONS("-Wno-variadic-macros")         # Inhibit variadic macros warnings (needed for ORM)
-#ADD_DEFINITIONS("-Wno-deprecated")               # No warnings about deprecated features
-#ADD_DEFINITIONS("-std=c++0x")               # No warnings about deprecated features
-
-#ADD_DEFINITIONS("-DSOCKET_CONNECTION")      #defines sockets as used IPC
-#ADD_DEFINITIONS("-DDBUS_CONNECTION")        #defines DBus as used IPC
 
 STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
 ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
index f67f221191754c4e06bb666a601dfc5a432c6541..b2b1569a988b199c9e8416c4181c94bb5f95ac71 100644 (file)
-# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
-#
-#    Licensed under the Apache License, Version 2.0 (the "License");
-#    you may not use this file except in compliance with the License.
-#    You may obtain a copy of the License at
-#
-#        http://www.apache.org/licenses/LICENSE-2.0
-#
-#    Unless required by applicable law or agreed to in writing, software
-#    distributed under the License is distributed on an "AS IS" BASIS,
-#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#    See the License for the specific language governing permissions and
-#    limitations under the License.
-#
-#
-# @file     CMakeLists.txt
-# @author   Bartlomiej Grzelewski (b.grzelewski@samsung.com)
-#
-
-#SET(DAEMON_BASIC_DEP
-#    dpl-efl
-#    dpl-dbus-efl
-#    dpl-utils-efl
-#    libsoup-2.4
-#    openssl
-#    libsmack
-#  )
-#
-#IF(SMACK_ENABLE)
-#    LIST(APPEND DAEMON_BASIC_DEP libprivilege-control)
-#ENDIF(SMACK_ENABLE)
-#
-#PKG_CHECK_MODULES(DAEMON_DEP
-#    ${DAEMON_BASIC_DEP}
-#    REQUIRED)
-#
-#SET(DAEMON_SOURCES_PATH ${PROJECT_SOURCE_DIR}/src)
-#
-#SET(DAEMON_SOURCES
-#    #socket connection
-#    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketConnection.cpp
-#    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketStream.cpp
-#    #caller
-#    ${DAEMON_SOURCES_PATH}/services/caller/security_caller.cpp
-#    #daemon
-#    ${DAEMON_SOURCES_PATH}/daemon/dbus/security_dbus_service.cpp
-#    ${DAEMON_SOURCES_PATH}/daemon/sockets/security_socket_service.cpp
-#    ${DAEMON_SOURCES_PATH}/daemon/security_daemon.cpp
-#    ${DAEMON_SOURCES_PATH}/main.cpp
-#    #ocsp
-#    ${DAEMON_SOURCES_PATH}/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ocsp/socket/ocsp_service_callbacks.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ocsp/ocsp_service.cpp
-#    #ace
-#    ${DAEMON_SOURCES_PATH}/services/ace/dbus/ace_server_dbus_interface.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/socket/ace_service_callbacks.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/ace_service.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_controller.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/logic/attribute_facade.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_logic.cpp
-#    ${DAEMON_SOURCES_PATH}/services/ace/logic/simple_roaming_agent.cpp
-#    #popup
-#    ${DAEMON_SOURCES_PATH}/services/popup/dbus/popup_response_dbus_interface.cpp
-#    ${DAEMON_SOURCES_PATH}/services/popup/socket/popup_service_callbacks.cpp
-#  )
-#
-#SET_SOURCE_FILES_PROPERTIES(${DAEMON_SOURCES} PROPERTIES COMPILE_FLAGS "-std=c++0x")
-#
-############################## Lets start compilation process ##################
-##ace library
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
-##socket connection library
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/socket_connection/connection)
-##daemon
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets/api)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets)
-##caller
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/caller)
-##ace
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket/api)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/logic)
-##ocsp
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket/api)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/logic)
-##popup
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket/api)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/logic)
-#INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
-#INCLUDE_DIRECTORIES(${DAEMON_DEP_INCLUDE_DIRS})
-#
-#ADD_EXECUTABLE(${TARGET_DAEMON}
-#    ${DAEMON_SOURCES})
-#
-#TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
-#    ${DAEMON_DEP_LIBRARIES}
-#    ${TARGET_ACE_LIB}
-#    ${TARGET_ACE_DAO_RW_LIB})
-#
-#INSTALL(TARGETS ${TARGET_DAEMON}
-#    DESTINATION bin)
-#
-#INSTALL(FILES
-#    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/org.tizen.SecurityDaemon.service
-#    DESTINATION /usr/share/dbus-1/services
-#    )
-#
-#INSTALL(FILES
-#    ${PROJECT_SOURCE_DIR}/src/services/ace/ace_server_api.h
-#    ${PROJECT_SOURCE_DIR}/src/services/ocsp/ocsp_server_api.h
-#    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_response_server_api.h
-#    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_ace_data_types.h
-#    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/security_daemon_dbus_config.h
-#    DESTINATION /usr/include/wrt-security
-#    )
-#
-ADD_SUBDIRECTORY(security-srv)
+PKG_CHECK_MODULES(SECURITY_SERVER_DEP
+    dlog
+    openssl
+    libsmack
+    REQUIRED
+    )
+
+SET(SECURITY_SERVER_PATH ${PROJECT_SOURCE_DIR}/src)
+
+SET(SECURITY_SERVER_SOURCES
+    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
+    ${SECURITY_SERVER_PATH}/server/security-server-cookie.c
+    ${SECURITY_SERVER_PATH}/server/security-server-main.c
+    ${SECURITY_SERVER_PATH}/server/security-server-password.c
+    ${SECURITY_SERVER_PATH}/util/security-server-util-common.c
+    )
+
+SET_SOURCE_FILES_PROPERTIES(
+    ${SECURITY_SERVER_SOURCES}
+    PROPERTIES
+        COMPILE_FLAGS "-D_GNU_SOURCE -DSECURITY_SERVER_DEBUG_DLOG")
+
+INCLUDE_DIRECTORIES(
+    ${SECURITY_SERVER_PATH}/include
+    ${SECURITY_SERVER_DEP_INCLUDE_DIRS}
+    )
+
+ADD_EXECUTABLE(${TARGET_SECURITY_SERVER} ${SECURITY_SERVER_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_SECURITY_SERVER}
+    ${SECURITY_SERVER_DEP_LIBRARIES}
+    )
+
+################################################################################
+
+SET(SECURITY_CLIENT_VERSION_MAJOR 1)
+SET(SECURITY_CLIENT_VERSION ${SECURITY_CLIENT_VERSION_MAJOR}.0.1)
+
+SET(SECURITY_CLIENT_SOURCES
+    ${SECURITY_SERVER_PATH}/client/security-server-client.c
+    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
+    )
+
+ADD_LIBRARY(${TARGET_SECURITY_CLIENT} SHARED ${SECURITY_CLIENT_SOURCES})
+
+SET_TARGET_PROPERTIES(
+    ${TARGET_SECURITY_CLIENT}
+    PROPERTIES
+        LINK_FLAGS "-module -avoid-version"
+        COMPILE_FLAGS "-D_GNU_SOURCE -DSECURITY_SERVER_DEBUG_DLOG -fPIC"
+        SOVERSION ${SECURITY_CLIENT_VERSION_MAJOR}
+        VERSION ${SECURITY_CLIENT_VERSION}
+    )
+
+TARGET_LINK_LIBRARIES(${TARGET_SECURITY_CLIENT}
+    ${SECURITY_SERVER_DEP_LIBRARIES}
+    )
+
+################################################################################
+
+INSTALL(TARGETS ${TARGET_SECURITY_CLIENT} DESTINATION lib)
+
+INSTALL(TARGETS ${TARGET_SECURITY_SERVER} DESTINATION bin)
+
+INSTALL(FILES
+    ${SECURITY_SERVER_PATH}/include/security-server.h
+    DESTINATION /usr/include/security-server
+    )
+
+INSTALL(FILES
+    ${SECURITY_SERVER_PATH}/mw-list
+    DESTINATION /usr/share/security-server
+    )
+
+INSTALL(FILES
+    ${SECURITY_SERVER_PATH}/security-serverd
+    DESTINATION /etc/rc.d/init.d
+    )
+
+################################################################################
+
+#CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
+#INSTALL
+
+################################################################################
diff --git a/src/client/security-server-client.c b/src/client/security-server-client.c
new file mode 100644 (file)
index 0000000..68e83a0
--- /dev/null
@@ -0,0 +1,1111 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/smack.h>
+#include <fcntl.h>
+
+#include "security-server.h"
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+#if 0
+void printhex(unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+
+char *read_cmdline_from_proc(pid_t pid)
+{
+       int memsize = 32;
+       char path[32];
+       char *cmdline = NULL;
+
+       snprintf(path, sizeof(path), "/proc/%d/exe", pid);
+
+       cmdline = malloc(32);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               goto error;
+       }
+
+       while(1)
+       {
+               bzero(cmdline, memsize);
+               /* readlink() may have security hole in normal symbolic link. *
+                * But this link is located at proc fs that only kernel can change */
+               readlink(path, cmdline, memsize);       /* FlawFinder: ignore */
+SEC_SVR_DBG("pid: %d, cmdline: %s", pid, cmdline);
+
+               /* Check it's truncated */
+               if(cmdline[memsize -1] != 0)
+               {
+                       cmdline = (char *)realloc(cmdline, sizeof(char) * (memsize + 32));
+                       memsize += 32;
+                       if(cmdline == NULL)
+                       {
+                               SEC_SVR_DBG("%s", "Out of memory");
+                               goto error;
+                       }
+               }
+               else
+                       break;
+       }
+
+error:
+       return cmdline;
+}
+#endif
+
+
+/* We may need to filter error code */
+int convert_to_public_error_code(int err_code)
+{
+       /* Do we need this? */
+       return err_code;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_gid(const char *object)
+{
+       int sockfd = -1, retval, gid;
+       response_header hdr;
+
+       if(object == NULL)
+       {
+               SEC_SVR_DBG("%s", "Client: object is null or object is too big");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+       if( strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME )
+       {
+               SEC_SVR_DBG("%s", "object is null or object is too big");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       if(strlen(object) == 0)
+       {
+               SEC_SVR_DBG("Client: object is is empty");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       SEC_SVR_DBG("%s", "Client: security_server_get_gid() is called");
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Connection failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: Security server has been connected");
+
+       /* make request packet and send to server*/
+       retval = send_gid_request(sockfd, object);
+       SEC_SVR_DBG("%s", "Client: gid request has been sent");
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send gid request failed: %d", retval);
+               goto error;
+       }
+
+       /* Receive response */
+       retval = recv_get_gid_response(sockfd, &hdr, &gid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: get gid response has been received");
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GID_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: It'll be an error. return code:%d", hdr.return_code);
+                       retval = return_code_to_error_code(hdr.return_code);
+                       goto error;
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client: Something wrong with response:%d", hdr.basic_hdr.msg_id);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+                       goto error;
+               }
+       }
+
+       SEC_SVR_DBG("received gid is %d", gid);
+       retval = gid;
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+       /* If error happened */
+       if(retval < 0)
+               retval = convert_to_public_error_code(retval);
+
+       return retval;
+}
+
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(object == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: connect to server failed: %d", retval);
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_object_name_request(sockfd, gid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: cannot send request: %d", retval);
+               goto error;
+       }
+
+       retval = recv_get_object_name(sockfd, &hdr, object, max_object_size);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
+               goto error;
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: There is error on response: return code:%d", hdr.basic_hdr.msg_id);
+                       retval = return_code_to_error_code(hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client: Some unexpected error happene: return code:%d", hdr.basic_hdr.msg_id);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_request_cookie(char *cookie, size_t max_cookie)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+       if(max_cookie < SECURITY_SERVER_COOKIE_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+               goto error;
+       }
+
+       SEC_SVR_DBG("%s", "Client: security_server_request_cookie() is called");
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("%s", "Client: connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: send cookie failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: cookie request sent");
+       retval = recv_cookie(sockfd, &hdr, cookie);
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE)    /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client ERROR: There is an error on response. return code:%d", hdr.return_code);
+                       retval = return_code_to_error_code(hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: cookie received");
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+
+
+       SECURITY_SERVER_API
+int security_server_check_privilege(const char *cookie, gid_t privilege)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_privilege_check_request(sockfd, cookie, privilege);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_privilege_check_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+       SECURITY_SERVER_API
+int security_server_check_privilege_by_cookie(const char *cookie,
+                                              const char *object,
+                                              const char *access_rights)
+{
+       int sockfd = -1, retval;
+        int olen, alen;
+       response_header hdr;
+
+       if(cookie == NULL || object == NULL || access_rights == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+        olen = strlen(object);
+        alen = strlen(access_rights);
+
+        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+        retval = send_privilege_check_new_request(
+                     sockfd, cookie, object, access_rights);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_privilege_check_new_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE)
+        /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d",
+                                    hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd >= 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_check_privilege_by_sockfd(int sockfd,
+                                              const char *object,
+                                              const char *access_rights)
+{
+    char *subject;
+    int ret;
+    ret = smack_new_label_from_socket(sockfd, &subject);
+    if (ret != 0)
+    {
+        return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    }
+    ret = smack_have_access(subject, object, access_rights);
+    SEC_SVR_DBG("check by sockfd, subject >%s< object >%s< rights >%s< ====> %d",
+                subject, object, access_rights, ret);
+    free(subject);
+    if (ret == 1)
+    {
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+    else
+    {
+        return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+    }
+}
+
+
+       SECURITY_SERVER_API
+int security_server_get_cookie_size(void)
+{
+       return SECURITY_SERVER_COOKIE_LEN;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_cookie_pid(const char *cookie)
+{
+       int sockfd = -1, retval, pid = -1;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_pid_request(sockfd, cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pid_response(sockfd, &hdr, &pid);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_PID_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+       if(hdr.return_code == SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE)
+       {
+               SEC_SVR_DBG("%s"," Client: There is no such cookie exist");
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       if(retval == 0)
+               return pid;
+
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_launch_debug_tool(int argc, const char **argv)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(argc < 1 || argv == NULL || argv[0] == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       if(argc == 1)
+       {
+               if(strcmp(argv[0], SECURITY_SERVER_KILL_APP_PATH) != 0)
+               {
+                       retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+                       goto error;
+               }
+       }
+
+       /* Check the caller is developer shell */
+       retval = getuid();
+       if(retval != SECURITY_SERVER_DEVELOPER_UID)
+       {
+               SEC_SVR_DBG("Client: It's not allowed to call this API by uid %d", retval);
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_launch_tool_request(sockfd, argc, argv);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE)      /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_is_pwd_valid(unsigned int *current_attempts,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int sockfd = -1, retval = SECURITY_SERVER_ERROR_UNKNOWN;
+       response_header hdr;
+
+       if(current_attempts == NULL || max_attempts == NULL ||valid_secs == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_valid_pwd_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pwd_response(sockfd, &hdr, current_attempts, max_attempts, valid_secs);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE) /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_set_pwd(const char *cur_pwd,
+                       const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_set_pwd_request(sockfd, cur_pwd, new_pwd, max_challenge, valid_period_in_days);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
+{
+    int sockfd = -1, retval;
+    response_header hdr;
+
+    retval = connect_to_server(&sockfd);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        goto error;
+    }
+
+    /* make request packet */
+    retval = send_set_pwd_validity_request(sockfd, valid_period_in_days);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        SEC_SVR_DBG("Client: Send failed: %d", retval);
+        goto error;
+    }
+
+    retval = recv_generic_response(sockfd, &hdr);
+
+    retval = return_code_to_error_code(hdr.return_code);
+    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE)   /* Wrong response */
+    {
+        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+        {
+            /* There must be some error */
+            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+        }
+        else
+        {
+            /* Something wrong with response */
+            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+        }
+        goto error;
+    }
+error:
+    if(sockfd > 0)
+        close(sockfd);
+
+    retval = convert_to_public_error_code(retval);
+    return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
+{
+    int sockfd = -1, retval;
+    response_header hdr;
+
+    retval = connect_to_server(&sockfd);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        goto error;
+    }
+
+    /* make request packet */
+    retval = send_set_pwd_max_challenge_request(sockfd, max_challenge);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        SEC_SVR_DBG("Client: Send failed: %d", retval);
+        goto error;
+    }
+
+    retval = recv_generic_response(sockfd, &hdr);
+
+    retval = return_code_to_error_code(hdr.return_code);
+    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE)   /* Wrong response */
+    {
+        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+        {
+            /* There must be some error */
+            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+        }
+        else
+        {
+            /* Something wrong with response */
+            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+        }
+        goto error;
+    }
+error:
+    if(sockfd > 0)
+        close(sockfd);
+
+    retval = convert_to_public_error_code(retval);
+    return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_reset_pwd(const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_reset_pwd_request(sockfd, new_pwd, max_challenge, valid_period_in_days);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE) /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_chk_pwd(const char *challenge,
+       unsigned int *current_attempt,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(challenge == NULL || strlen(challenge) > SECURITY_SERVER_MAX_PASSWORD_LEN
+               || current_attempt == NULL || max_attempts == NULL || valid_secs == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self goes here */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_chk_pwd_request(sockfd, challenge);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pwd_response(sockfd, &hdr, current_attempt, max_attempts, valid_secs);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_history(int number_of_history)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(number_of_history > SECURITY_SERVER_MAX_PASSWORD_HISTORY || number_of_history < 0)
+               return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_set_pwd_history_request(sockfd, number_of_history);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+SECURITY_SERVER_API
+char * security_server_get_smacklabel_cookie(const char * cookie)
+{
+    char * label = NULL;
+    int sockfd = -1, retval, pid = -1;
+    response_header hdr;
+
+    if(cookie == NULL)
+    {
+        retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+        goto error;
+    }
+
+    retval = connect_to_server(&sockfd);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        goto error;
+    }
+
+    /* make request packet */
+    retval = send_smack_request(sockfd, cookie);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        SEC_SVR_DBG("Client: Send failed: %d", retval);
+        goto error;
+    }
+
+    //allocating buffer for storing SMACK label received from server
+    label = calloc(SMACK_LABEL_LEN + 1, 1);
+    if(NULL == label)
+    {
+        SEC_SVR_DBG("Client ERROR: Memory allocation error");
+        goto error;
+    }
+
+    retval = recv_smack_response(sockfd, &hdr, label);
+
+    retval = return_code_to_error_code(hdr.return_code);
+    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE)        /* Wrong response */
+    {
+        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+        {
+            /* There must be some error */
+            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+        }
+        else
+        {
+            /* Something wrong with response */
+            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+        }
+        goto error;
+    }
+    if(hdr.return_code == SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE)
+    {
+        SEC_SVR_DBG("%s"," Client: There is no such cookie exist");
+    }
+
+error:
+    if(sockfd > 0)
+        close(sockfd);
+
+    retval = convert_to_public_error_code(retval);
+    if(retval == 0)
+        return label;
+
+    if(NULL != label)
+        free(label);
+
+    return NULL;
+}
+
+       SECURITY_SERVER_API
+char * security_server_get_smacklabel_sockfd(int fd)
+{
+       char * label = NULL;
+
+       if(smack_new_label_from_socket(fd, &label) != 0)
+       {
+               SEC_SVR_DBG("Client ERROR: Unable to get socket SMACK label");
+               return NULL;
+       }
+
+       return label;
+}
+
+
diff --git a/src/communication/security-server-comm.c b/src/communication/security-server-comm.c
new file mode 100644 (file)
index 0000000..56a4d14
--- /dev/null
@@ -0,0 +1,2497 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <sys/poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/smack.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <limits.h>
+
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+void printhex(const unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+char *read_cmdline_from_proc(pid_t pid)
+{
+       int memsize = 32;
+       char path[32];
+       char *cmdline = NULL, *tempptr = NULL;
+       FILE *fp = NULL;
+
+       snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
+
+       fp = fopen(path, "r");
+       if(fp == NULL)
+       {
+               SEC_SVR_DBG("Cannot open cmdline on pid[%d]", pid);
+               return NULL;
+       }
+
+       cmdline = malloc(32);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               fclose(fp);
+               return NULL;
+       }
+
+       bzero(cmdline, memsize);
+       if(fgets(cmdline, 32, fp) == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot read cmdline");
+               free(cmdline);
+               fclose(fp);
+               return NULL;
+       }
+
+       while(cmdline[memsize -2] != 0)
+       {
+               cmdline[memsize -1] = (char) fgetc(fp);
+               tempptr = realloc(cmdline, memsize + 32);
+               if(tempptr == NULL)
+               {
+                       fclose(fp);
+                       SEC_SVR_DBG("%s", "Out of memory");
+                       return NULL;
+               }
+               cmdline = tempptr;
+               bzero(cmdline + memsize, 32);
+               fgets(cmdline + memsize, 32, fp);
+               memsize += 32;
+       }
+
+       if(fp != NULL)
+               fclose(fp);
+       return cmdline;
+}
+
+/* Return code in packet is positive integer *
+ * We need to convert them to error code which are negative integer */
+int return_code_to_error_code(int ret_code)
+{
+       int ret;
+       switch(ret_code)
+       {
+               case SECURITY_SERVER_RETURN_CODE_SUCCESS:
+               case SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED:
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_BAD_REQUEST:
+                       ret = SECURITY_SERVER_ERROR_BAD_REQUEST;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED:
+                       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED:
+                       ret = SECURITY_SERVER_ERROR_ACCESS_DENIED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT:
+                       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_SERVER_ERROR:
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE:
+                       ret = SECURITY_SERVER_ERROR_NO_SUCH_COOKIE;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_PASSWORD:
+                       ret = SECURITY_SERVER_ERROR_NO_PASSWORD;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXIST;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_REUSED;
+                       break;
+               default:
+                       ret = SECURITY_SERVER_ERROR_UNKNOWN;
+                       break;
+       }
+       return ret;
+}
+
+int check_socket_poll(int sockfd, int event, int timeout)
+{
+       struct pollfd poll_fd[1];
+       int retval = SECURITY_SERVER_ERROR_POLL;
+
+       poll_fd[0].fd = sockfd;
+       poll_fd[0].events = event;
+       retval = poll(poll_fd, 1, timeout);
+       if(retval < 0)
+       {
+               SEC_SVR_DBG("poll() error. errno=%d", errno);
+               if(errno != EINTR)
+                       return SECURITY_SERVER_ERROR_POLL;
+               else
+               {
+                       /* Chile process has been closed. Not poll() problem. Call it once again */
+                       return check_socket_poll(sockfd, event, timeout);
+               }
+       }
+
+       /* Timed out */
+       if(retval == 0)
+       {
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       if(poll_fd[0].revents != event)
+       {
+               SEC_SVR_DBG("Something wrong on the peer socket. event=0x%x", poll_fd[0].revents);
+               return SECURITY_SERVER_ERROR_POLL;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int safe_server_sock_close(int client_sockfd)
+{
+       struct pollfd poll_fd[1];
+       int retval;
+       retval = SECURITY_SERVER_ERROR_POLL;
+       poll_fd[0].fd = client_sockfd;
+       poll_fd[0].events = POLLRDHUP;
+       retval = poll(poll_fd, 1, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       SEC_SVR_DBG("%s", "Server: Closing server socket");
+       close(client_sockfd);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Create a Unix domain socket and bind */
+int create_new_socket(int *sockfd)
+{
+       int retval = 0, localsockfd = 0, flags;
+       struct sockaddr_un serveraddr;
+       mode_t sock_mode;
+
+       /* Deleted garbage Unix domain socket file */
+       retval = remove(SECURITY_SERVER_SOCK_PATH);
+
+    if (retval == -1 && errno != ENOENT) {
+        retval = SECURITY_SERVER_ERROR_UNKNOWN;
+        localsockfd = -1;
+        SEC_SVR_DBG("%s", "Unable to remove /tmp/.security_server.sock");
+        goto error;
+    }
+
+       /* Create Unix domain socket */
+       if((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 )
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               localsockfd = -1;
+               SEC_SVR_DBG("%s", "Socket creation failed");
+               goto error;
+       }
+
+       if(smack_fsetlabel(localsockfd, "@", SMACK_LABEL_IPOUT) != 0)
+       {
+               SEC_SVR_DBG("%s", "SMACK labeling failed");
+               if(errno != EOPNOTSUPP)
+               {
+                       retval = SECURITY_SERVER_ERROR_SOCKET;
+            close(localsockfd);
+                       localsockfd = -1;
+                       goto error;
+               }
+       }
+       if(smack_fsetlabel(localsockfd, "*", SMACK_LABEL_IPIN) != 0)
+       {       SEC_SVR_DBG("%s", "SMACK labeling failed");
+               if(errno != EOPNOTSUPP)
+               {
+                       retval = SECURITY_SERVER_ERROR_SOCKET;
+            close(localsockfd);
+                       localsockfd = -1;
+                       goto error;
+               }
+       }
+
+       /* Make socket as non blocking */
+       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
+                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               close(localsockfd);
+               localsockfd = -1;
+               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
+               goto error;
+       }
+
+       bzero (&serveraddr, sizeof(serveraddr));
+       serveraddr.sun_family = AF_UNIX;
+       strncpy(serveraddr.sun_path, SECURITY_SERVER_SOCK_PATH,
+                       strlen(SECURITY_SERVER_SOCK_PATH));
+       serveraddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
+
+       /* Bind the socket */
+       if((bind(localsockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET_BIND;
+               SEC_SVR_DBG("%s", "Cannot bind");
+               close(localsockfd);
+               localsockfd = -1;
+               goto error;
+       }
+
+
+       /* Change permission to accept all processes that has different uID/gID */
+       sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO);
+       /* Flawfinder hits this chmod function as level 5 CRITICAL as race condition flaw *
+        * Flawfinder recommends to user fchmod insted of chmod
+        * But, fchmod doesn't work on socket file so there is no other choice at this point */
+       if(chmod(SECURITY_SERVER_SOCK_PATH, sock_mode) < 0)             /* Flawfinder: ignore */
+       {
+               SEC_SVR_DBG("%s", "chmod() error");
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               close(localsockfd);
+               localsockfd = -1;
+               goto error;
+       }
+
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       *sockfd = localsockfd;
+       return retval;
+}
+
+/* Authenticate peer that it's really security server.
+ * Check UID that is root
+ */
+int authenticate_server(int sockfd)
+{
+       int retval;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+/*     char *cmdline = NULL;*/
+
+       /* get socket peer credential */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "getsockopt() failed");
+               goto error;
+       }
+
+       /* Security server must run as root */
+       if(cr.uid != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Peer is not root: uid=%d", cr.uid);
+               goto error;
+       }
+       else
+               retval = SECURITY_SERVER_SUCCESS;
+
+       /* Read command line of the PID from proc fs */
+       /* This is commented out because non root process cannot read link of /proc/pid/exe */
+/*     cmdline = read_cmdline_from_proc(cr.pid);
+
+       if(strcmp(cmdline, SECURITY_SERVER_DAEMON_PATH) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Cmdline is different. auth failed. cmdline=%s", cmdline);
+       }
+       else
+       {
+               retval = SECURITY_SERVER_SUCCESS;
+               SEC_SVR_DBG("Server authenticatd. %s, sockfd=%d", cmdline, sockfd);
+       }
+*/
+error:
+/*     if(cmdline != NULL)
+               free(cmdline);
+*/
+       return retval;
+}
+
+/* Create a socket and connect to Security Server */
+int connect_to_server(int *fd)
+{
+       struct sockaddr_un clientaddr;
+       int client_len = 0, localsockfd, ret, flags;
+       *fd = -1;
+
+       /* Create a socket */
+       localsockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+       if(localsockfd < 0)
+       {
+               SEC_SVR_DBG("%s", "Error on socket()");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       /* Make socket as non blocking */
+       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
+                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+               close(localsockfd);
+               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       bzero(&clientaddr, sizeof(clientaddr));
+       clientaddr.sun_family = AF_UNIX;
+       strncpy(clientaddr.sun_path, SECURITY_SERVER_SOCK_PATH, strlen(SECURITY_SERVER_SOCK_PATH));
+       clientaddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
+       client_len = sizeof(clientaddr);
+
+       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
+       if( ret < 0)
+       {
+               if(errno == EINPROGRESS)
+               {
+                       SEC_SVR_DBG("%s", "Connection is in progress");
+                       ret = check_socket_poll(localsockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+                       if(ret == SECURITY_SERVER_ERROR_POLL)
+                       {
+                               SEC_SVR_DBG("%s", "poll() error");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+                       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+                       {
+                               SEC_SVR_DBG("%s", "poll() timeout");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+                       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
+                       if(ret < 0)
+                       {
+                               SEC_SVR_DBG("%s", "connection failed");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+               }
+               else
+               {
+                       SEC_SVR_DBG("%s", "Connection failed");
+                       close(localsockfd);
+                       return SECURITY_SERVER_ERROR_SOCKET;
+               }
+       }
+
+       /* Authenticate the peer is actually security server */
+       ret = authenticate_server(localsockfd);
+       if(ret  != SECURITY_SERVER_SUCCESS)
+       {
+               close(localsockfd);
+               SEC_SVR_DBG("Authentication failed. %d", ret);
+               return ret;
+       }
+       *fd = localsockfd;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Accept a new client connection */
+int accept_client(int server_sockfd)
+{
+       /* Call poll() to wait for socket connection */
+       int retval, localsockfd;
+       struct sockaddr_un clientaddr;
+       unsigned int client_len;
+
+       client_len = sizeof(clientaddr);
+
+       /* Check poll */
+       retval = check_socket_poll(server_sockfd, POLLIN, SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Error on polling");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       /* Timed out */
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               /*SEC_SVR_DBG("%s", "accept() timeout");*/
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       localsockfd = accept(server_sockfd,
+                       (struct sockaddr *)&clientaddr,
+                       &client_len);
+
+       if(localsockfd < 0)
+       {
+               SEC_SVR_DBG("Cannot accept client. errno=%d", errno);
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+       return localsockfd;
+}
+
+/* Minimal check of request packet */
+int validate_header(basic_header hdr)
+{
+       if(hdr.version != SECURITY_SERVER_MSG_VERSION)
+               return SECURITY_SERVER_ERROR_BAD_REQUEST;
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send generic response packet to client
+ *
+ * Generic Response Packet Format
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+|---------------------------------------------------------------|
+| version=0x01  |  Message ID   |Message Length (without header)|
+|---------------------------------------------------------------|
+|  return code  |
+-----------------
+*/
+int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code)
+{
+       response_header hdr;
+       int size;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = msgid;
+       hdr.basic_hdr.msg_len = 0;
+       hdr.return_code = return_code;
+
+       /* Check poll */
+       size = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(size == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(size == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       size = write(sockfd, &hdr, sizeof(hdr));
+
+       if(size < sizeof(hdr))
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie response to client
+ *
+ * Get Cookie response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ *  |---------------------------------------------------------------|
+ *  | version=0x01  |MessageID=0x02 |       Message Length =20      |
+ *  |---------------------------------------------------------------|
+ *  |  return code  |                                               |
+ *  -----------------                                               |
+ *  |                 cookie (20 bytes)                             |
+ *  |---------------------------------------------------------------|
+*/
+int send_cookie(int sockfd, unsigned char *cookie)
+{
+       response_header hdr;
+       unsigned char msg[SECURITY_SERVER_COOKIE_LEN + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE;
+       hdr.basic_hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       ret = write(sockfd, msg, sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN);
+       if(ret <  sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN)
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write: %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send Object name response *
+ * Get Object name response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x06 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |                                               |
+ * -----------------                                               |
+ * |                 object name                                   |
+ * |---------------------------------------------------------------|
+*/
+int send_object_name(int sockfd, char *obj)
+{
+       response_header hdr;
+       unsigned char msg[strlen(obj) + sizeof(hdr)];
+       int ret;
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = 0x06;
+       hdr.basic_hdr.msg_len = strlen(obj);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), obj, strlen(obj));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       ret = write(sockfd, msg, sizeof(hdr) + strlen(obj));
+       if(ret <  sizeof(hdr) + strlen(obj))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write: %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send GID response to client
+ *
+ * Get GID response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x08 |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |  return code  |           gid (first 3 words)                 |
+ * |---------------------------------------------------------------|
+ * |gid(last word) |
+ * |---------------|
+*/
+int send_gid(int sockfd, int gid)
+{
+       response_header hdr;
+       unsigned char msg[sizeof(gid) + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_RESPONSE;
+       hdr.basic_hdr.msg_len = sizeof(gid);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), &gid, sizeof(gid));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, sizeof(hdr) + sizeof(gid));
+       if(ret <  sizeof(hdr) + sizeof(gid))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send PID response to client
+ *
+ * Get PID response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0a |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |  return code  |           pid (first 3 words)                 |
+ * |---------------------------------------------------------------|
+ * |pid(last word) |
+ * |---------------|
+*/
+int send_pid(int sockfd, int pid)
+{
+       response_header hdr;
+       unsigned char msg[sizeof(pid) + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_RESPONSE;
+       hdr.basic_hdr.msg_len = sizeof(pid);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), &pid, sizeof(pid));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, sizeof(hdr) + sizeof(pid));
+       if(ret <  sizeof(hdr) + sizeof(pid))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send SMACK label to client with lenght N
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x1e |  Message Length = SMACK_LABEL_LEN + 1
+ * |---------------------------------------------------------------|
+ * |  return code  |           SMACK label byte 0                  |
+ * |---------------------------------------------------------------|
+ * |                      ..................                       |
+ * |---------------------------------------------------------------|
+ * |                      SMACK label byte N                       |
+ * |---------------------------------------------------------------|
+*/
+int send_smack(int sockfd, char * label)
+{
+       response_header hdr;
+    //added 1 to the size is for NULL terminating label
+    int LABEL_SIZE = SMACK_LABEL_LEN + 1;
+    int PACKET_SIZE = sizeof(hdr) + LABEL_SIZE;
+       unsigned char msg[PACKET_SIZE];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE;
+       hdr.basic_hdr.msg_len = LABEL_SIZE;
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), label, LABEL_SIZE);
+    memset(msg + sizeof(hdr) + SMACK_LABEL_LEN, 0x00, 1); //adding NULL ad the label end
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, PACKET_SIZE);
+       if(ret <  PACKET_SIZE)
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send Check password response to client
+ *
+ * Check password response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |   MessageID   |       Message Length = 12     |
+ * |---------------------------------------------------------------|
+ * |  return code  |           attempts (first 3 words)            |
+ * |---------------------------------------------------------------|
+ * |attempts(rest) |          max_attempts (first 3 words)         |
+ * |---------------|-----------------------------------------------|
+ * | max_attempts  |          expire_in_days (first 3 words)       |
+ * |---------------------------------------------------------------|
+ * |expire_in_days |
+ * |----------------
+ */
+int send_pwd_response(const int sockfd,
+       const unsigned char msg_id,
+       const unsigned char return_code,
+       const unsigned int current_attempts,
+       const unsigned int max_attempts,
+       const unsigned int expire_time)
+{
+       response_header hdr;
+       unsigned int expire_secs;
+       unsigned char msg[sizeof(hdr) + sizeof(current_attempts) + sizeof(max_attempts) + sizeof(expire_secs)];
+       int ret, ptr = 0;
+
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = msg_id;
+       hdr.basic_hdr.msg_len = sizeof(unsigned int) * 3;
+       hdr.return_code = return_code;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       ptr += sizeof(hdr);
+       memcpy(msg + ptr, &current_attempts, sizeof(current_attempts));
+       ptr += sizeof(current_attempts);
+       memcpy(msg + ptr, &max_attempts, sizeof(max_attempts));
+       ptr += sizeof(max_attempts);
+       memcpy(msg + ptr, &expire_time, sizeof(expire_time));
+       ptr += sizeof(expire_time);
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Server: poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "Server: poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, ptr);
+       if(ret <  ptr)
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Server: ERROR on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie request packet to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x01 |       Message Length = 0      |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_request(int sock_fd)
+{
+       basic_header hdr;
+       int retval;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send GID request message to security server
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x07 |   Message Length = variable   |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                   Object name (variable)                      |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_gid_request(int sock_fd, const char* object)
+{
+       basic_header hdr;
+       int retval = 0, send_len = 0;
+       unsigned char *buf = NULL;
+
+       if(strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME)
+       {
+               /* Object name is too big*/
+               SEC_SVR_DBG("Object name is too big %dbytes", strlen(object));
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_REQUEST;
+       hdr.msg_len = strlen(object);
+
+       send_len = sizeof(hdr) + strlen(object);
+
+       buf = malloc(send_len);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "out of memory");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), object, strlen(object));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       retval = write(sock_fd, buf, send_len);
+       if(retval < send_len)
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d. errno=%d, sockfd=%d", retval, errno, sock_fd);
+               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       else
+               retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+
+       return retval;
+}
+
+/* Send object name request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x05 |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |                               gid                             |
+ * |---------------------------------------------------------------|
+ */
+int send_object_name_request(int sock_fd, int gid)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + sizeof(gid)];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST;
+       hdr.msg_len = sizeof(gid);
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), &gid, sizeof(gid));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send privilege check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x03 |      Message Length = 24      |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                      Cookie (20bytes)                         |
+ * |                                                               |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                            GID                                |
+ * |---------------------------------------------------------------|
+ */
+int send_privilege_check_request(int sock_fd, const char*cookie, int gid)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + sizeof(gid) + SECURITY_SERVER_COOKIE_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST;
+       hdr.msg_len = sizeof(gid) + SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &gid, sizeof(gid));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int send_privilege_check_new_request(int sock_fd,
+                                     const char *cookie,
+                                     const char *object,
+                                     const char *access_rights)
+{
+       basic_header hdr;
+       int retval;
+        int olen, alen;
+        int size;
+
+        olen = strlen(object);
+        alen = strlen(access_rights);
+        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
+        {
+                return SECURITY_SERVER_ERROR_INPUT_PARAM;
+        }
+
+       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN +
+                          2*sizeof(int) + MAX_OBJECT_LABEL_LEN + MAX_MODE_STR_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &olen, sizeof(int));
+        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + sizeof(int),
+               &alen, sizeof(int));
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int), object, olen);
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen,
+               access_rights, alen);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+        size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
+       /* Send to server */
+       retval = write(sock_fd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send SMACK request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x1d |      Message Length = 20      |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                      Cookie (20bytes)                         |
+ * |                                                               |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_smack_request(int sock_fd, const char * cookie)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send PID check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x09 |      Message Length = 20      |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                      Cookie (20bytes)                         |
+ * |                                                               |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_pid_request(int sock_fd, const char*cookie)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+
+/* Send debug tool launch request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0b |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                        total # of args                        |
+ * |---------------------------------------------------------------|
+ * |                        1st argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            1st argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                        2nd argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            2nd argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                                ...                            |
+ * |---------------------------------------------------------------|
+ * |                        nth argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            nth argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_launch_tool_request(int sock_fd, int argc, const char **argv)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr, i, tempnum;
+       unsigned char *buf = NULL;
+
+       for (i=0;i<argc;i++)
+       {
+               if(argv[i] == NULL)
+               {
+                       SEC_SVR_DBG("Error: %dth argv is NULL", i);
+                       return SECURITY_SERVER_ERROR_INPUT_PARAM;
+               }
+               total_length += strlen(argv[i]);
+       }
+
+       if(total_length < 1)
+       {
+               SEC_SVR_DBG("Error: There is a problem in argv. [%d]", total_length);
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+       total_length += sizeof(hdr) + sizeof(int) +(argc * sizeof(int));
+
+       if(total_length > 0xffff)
+       {
+               SEC_SVR_DBG("Buffer overflow. too big payload. [%d]", total_length);
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &argc, sizeof(int));
+       ptr += sizeof(hdr);
+
+       /* Assemple each argv length and value */
+       for(i=0;i<argc;i++)
+       {
+               tempnum = strlen(argv[i]);
+               memcpy(buf + ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf + ptr, argv[i], tempnum);
+               ptr += tempnum;
+       }
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send validate password request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0d |       Message Length          |
+ * |---------------------------------------------------------------|
+ */
+int send_valid_pwd_request(int sock_fd)
+{
+       basic_header hdr;
+       int retval;
+
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       return retval;
+}
+
+/* Send password set request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  cur_pwd_len  |  new_pwd_len  |                               |
+ * |--------------------------------                               |
+ * |                            cur pwd                            |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            new pwd                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         max attempts                          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_request(int sock_fd,
+                       const char*cur_pwd,
+                       const char*new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, cur_pwd_len, new_pwd_len;
+
+       if(cur_pwd == NULL)
+               cur_pwd_len = 0;
+       else
+               cur_pwd_len = strlen(cur_pwd);
+       new_pwd_len = strlen(new_pwd);
+
+       total_length += sizeof(hdr) + sizeof(char) + sizeof(char) + cur_pwd_len
+               + new_pwd_len + sizeof(unsigned int) + sizeof(unsigned int);
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &cur_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       if(cur_pwd != NULL)
+       {
+               memcpy(buf + ptr, cur_pwd, cur_pwd_len);
+               ptr += cur_pwd_len;
+       }
+       memcpy(buf + ptr, new_pwd, new_pwd_len);
+       ptr += new_pwd_len;
+       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+       ptr += sizeof(unsigned int);
+       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password validity change request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days)
+{
+    basic_header hdr;
+    int retval, total_length = 0, ptr;
+    unsigned char *buf = NULL;
+
+    total_length = sizeof(hdr) + sizeof(unsigned int);
+
+    buf = malloc(total_length);
+    if(buf == NULL)
+    {
+        SEC_SVR_DBG("%s", "Error: failed to malloc()");
+        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+    }
+
+    /* Assemble header */
+    hdr.version = SECURITY_SERVER_MSG_VERSION;
+    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST;
+    hdr.msg_len = (unsigned short)total_length;
+    memcpy(buf, &hdr, sizeof(hdr));
+    ptr = sizeof(hdr);
+    memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+    /* Check poll */
+    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+    if(retval == SECURITY_SERVER_ERROR_POLL)
+    {
+        SEC_SVR_DBG("%s", "poll() error");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+
+    }
+    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+    {
+        SEC_SVR_DBG("%s", "poll() timeout");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+
+    /* Send to server */
+    retval = write(sock_fd, buf, total_length);
+    if(retval < sizeof(buf))
+    {
+        /* Write error */
+        SEC_SVR_DBG("Error on write(): %d", retval);
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+    retval = SECURITY_SERVER_SUCCESS;
+
+error:
+    if(buf != NULL)
+        free(buf);
+    return retval;
+}
+
+/* Send password max challenge request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                         max challenge                         |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge)
+{
+    basic_header hdr;
+    int retval, total_length = 0, ptr;
+    unsigned char *buf = NULL;
+
+    total_length = sizeof(hdr) + sizeof(unsigned int);
+
+    buf = malloc(total_length);
+    if(buf == NULL)
+    {
+        SEC_SVR_DBG("%s", "Error: failed to malloc()");
+        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+    }
+
+    /* Assemble header */
+    hdr.version = SECURITY_SERVER_MSG_VERSION;
+    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST;
+    hdr.msg_len = (unsigned short)total_length;
+    memcpy(buf, &hdr, sizeof(hdr));
+    ptr = sizeof(hdr);
+    memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+
+    /* Check poll */
+    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+    if(retval == SECURITY_SERVER_ERROR_POLL)
+    {
+        SEC_SVR_DBG("%s", "poll() error");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+
+    }
+    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+    {
+        SEC_SVR_DBG("%s", "poll() timeout");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+
+    /* Send to server */
+    retval = write(sock_fd, buf, total_length);
+    if(retval < sizeof(buf))
+    {
+        /* Write error */
+        SEC_SVR_DBG("Error on write(): %d", retval);
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+    retval = SECURITY_SERVER_SUCCESS;
+
+error:
+    if(buf != NULL)
+        free(buf);
+    return retval;
+}
+
+/* Send password reset request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x11 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  new_pwd_len  |                                               |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            new pwd                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         max attempts                          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_reset_pwd_request(int sock_fd,
+                       const char*new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, new_pwd_len;
+
+       new_pwd_len = strlen(new_pwd);
+
+       total_length += sizeof(hdr) + sizeof(char) + new_pwd_len + sizeof(unsigned int) +
+               sizeof(unsigned int);
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, new_pwd, new_pwd_len);
+       ptr += new_pwd_len;
+       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+       ptr += sizeof(unsigned int);
+       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x13 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * | challenge_len |                                               |
+ * |---------------                                                |
+ * |                          challenge                            |
+ * |---------------------------------------------------------------|
+ */
+int send_chk_pwd_request(int sock_fd, const char*challenge)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, challenge_len;
+
+       challenge_len = strlen(challenge);
+
+       total_length += sizeof(hdr) + sizeof(char) + challenge_len;
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &challenge_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, challenge, challenge_len);
+       ptr += sizeof(char);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password history set request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x15 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * | challenge_len |
+ * |----------------
+ */
+int send_set_pwd_history_request(int sock_fd, int num)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char history;
+       unsigned char buf[sizeof(hdr) + sizeof(history)];
+
+       total_length = sizeof(hdr) + sizeof(char);
+       history = (unsigned char) num;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &history, sizeof(char));
+       ptr += sizeof(char);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, ptr);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       return retval;
+}
+
+/* Receive request header */
+int recv_hdr(int client_sockfd, basic_header *basic_hdr)
+{
+       int retval;
+
+       /* Check poll */
+       retval = check_socket_poll(client_sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       /* Receive request header first */
+       retval = read(client_sockfd, basic_hdr, sizeof(basic_header));
+       if(retval < sizeof(basic_header))
+       {
+               SEC_SVR_DBG("read failed. closing socket %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Validate header */
+       retval = validate_header(*basic_hdr);
+       return retval;
+}
+
+
+/* Receive check privilege request packet body */
+int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege)
+{
+       int retval;
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, requested_privilege, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("privilege size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive check privilege request packet body (new mode)*/
+int recv_check_privilege_new_request(int sockfd,
+                                     unsigned char *requested_cookie,
+                                     char *object_label,
+                                     char *access_rights)
+{
+       int retval;
+        int olen, alen;
+
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, &olen, sizeof(int));
+       if(retval < sizeof(int) || olen < 0 || olen > MAX_OBJECT_LABEL_LEN)
+       {
+               SEC_SVR_DBG("error reading object_label len: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, &alen, sizeof(int));
+       if(retval < sizeof(int) || alen < 0 || alen > MAX_MODE_STR_LEN)
+       {
+               SEC_SVR_DBG("error reading access_rights len: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, object_label, olen);
+       if(retval < olen)
+       {
+               SEC_SVR_DBG("error reading object_label: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+        object_label[olen] = '\0';
+
+       retval = read(sockfd, access_rights, olen);
+       if(retval < alen)
+       {
+               SEC_SVR_DBG("error reading access_rights: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+        access_rights[alen] = '\0';
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive pid request packet body */
+int recv_pid_request(int sockfd, unsigned char *requested_cookie)
+{
+       int retval;
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* receiving cookie from package */
+int recv_smack_request(int sockfd, unsigned char *requested_cookie)
+{
+       int retval;
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive pid request packet body */
+int recv_launch_tool_request(int sockfd, int argc, char *argv[])
+{
+       int retval, i, argv_len;
+
+       argv[0] = malloc(strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1);
+       strncpy(argv[0], SECURITY_SERVER_DEBUG_TOOL_PATH, (strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1));
+
+       for(i=1;i<argc;i++)
+       {
+               retval = read(sockfd, &argv_len, sizeof(int));
+               if(retval < sizeof(int))
+               {
+                       SEC_SVR_DBG("Error: argv length recieve failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+
+               if(argv_len <= 0 || argv_len >= INT_MAX)
+               {
+                       SEC_SVR_DBG("Error: argv length out of boundaries");
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+
+               argv[i] = malloc(argv_len + 1);
+               if(argv[i] == NULL)
+               {
+                       SEC_SVR_DBG("Error: malloc() failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               }
+
+               memset(argv[i], 0x00, argv_len + 1);
+               retval = read(sockfd, argv[i], argv_len);
+               if(retval < argv_len)
+               {
+                       SEC_SVR_DBG("Error: argv recieve failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+       }
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_generic_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Client: poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "Client: poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, hdr, sizeof(response_header));
+       if(retval < sizeof(response_header) )
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: return code is not success: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_get_gid_response(int sockfd, response_header *hdr, int *gid)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, gid, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size)
+{
+       int retval;
+       char *local_obj_name = NULL;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Read response */
+       retval = read(sockfd, hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("cannot recv respons: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr->return_code == SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               if(max_object_size < hdr->basic_hdr.msg_len)
+               {
+                       SEC_SVR_DBG("Object name is too small need %d bytes, but %d bytes", hdr->basic_hdr.msg_len, max_object_size);
+                       return SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+               }
+               if(hdr->basic_hdr.msg_len > SECURITY_SERVER_MAX_OBJ_NAME)
+               {
+                       SEC_SVR_DBG("Received object name is too big. %d", hdr->basic_hdr.msg_len);
+                       return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+
+               local_obj_name = malloc(hdr->basic_hdr.msg_len + 1);
+               if(local_obj_name == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Out of memory error");
+                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               }
+
+               retval = read(sockfd, local_obj_name, hdr->basic_hdr.msg_len);
+               if(retval < (hdr->basic_hdr.msg_len))
+               {
+                       /* Error on socket */
+                       SEC_SVR_DBG("read() failed: %d", retval);
+                       if(local_obj_name != NULL)
+                               free(local_obj_name);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+               memcpy(object, local_obj_name, hdr->basic_hdr.msg_len);
+               object[hdr->basic_hdr.msg_len] = 0;
+               retval = SECURITY_SERVER_SUCCESS;
+       }
+       else
+       {
+               SEC_SVR_DBG("Error received. return code: %d", hdr->return_code);
+               retval = return_code_to_error_code(hdr->return_code);
+               return retval;
+       }
+
+       if(local_obj_name != NULL)
+               free(local_obj_name);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_cookie(int sockfd, response_header *hdr, char *cookie)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("read() failed: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_privilege_check_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
+                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
+       {
+               SEC_SVR_DBG("response error: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_privilege_check_new_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
+                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
+       {
+               SEC_SVR_DBG("response error: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_smack_response(int sockfd, response_header *hdr, char * label)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, label, SMACK_LABEL_LEN + 1);
+       if(retval < sizeof(int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_pid_response(int sockfd, response_header *hdr, int *pid)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, pid, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_pwd_response(int sockfd, response_header *hdr,
+       unsigned int *current_attempts,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int retval;
+       *current_attempts = 0;
+       *max_attempts = 0;
+       *valid_secs = 0;
+
+       retval = recv_generic_response(sockfd, hdr);
+
+       switch(retval)
+       {
+               case SECURITY_SERVER_ERROR_PASSWORD_EXIST:
+               case SECURITY_SERVER_ERROR_NO_PASSWORD:
+               case SECURITY_SERVER_ERROR_PASSWORD_MISMATCH:
+               case SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER:
+               case SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+               case SECURITY_SERVER_ERROR_PASSWORD_EXPIRED:
+               case SECURITY_SERVER_ERROR_PASSWORD_REUSED:
+               case SECURITY_SERVER_SUCCESS:
+                       break;
+               default:
+                       return return_code_to_error_code(hdr->return_code);
+       }
+
+       retval = read(sockfd, current_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       retval = read(sockfd, max_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       retval = read(sockfd, valid_secs, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+    //if come here there were no errors
+    return SECURITY_SERVER_SUCCESS;
+}
+
+/* Authenticate client application *
+ * Currently it only gets peer's credential information only *
+ * If we need, we can extend in the futer */
+int authenticate_client_application(int sockfd, int *pid, int *uid)
+{
+       int retval = 0;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "getsockopt failed");
+               *pid = 0;
+               goto error;
+       }
+       *pid = cr.pid;
+       *uid = cr.uid;
+
+       /* Authenticate client that it's real client application */
+       /* TBA */
+
+error:
+       return retval;
+}
+
+/* Checking client is pre-defined middleware daemons *
+ * Check privilege API is only allowed to middleware daemons *
+ * cmd line list of middleware daemons are listed in
+ * /usr/share/security-server/mw-list */
+int search_middleware_cmdline(char *cmdline)
+{
+       FILE *fp = NULL;
+       int ret;
+       char middleware[SECURITY_SERVER_MAX_PATH_LEN];
+
+       /* Open the list file */
+       fp = fopen(SECURITY_SERVER_MIDDLEWARE_LIST_PATH, "r");
+       if(fp == NULL)
+       {
+               /* error on file */
+               SEC_SVR_DBG("%s", "Error oening mw-list file");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       /* Search each line */
+       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       while(fgets(middleware, SECURITY_SERVER_MAX_PATH_LEN, fp) != NULL)
+       {
+               if(strncmp(middleware, cmdline, strlen(middleware)-1) == 0)
+               {
+                       /* found */
+                       SEC_SVR_DBG("%s", "found matching cmd line");
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               }
+
+       }
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Authenticate the application is middleware daemon
+ * The middleware must run as root (or middleware user) and the cmd line must be
+ * pre listed for authentication to succeed */
+int authenticate_client_middleware(int sockfd, int *pid)
+{
+       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+       char *cmdline = NULL;
+       struct passwd pw, *ppw;
+       size_t buf_size;
+       char *buf;
+       static uid_t middleware_uid = 0;
+
+       *pid = 0;
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "Error on getsockopt");
+               goto error;
+       }
+
+       if (!middleware_uid)
+       {
+               buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
+               if (buf_size == -1)
+                       buf_size = 1024;
+
+               buf = malloc(buf_size);
+
+               /* This test isn't essential, skip it in case of error */
+               if (buf) {
+                       if (getpwnam_r(SECURITY_SERVER_MIDDLEWARE_USER, &pw, buf, buf_size, &ppw) == 0 && ppw)
+                               middleware_uid = pw.pw_uid;
+
+                       free(buf);
+               }
+       }
+
+       /* Middleware services need to run as root or middleware/app user */
+       if(cr.uid != 0 && cr.uid != middleware_uid)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = read_cmdline_from_proc(cr.pid);
+       if(cmdline  == NULL)
+       {
+               /* It's weired. no file in proc file system, */
+               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
+               goto error;
+       }
+
+       /* Search cmdline of the peer that is really middleware executable */
+       retval = search_middleware_cmdline(cmdline);
+       *pid = cr.pid;
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+
+       return retval;
+}
+
+/* Authenticate the application is middleware daemon
+ * The middleware must run as root and the cmd line must be pre listed */
+int authenticate_developer_shell(int sockfd)
+{
+       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+       char *cmdline = NULL;
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "Error on getsockopt");
+               goto error;
+       }
+
+       /* All middlewares will run as root */
+       if(cr.uid != SECURITY_SERVER_DEVELOPER_UID)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = read_cmdline_from_proc(cr.pid);
+       if(cmdline  == NULL)
+       {
+               /* It's weired. no file in proc file system, */
+               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
+               goto error;
+       }
+
+       /* Search cmdline of the peer that is really debug tool */
+       if(strncmp(cmdline, SECURITY_SERVER_DEBUG_TOOL_PATH, strlen(SECURITY_SERVER_DEBUG_TOOL_PATH)) != 0)
+       {
+               SEC_SVR_DBG("Error: Wrong cmdline [%s]", cmdline);
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+       SEC_SVR_DBG("%s", "Client Authenticated");
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+
+       return retval;
+}
+
+int free_argv(char **argv, int argc)
+{
+       int i;
+       if(argv == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot free NULL pointer");
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+       for (i=0;i<argc;i++)
+       {
+               if(argv[i] != NULL)
+                       free(argv[i]);
+       }
+       free(argv);
+       return SECURITY_SERVER_SUCCESS;
+}
+
diff --git a/src/daemon/dbus/org.tizen.SecurityDaemon.service b/src/daemon/dbus/org.tizen.SecurityDaemon.service
deleted file mode 100644 (file)
index 891bde6..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-[D-BUS Service]
-Name=org.tizen.SecurityDaemon
-Exec=/usr/bin/security-server
diff --git a/src/daemon/dbus/security_daemon_dbus_config.h b/src/daemon/dbus/security_daemon_dbus_config.h
deleted file mode 100644 (file)
index 30b8d90..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        security_daemon_dbus_config.h
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       This file contains security daemon DBus configuration.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
-
-#include <string>
-
-namespace WrtSecurity {
-
-struct SecurityDaemonConfig {
-    static const std::string OBJECT_PATH()
-    {
-        return "/org/tizen/SecurityDaemon";
-    }
-
-    static const std::string SERVICE_NAME()
-    {
-        return "org.tizen.SecurityDaemon";
-    }
-};
-
-} // namespace WrtSecurity
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
diff --git a/src/daemon/dbus/security_dbus_service.cpp b/src/daemon/dbus/security_dbus_service.cpp
deleted file mode 100644 (file)
index 7beba55..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        security_dbus_service.cpp
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
- * @version     1.0
- * @brief       This file contains implementation of security DBus service.
- */
-#include <dpl/log/log.h>
-#include <algorithm>
-#include <gio/gio.h>
-#include <dpl/exception.h>
-#include <dpl/dbus/interface.h>
-#include <dpl/dbus/connection.h>
-#include "security_dbus_service.h"
-#include "security_daemon_dbus_config.h"
-#include <ace_server_dbus_interface.h>
-#include <ocsp_server_dbus_interface.h>
-#include <popup_response_dbus_interface.h>
-
-
-void SecurityDBusService::start()
-{
-    LogDebug("SecurityDBusService starting");
-    m_connection = DPL::DBus::Connection::systemBus();
-    std::for_each(m_objects.begin(),
-                  m_objects.end(),
-                  [&m_connection] (const DPL::DBus::ObjectPtr& object)
-                  {
-                      m_connection->registerObject(object);
-                  });
-    m_connection->registerService(
-            WrtSecurity::SecurityDaemonConfig::SERVICE_NAME());
-}
-
-void SecurityDBusService::stop()
-{
-    LogDebug("SecurityDBusService stopping");
-    m_connection.reset();
-}
-
-void SecurityDBusService::initialize()
-{
-    LogDebug("SecurityDBusService initializing");
-    g_type_init();
-
-    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
-                 std::make_shared<RPC::AceServerDBusInterface>());
-    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
-                 std::make_shared<RPC::OcspServerDBusInterface>());
-    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
-                 std::make_shared<RPC::PopupResponseDBusInterface>());
-}
-
-void SecurityDBusService::addInterface(const std::string& objectPath,
-                                       const InterfaceDispatcherPtr& dispatcher)
-{
-    auto ifaces =
-        DPL::DBus::Interface::fromXMLString(dispatcher->getXmlSignature());
-    if (ifaces.empty())
-    {
-        ThrowMsg(DPL::Exception, "No interface description.");
-    }
-
-    auto iface = ifaces.at(0);
-    iface->setDispatcher(dispatcher.get());
-
-    m_dispatchers.push_back(dispatcher);
-    m_objects.push_back(DPL::DBus::Object::create(objectPath, iface));
-}
-
-void SecurityDBusService::deinitialize()
-{
-    LogDebug("SecurityDBusService deinitializing");
-    m_objects.clear();
-    m_dispatchers.clear();
-}
-
-#ifdef DBUS_CONNECTION
-DAEMON_REGISTER_SERVICE_MODULE(SecurityDBusService)
-#endif //DBUS_CONNECTION
diff --git a/src/daemon/dbus/security_dbus_service.h b/src/daemon/dbus/security_dbus_service.h
deleted file mode 100644 (file)
index 82fd627..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        security_dbus_service.h
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
- * @version     1.0
- * @brief       This file contains definitions of security DBus service.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
-#define WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
-
-#include <memory>
-#include <vector>
-#include <dpl/dbus/connection.h>
-#include <dpl/dbus/object.h>
-#include <dpl/dbus/dispatcher.h>
-#include <dpl/dbus/dbus_interface_dispatcher.h>
-#include <security_daemon.h>
-
-class SecurityDBusService : public SecurityDaemon::DaemonService {
-private:
-    virtual void initialize();
-    virtual void start();
-    virtual void stop();
-    virtual void deinitialize();
-
-private:
-    typedef std::shared_ptr<DPL::DBus::InterfaceDispatcher> InterfaceDispatcherPtr;
-    typedef std::shared_ptr<DPL::DBus::Dispatcher> DispatcherPtr;
-
-    void addInterface(const std::string& objectPath,
-                      const InterfaceDispatcherPtr& dispatcher);
-
-    DPL::DBus::ConnectionPtr m_connection;
-    std::vector<DPL::DBus::ObjectPtr> m_objects;
-    std::vector<DispatcherPtr> m_dispatchers;
-};
-
-#endif // WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
diff --git a/src/daemon/security_daemon.cpp b/src/daemon/security_daemon.cpp
deleted file mode 100644 (file)
index 7f93e4f..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        security_daemon.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This is implementation file of Security Daemon
- */
-
-#include "security_daemon.h"
-
-#include <dpl/assert.h>
-#include <dpl/foreach.h>
-#include <dpl/log/log.h>
-
-#include <dpl/framework_efl.h>
-
-#include <dpl/singleton_impl.h>
-IMPLEMENT_SINGLETON(SecurityDaemon::SecurityDaemon)
-
-#include <ace-dao-rw/AceDAO.h>
-
-namespace SecurityDaemon {
-
-//This is declared not in SecurityDaemon class, so no Ecore.h is needed there.
-static Ecore_Event_Handler *g_exitHandler;
-static Eina_Bool exitHandler(void */*data*/, int /*type*/, void */*event*/)
-{
-    auto& daemon = SecurityDaemonSingleton::Instance();
-    daemon.terminate(0);
-
-    return ECORE_CALLBACK_CANCEL;
-}
-
-SecurityDaemon::SecurityDaemon() :
-    m_initialized(false),
-    m_terminating(false),
-    m_returnValue(0)
-{
-}
-
-void SecurityDaemon::initialize(int& /*argc*/, char** /*argv*/)
-{
-    DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON");
-    LogDebug("Initializing");
-    Assert(!m_initialized && "Already Initialized");
-
-    g_exitHandler = ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT,
-                                            &exitHandler,
-                                            NULL);
-
-    DatabaseService::initialize();
-    FOREACH (service, m_servicesList) {
-        (*service)->initialize();
-    }
-    m_initialized = true;
-    LogDebug("Initialized");
-}
-
-int SecurityDaemon::execute()
-{
-    Assert(m_initialized && "Not Initialized");
-    LogDebug("Starting execute");
-    FOREACH (service, m_servicesList) {
-        (*service)->start();
-    }
-    ecore_main_loop_begin();
-    return m_returnValue;
-}
-
-void SecurityDaemon::terminate(int returnValue)
-{
-    Assert(m_initialized && "Not Initialized");
-    Assert(!m_terminating && "Already terminating");
-    LogDebug("Terminating");
-
-    ecore_event_handler_del(g_exitHandler);
-
-    m_returnValue = returnValue;
-    m_terminating = true;
-
-    FOREACH (service, m_servicesList) {
-        (*service)->stop();
-    }
-
-    ecore_main_loop_quit();
-}
-
-void SecurityDaemon::shutdown()
-{
-    LogDebug("Shutdown");
-    Assert(m_initialized && "Not Initialized");
-    Assert(m_terminating && "Not terminated");
-
-    DatabaseService::deinitialize();
-    FOREACH (service, m_servicesList) {
-        (*service)->deinitialize();
-    }
-
-    m_initialized = false;
-}
-
-namespace DatabaseService {
-
-void initialize(void)
-{
-    LogDebug("Ace/Wrt database services initializing...");
-    AceDB::AceDAO::attachToThreadRW();
-}
-
-void deinitialize(void)
-{
-    LogDebug("Ace/Wrt database services deinitializing...");
-    AceDB::AceDAO::detachFromThread();
-}
-
-} //namespace DatabaseService
-
-} //namespace SecurityDaemon
diff --git a/src/daemon/security_daemon.h b/src/daemon/security_daemon.h
deleted file mode 100644 (file)
index a98f309..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        security_daemon.h
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This is header file of Security Daemon
- */
-
-#ifndef WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
-#define WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
-
-#include <utility>
-#include <memory>
-#include <list>
-#include <dpl/noncopyable.h>
-#include <dpl/singleton.h>
-#include <dpl/assert.h>
-
-
-namespace SecurityDaemon {
-
-class DaemonService : DPL::Noncopyable {
-  public:
-    virtual void initialize() = 0;
-    virtual void start() = 0;
-    virtual void stop() = 0;
-    virtual void deinitialize() = 0;
-};
-
-class SecurityDaemon : DPL::Noncopyable
-{
-  public:
-    SecurityDaemon();
-
-    void initialize(int& argc, char** argv);
-    int execute();
-    void terminate(int returnValue = 0);
-
-    template<typename ServiceType, typename ...Args>
-    void registerService(Args&&... args)
-    {
-        Assert(!m_initialized && "Too late for registration");
-
-        m_servicesList.push_back(
-                std::make_shared<ServiceType>(std::forward<Args>(args)...));
-    }
-
-    void shutdown();
-
-  private:
-    bool m_initialized;
-    bool m_terminating;
-    int m_returnValue;
-    typedef std::list<std::shared_ptr<DaemonService>> DaemonServiceList;
-    DaemonServiceList m_servicesList;
-};
-
-namespace DatabaseService {
-    void initialize();
-    void deinitialize();
-};
-
-} //namespace SecurityDaemon
-
-typedef DPL::Singleton<SecurityDaemon::SecurityDaemon> SecurityDaemonSingleton;
-
-#define DAEMON_REGISTER_SERVICE_MODULE(Type)                                \
-    namespace {                                                             \
-        static int initializeModule();                                      \
-        static int initializeModuleHelper = initializeModule();             \
-        int initializeModule()                                              \
-        {                                                                   \
-            (void)initializeModuleHelper;                                   \
-            SecurityDaemonSingleton::Instance().registerService<Type>();    \
-            return 0;                                                       \
-        }                                                                   \
-    }
-
-
-#endif /* WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H */
diff --git a/src/daemon/sockets/api/callback_api.h b/src/daemon/sockets/api/callback_api.h
deleted file mode 100644 (file)
index ddda4d4..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        callback_api.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       This header provides types and exceptions required for security service callbacks
- */
-
-#ifndef CALLBACK_API_H_
-#define CALLBACK_API_H_
-
-#include <dpl/exception.h>
-
-typedef void (*socketServerCallback) (SocketConnection * connector);
-
-typedef bool (*securityCheck) (int socketfd);
-
-namespace ServiceCallbackApi{
-
-    class Exception{
-    public:
-        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, ServiceCallbackException)
-    };
-
-}
-
-#endif /* CALLBACK_API_H_ */
diff --git a/src/daemon/sockets/security_daemon_socket_config.h b/src/daemon/sockets/security_daemon_socket_config.h
deleted file mode 100644 (file)
index 3d8b6f8..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        security_daemon_socket_config.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief
- */
-
-#ifndef SECURITY_DAEMON_SOCKET_CONFIG_H_
-#define SECURITY_DAEMON_SOCKET_CONFIG_H_
-
-#include <string>
-#include <signal.h>
-
-namespace WrtSecurity {
-
-struct SecurityDaemonSocketConfig {
-    static const std::string SERVER_ADDRESS()
-    {
-        return "/tmp/server";
-    }
-};
-
-} // namespace WrtSecurity
-#endif /* SECURITY_DAEMON_SOCKET_CONFIG_H_ */
diff --git a/src/daemon/sockets/security_socket_service.cpp b/src/daemon/sockets/security_socket_service.cpp
deleted file mode 100644 (file)
index 689de1c..0000000
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        security_socket_service.cpp
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Implementation of socket server
- */
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sys/signalfd.h>
-#include <sys/select.h>
-#include <sys/stat.h>
-#include <signal.h>
-#include <fcntl.h>
-#include <cstring>
-#include <dpl/log/log.h>
-#include "ace_service_callbacks_api.h"
-#include "ocsp_service_callbacks_api.h"
-#include "popup_service_callbacks_api.h"
-#include "security_daemon_socket_config.h"
-#include "security_socket_service.h"
-
-#define TIMEOUT_SEC 0
-#define TIMEOUT_NSEC 100000000
-#define MAX_LISTEN 5
-#define SIGNAL_TO_CLOSE SIGUSR1
-
-void SecuritySocketService::throwWithErrnoMessage(const std::string& specificInfo){
-    LogError(specificInfo << " : " << strerror(errno));
-    ThrowMsg(DPL::Exception, specificInfo << " : " << strerror(errno));
-}
-
-void SecuritySocketService::registerServiceCallback(const std::string &interfaceName,
-                                                    const std::string &methodName,
-                                                    socketServerCallback callbackMethod,
-                                                    securityCheck securityMethod){
-    if(NULL == callbackMethod){
-        LogError("Null callback");
-        ThrowMsg(DPL::Exception, "Null callback");
-    }
-    if(interfaceName.empty() || methodName.empty()){
-        LogError("Interface and method name cannot be empty");
-        ThrowMsg(DPL::Exception, "Empty interface or method name");
-    }
-
-    auto serviceCallbackPtr = std::make_shared<ServiceCallback>(ServiceCallback(callbackMethod, securityMethod));
-    m_callbackMap[interfaceName][methodName] = serviceCallbackPtr;
-}
-
-void SecuritySocketService::addClientSocket(int clientSocket){
-    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
-    m_clientSocketList.push_back(clientSocket);
-}
-
-void SecuritySocketService::removeClientSocket(int clientSocket){
-    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
-    m_clientSocketList.remove(clientSocket);
-}
-
-bool SecuritySocketService::popClientSocket(int * clientSocket){
-    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
-    if(m_clientSocketList.empty())
-        return false;
-    *clientSocket = m_clientSocketList.front();
-    m_clientSocketList.pop_front();
-    return true;
-}
-
-void SecuritySocketService::initialize(){
-
-    LogInfo("Initializing...");
-    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
-    m_signalToClose = SIGNAL_TO_CLOSE;
-
-    //registering Ace callbacks
-    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
-                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
-                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
-
-    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
-                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().first,
-                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().second);
-
-    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
-                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().first,
-                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().second);
-    LogInfo("Registered Ace callbacks");
-
-    //registering Ocsp callbacks
-    registerServiceCallback(WrtSecurity::OcspServerApi::INTERFACE_NAME(),
-                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
-                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
-    LogInfo("Registered Ocsp callbacks");
-
-    //registering Popup callbacks
-    registerServiceCallback(WrtSecurity::PopupServerApi::INTERFACE_NAME(),
-                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().first,
-                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().second);
-    LogInfo("Registered Popup callbacks");
-
-    if(-1 == (m_listenFd = socket(AF_UNIX, SOCK_STREAM, 0))){
-        throwWithErrnoMessage("socket()");
-    }
-    LogInfo("Server socket created");
-
-    //socket needs to be nonblocking, because read can block after select
-    int flags;
-    if (-1 == (flags = fcntl(m_listenFd, F_GETFL, 0)))
-        flags = 0;
-    if(-1 == (fcntl(m_listenFd, F_SETFL, flags | O_NONBLOCK))){
-        throwWithErrnoMessage("fcntl");
-    }
-
-    sockaddr_un server_address;
-    bzero(&server_address, sizeof(server_address));
-    server_address.sun_family = AF_UNIX;
-    strcpy(server_address.sun_path, m_serverAddress.c_str());
-    unlink(server_address.sun_path);
-
-    mode_t socket_umask, original_umask;
-    socket_umask = 0;
-    original_umask = umask(socket_umask);
-
-    if(-1 == bind(m_listenFd, (struct sockaddr *)&server_address, SUN_LEN(&server_address))){
-        throwWithErrnoMessage("bind()");
-    }
-
-    umask(original_umask);
-
-    LogInfo("Initialized");
-}
-
-void SecuritySocketService::start(){
-
-    LogInfo("Starting...");
-    if(m_serverAddress.empty()){
-        LogError("Server not initialized");
-        ThrowMsg(DPL::Exception, "Server not initialized");
-    }
-
-    sigset_t sigset;
-    sigemptyset(&sigset);
-    if(-1 == sigaddset(&sigset, m_signalToClose)){
-        throwWithErrnoMessage("sigaddset()");
-    }
-    int returned_value;
-    if ((returned_value = pthread_sigmask(SIG_BLOCK, &sigset, NULL)) < 0) {
-        errno = returned_value;
-        throwWithErrnoMessage("pthread_sigmask()");
-    }
-
-    pthread_t mainThread;
-
-    if((returned_value = pthread_create(&mainThread, NULL, &serverThread, this)) < 0){
-        errno = returned_value;
-        throwWithErrnoMessage("pthread_create()");
-    }
-    m_mainThread = mainThread;
-
-    LogInfo("Started");
-}
-
-void * SecuritySocketService::serverThread(void * data){
-    pthread_detach(pthread_self());
-    SecuritySocketService &t = *static_cast<SecuritySocketService *>(data);
-    LogInfo("Running server main thread");
-    Try {
-        t.mainLoop();
-    } Catch (DPL::Exception) {
-        LogError("Socket server error. Exiting...");
-        return (void *)1;
-    }
-
-    return (void *)0;
-}
-
-
-void SecuritySocketService::mainLoop(){
-
-    if(listen(m_listenFd, MAX_LISTEN) == -1){
-        throwWithErrnoMessage("listen()");
-    }
-
-    //Settings to catch closing signal in select
-    int signal_fd;
-    sigset_t sigset;
-    if(-1 == (sigemptyset(&sigset))){
-        throwWithErrnoMessage("sigemptyset()");
-    }
-    if(-1 == (sigaddset(&sigset, m_signalToClose))) {
-        throwWithErrnoMessage("sigaddset()");
-    }
-    if((signal_fd = signalfd(-1, &sigset, 0)) < 0){
-        throwWithErrnoMessage("signalfd()");
-    }
-
-    //Setting descriptors for pselect
-    fd_set allset, rset;
-    int maxfd;
-    FD_ZERO(&allset);
-    FD_SET(m_listenFd, &allset);
-    FD_SET(signal_fd, &allset);
-    timespec timeout;
-    maxfd = (m_listenFd > signal_fd) ? (m_listenFd) : (signal_fd);
-    ++maxfd;
-    //this will block SIGPIPE for this thread and every thread created in it
-    //reason : from here on we don't won't to receive SIGPIPE on writing to closed socket
-    //instead of signal we want to receive error from write - hence blocking SIGPIPE
-    sigset_t set;
-    sigemptyset(&set);
-    sigaddset(&set, SIGPIPE);
-    pthread_sigmask(SIG_BLOCK, &set, NULL);
-
-    while(1){
-        timeout.tv_sec = TIMEOUT_SEC;
-        timeout.tv_nsec = TIMEOUT_NSEC;
-        rset = allset;
-        if(-1 == pselect(maxfd, &rset, NULL, NULL, &timeout, NULL)){
-            closeConnections();
-            throwWithErrnoMessage("pselect()");
-        }
-
-        if(FD_ISSET(signal_fd, &rset)){
-            LogInfo("Got signal to close");
-            signalfd_siginfo siginfo;
-            ssize_t res;
-            res = read(signal_fd, &siginfo, sizeof(siginfo));
-            if(res <= 0){
-                closeConnections();
-                throwWithErrnoMessage("read()");
-            }
-            if((size_t)res != sizeof(siginfo)){
-                closeConnections();
-                LogError("couldn't read whole siginfo");
-                ThrowMsg(DPL::Exception, "couldn't read whole siginfo");
-            }
-            if((int)siginfo.ssi_signo == m_signalToClose){
-                LogInfo("Server thread got signal to close");
-                closeConnections();
-                return;
-            } else {
-                LogInfo("Got not handled signal");
-            }
-        }
-        if(FD_ISSET(m_listenFd, &rset)){
-            int client_fd;
-            if(-1 == (client_fd = accept(m_listenFd, NULL, NULL))){
-                closeConnections();
-                throwWithErrnoMessage("accept()");
-            }
-            LogInfo("Got incoming connection");
-            Connection_Info * connection = new Connection_Info(client_fd, (void *)this);
-            int res;
-            pthread_t client_thread;
-            if((res = pthread_create(&client_thread, NULL, &connectionThread, connection)) < 0){
-                delete connection;
-                errno = res;
-                closeConnections();
-                throwWithErrnoMessage("pthread_create()");
-            }
-            addClientSocket(client_fd);
-        }
-    }
-}
-
-void * SecuritySocketService::connectionThread(void * data){
-    pthread_detach(pthread_self());
-    std::auto_ptr<Connection_Info> c (static_cast<Connection_Info *>(data));
-    SecuritySocketService &t = *static_cast<SecuritySocketService *>(c->data);
-    LogInfo("Starting connection thread");
-    Try {
-        t.connectionService(c->connfd);
-    } Catch (DPL::Exception){
-        LogError("Connection thread error : " << _rethrown_exception.DumpToString());
-        t.removeClientSocket(c->connfd);
-        close(c->connfd);
-        return (void*)1;
-    }
-    LogInfo("Client serviced");
-    return (void*)0;
-}
-
-void SecuritySocketService::connectionService(int fd){
-
-    SocketConnection connector = SocketConnection(fd);
-    std::string interfaceName, methodName;
-
-    Try {
-        connector.read(&interfaceName, &methodName);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection read error");
-        ReThrowMsg(DPL::Exception, "Socket Connection read error");
-    }
-
-    LogDebug("Got interface : " << interfaceName);
-    LogDebug("Got method : " << methodName);
-
-    if( m_callbackMap.find(interfaceName) == m_callbackMap.end()){
-        LogError("Unknown interface : " << interfaceName);
-        ThrowMsg(DPL::Exception, "Unknown interface : " << interfaceName);
-    }
-
-    if(m_callbackMap[interfaceName].find(methodName) == m_callbackMap[interfaceName].end()){
-        LogError("Unknown method : " << methodName);
-        ThrowMsg(DPL::Exception, "Unknown method");
-    }
-
-    if(m_callbackMap[interfaceName][methodName]->securityCallback != NULL){
-        if(!m_callbackMap[interfaceName][methodName]->securityCallback(fd)){
-            LogError("Security check returned false");
-            ThrowMsg(DPL::Exception, "Security check returned false");
-        }
-    }
-
-    LogInfo("Calling service");
-    Try{
-        m_callbackMap[interfaceName][methodName]->serviceCallback(&connector);
-    } Catch (ServiceCallbackApi::Exception::ServiceCallbackException){
-        LogError("Service callback error");
-        ReThrowMsg(DPL::Exception, "Service callback error");
-    }
-
-    LogInfo("Removing client");
-    removeClientSocket(fd);
-    close(fd);
-
-    LogInfo("Call served");
-
-}
-
-void SecuritySocketService::stop(){
-    LogInfo("Stopping");
-    if(-1 == close(m_listenFd))
-        if(errno != ENOTCONN)
-            throwWithErrnoMessage("close()");
-    int returned_value;
-    if((returned_value = pthread_kill(m_mainThread, m_signalToClose)) < 0){
-        errno = returned_value;
-        throwWithErrnoMessage("pthread_kill()");
-    }
-    pthread_join(m_mainThread, NULL);
-
-    LogInfo("Stopped");
-}
-
-void SecuritySocketService::closeConnections(){
-
-    int clientSocket;
-    LogInfo("Closing client sockets");
-    while(popClientSocket(&clientSocket)){
-        if(-1 == close(clientSocket)){
-            LogError("close() : " << strerror(errno));
-        }
-    }
-
-    LogInfo("Connections closed");
-}
-
-void SecuritySocketService::deinitialize(){
-    m_serverAddress.clear();
-
-    LogInfo("Deinitialized");
-
-}
-
-#ifdef SOCKET_CONNECTION
-DAEMON_REGISTER_SERVICE_MODULE(SecuritySocketService)
-#endif
diff --git a/src/daemon/sockets/security_socket_service.h b/src/daemon/sockets/security_socket_service.h
deleted file mode 100644 (file)
index 882d0e5..0000000
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        security_socket_service.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header of socket server class
- */
-
-#ifndef SECURITY_SOCKET_SERVICE_H_
-#define SECURITY_SOCKET_SERVICE_H_
-
-#include <map>
-#include <list>
-#include <memory>
-#include <mutex>
-#include <pthread.h>
-#include <security_daemon.h>
-#include <SocketConnection.h>
-#include <callback_api.h>
-
-class SecuritySocketService : public SecurityDaemon::DaemonService {
-
-private:
-
-  virtual void initialize();
-  virtual void start();
-  virtual void stop();
-  virtual void deinitialize();
-
-
-private:
-
-    //Function for registering callback with given interface and method name and possibly security check callback
-    void registerServiceCallback(const std::string& interfaceName,
-                                 const std::string& methodName,
-                                 socketServerCallback serviceCallback,
-                                 securityCheck securityCallback = NULL);
-    //Thread function for server
-    static void * serverThread(void *);
-    //Main function for server
-    void mainLoop();
-    //Thread function for connection serving
-    static void * connectionThread(void *);
-    //Main function for connection serving
-    void connectionService(int fd);
-    //closing all connections
-    void closeConnections();
-    //logs an error and throws an exception with message containing errno message
-    void throwWithErrnoMessage(const std::string &specificInfo);
-
-    //concurrency safe methods for client socket list - add, remove and pop (with returned value)
-    void addClientSocket(int clientThread);
-    void removeClientSocket(int clientThread);
-    bool popClientSocket(int* clientThread);
-
-    //Address of socket server
-    std::string m_serverAddress;
-    //Signal used for informing threads to stop
-    int m_signalToClose;
-    //Socket for listening
-    int m_listenFd;
-    //Number of main thread
-    pthread_t m_mainThread;
-    //Numbers of all created threads for connections
-    std::list<int> m_clientSocketList;
-
-    //Thread list mutex
-    std::mutex m_clientSocketListMutex;
-
-    //Structure for callback maps
-    class ServiceCallback
-    {
-    public:
-        ServiceCallback(socketServerCallback ser, securityCheck sec) : serviceCallback(ser), securityCallback(sec){}
-        socketServerCallback serviceCallback;
-        securityCheck securityCallback;
-    };
-
-    typedef std::shared_ptr<ServiceCallback> ServiceCallbackPtr;
-    //Map for callback methods, key is a method name and value is a callback to method
-    typedef std::map<std::string, ServiceCallbackPtr> ServiceMethodCallbackMap;
-    //Map for interface methods, key is an interface name and value is a map of available methods with callbacks
-    std::map<std::string, ServiceMethodCallbackMap> m_callbackMap;
-
-    //Structure passed to connection thread
-    struct Connection_Info{
-        Connection_Info(int fd, void * data) : connfd(fd), data(data)
-        {}
-        int connfd;
-        void * data;
-    };
-
-};
-
-#endif /* SECURITY_SOCKET_SERVICE_H_ */
diff --git a/src/include/SLP_security-model_PG.h b/src/include/SLP_security-model_PG.h
new file mode 100644 (file)
index 0000000..0f2dc07
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * @defgroup SLP_PG_SECURITY Security and Permissions
+ * @ingroup SLP_PG
+ * @{
+ *     @brief  <em class="ref">Also see </em>  [ @ref SecurityFW ]
+ *     @defgroup CertificateManager_PG
+ *     @defgroup Security_Server_PG
+ *     @defgroup SecureStorage_PG
+ *     @}
+ *     @defgroup SLP_PG_SECURITY
+ *     @ingroup SLP_PG
+ *     @{
+
+<h1 class="pg">Security Requirements</h1>
+<h2>Privileges </h2>
+<p>All processes MUST have least privilege to operate their own purpose. middleware daemons might run as root to satisfy their functional requirements, but there MUST BE NO application process which is running as root. In this document application represents all processes which has user interface to the end user.</p>
+<p>Each application process should have different privileges to satisfy least privilege, therefore there should be an entity to take care of process privileges.</p>
+<p>If an application process requires higher (system or root) privilege to provide some function, the function must be implemented in a middleware daemon and the function must be provided as an API to application</p>
+<h2>Application Sandboxing</h2>
+<p>All applications MUST NOT interfere each other. Interference covers killing other processes, modify or delete other application's files, overwrite or read other application process' memory area, masquerading other applications, and reading other application's sensitive files.</p>
+<h2>Middleware Resource Protection</h2>
+<p>All middleware resources MUST be protected by unauthorized access from applications. If the middleware is a daemon process, the process must not be interfered by applications, if the middleware is a library and the resources of the middleware are files, then the files must not be modified by unauthorized process.</p>
+<p>The resources must be protected at the resource level, not API level because API could be easily detoured</p>
+<h2>Privilege Escalation</h2>
+<p>There should be no privilege escalation, but by some management and/or manufacturing reason, unpredicted privilege escalation might be necessary. In this situation the modules which require privilege escalation MUST be highly reviewed and managed by developers and security manager.</p>
+<h1 class="pg">Security Model</h1>
+<h2>Background Information</h2>
+<h3>Discretionary Access Control</h3>
+<p>Linux kernel have supported discretionary access control (DAC) from the very beginning which controls access based on user ID, group ID of a process and owner of file that the process tries to access. This access control mechanism has been evolved with the Linux system evolution, additionally, SLP is not an embedded Linux platform but a normal Linux platform, therefore SLP has full support on DAC.</p>
+<p>In Linux all process is executed with user ID and groups, normally inherited by parent process. The processes which are executed in booting script will be executed as root user because the parent process "init" is root process. Any other user processes including user shell will be executed as an user that is logged in by the console login process. The groups that the process belongs to are also inherited by parent process, the list of group ID is assigned when the user is logged in based on "/etc/group" file. A process can be belonged more than thousand of groups (max 65,536 but I think too many groups might occur some problem).</p>
+<p>Only root process can change user ID and groups of the process by calling setuid() and setgroups() function, so if a root process is changed user to non root, then it can never change its user ID and groups again.</p>
+<p>There is a special feature to change user ID even the process is not owned by root user. If the executable file has setuid sticky bit, then the process will be executed as the owner of executable files. This is very important for access control because it can produce "privilege escalation" which can harm the platform security. In Linux PC, utilities such as "sudo" and "su" has this feature because these command need to change user to root or other user ID. These utilities first executed as root user and then changes to other user ID if needed.</p>
+<p>In Linux file system, all files are labeled with security context which describes owner user ID and group ID of the file and the permission of each accessible entity which are owner, group, and others. Permissions are consisting of read, write, and execute for each entity. If accessing process's user ID is same to owner of the file to be accessed, then the owner's permission is applied, if the process has the group that is labeled on the file, then the group's permission is applied, if not, then the other's permission is applied. All these functions are implemented in Linux kernel, so you don't need anything more for the feature. By the way, root process bypasses all the permission checking, that is root process can access all files. You can refer to Linux fundamental documents for this feature.</p>
+<p>The owner of a file can change permission of the file but, cannot change owner of the file. Only root process can change owner of the file, so if you want to change owner of a file, you have to be root.</p>
+<h3>Mandatory Access Control</h3>
+<p>DAC is great security feature of Linux, but sometime DAC is not sufficient to protect platform. DAC is based on user ID, group and file’s permissions, the granularity is limited to user ID level, in some way platform may need more precise access control than DAC. Mandatory Access Control (MAC) provides this security feature to give better and precise access control based on labeling and policy.</p>
+<p>MAC was not a part of standard Linux in the beginning, but since there were several requirements, so from kernel 2.6 version, some of the MAC mechanisms have been added to main line kernel source as optional features.</p>
+<p>MAC needs security context labeling and policy to control. Usually, all files have its security context described in extended attribute(xattr) of file system or some other places if xattr is not supported. Policy describes which subject (process) has permission to do something (operation) to some object. It doesn’t refer to owner and permission of the DAC field, just refer to security context of subject and object, and then searches allowed operations. Object can be files, directories, system calls, sockets and so on, each MAC mechanism has different set of objects.</p>
+<p>Using MAC, even root process can be denied to access some important object and some chosen root process can be allowed. Currently there are many MAC mechanisms such as SELinux, App-Armor, SMACK, RBAC, grsecurity and so on, and each of them has different objectives and approach.</p>
+<h2>Security Model</h2>
+<p>Since SLP is a Linux platform, its security model is similar to other Linux platform’s security model. In SLP, DAC and MAC are used, but biggest difference is that we need user space access control such as telephony, system management and so on.</p>
+<h3>Discretionary Access Control</h3>
+<p>- <b><i>User ID policy for processes</i></b></p>
+<p>All middleware daemons are running as root user ID, it's natural because daemons are executed by init process which is root process. There are a few exceptions that are not running as root even though the process is executed by init process. They are menu-screen, voice-call-daemon, and indicator. The reason is that the exceptional processes are executed by init process but they are not middleware, but applications. These special processes maybe increased at any time.</p>
+<p>Normal applications are executed as non root user ID. To achieve application sandboxing, all applications should run as all different user IDs, but it might occur complexity to the platform, so all the inhouse applications are executed as same user, and each 3rd party application will be executed as each different user ID.</p>
+<p><b><i>- Group ID for fine grained access control</i></b></p>
+<p>In Linux, a single process can be owned by a single user ID, but it can be belonged to multiple group IDs (max 65,536). In current desktop Linux such as Ubuntu, they use group ID to enforce access control for shared objects, such as CD-ROM, printer, audio, and so on. In SLP, we will use group ID as same usage, but the object will be different than normal desktop Linux, such as telephony, contact, and so on.</p>
+<p>As a result, each application will be given different group IDs based on its required privilege.</p>
+<p><i><b>- Security context on files</b></i></p>
+<p>For security and safety reason, basically all files in SLP owned by root as other Linux platform does, and then, non root user process cannot modify any files. The permission of normal files will be "rw-r--r--" which means only owner can modify or delete and the group member and others only can read, this is also same as other Linux platform. Lastly permission of executive files will be "rwxr-xr-x", so anybody can execute them, and also same as others.</p>
+<p>But there are many special files to be shared and modified by non root processes for example database files and device files in dev file system. In these cases, group ID of file is used. A shared file is owned by root but belonged to proper group ID which describes the file's content or object. The permission of the file could be "rw-rw-r--" to allow the processes belonged to the group can modify the file.</p>
+<p>There are some secret files to be protected by unauthorized read operation, then we can use same method as above but only difference will be no read permission to others, such as "rw-------", or "rw-rw----".</p>
+<p>Finally, there will be newly created files from middleware daemons and applications. There is default umask "022" , so if the created file is from middleware daemon, then the context of the file will be "root:root rw-r--r--", which means only root can modify and other users can read the file, if an application creates a file, then context wiil be "app_user:app_user rw-r--r--", so only the application can modify the file. This is normal usage but there must be some special cases which the file should be shared within applications. But, chown command and function only works under root privilege so applications cannot change owner of created files, so only thing possible is to change permission by chmod function. But there is only one option, share to none or share to all.</p>
+<h3>Mandatory Access Control</h3>
+<p>Mandatory access control(MAC) is currently out of scope of the SLP because there is almost no concrete threat which could be protected by MAC. Only one possible threat is that the network access by unauthorized process when there is a connected interface is already created. The adversary can monitor network interface status and if there is a new interface created, then it can use socket directly and it's possible to send some data by the socket. It's not possible to protect only by DAC.</p>
+<h2>User Space</h2>
+<p>There are many objects in user space such as making a phone call, sending a SMS message, which are not recognizable by kernel because thses objects are implemented in a daemon process, applications will request access by IPC and the kernel cannot manage inside of IPC messages. In these cases we must have a user space trusted entity which judges and controls access to such objects, which sits between applications and middleware daemons.</p>
+<p>To enable this, the entity must get identity of the subject application and object to be accessed, but it's not easy because some of the IPC mechanisms don't support peer's identity acquisition. For example all the dbus messages are routed by dbus daemon, so the receiver only guarantees dbus daemon sent the message, not the original sender of the message. Therefore, we have to support such mechanism to guarantee the original sender's identity to the final receiver along with reliable and secure access decision mechanism.</p>
+<p>To enforce access control, there must be an access policy which should be stored securely and it must be reliable. In SLP we utilized group ID for this policy. All processes have their user ID and groups which are controlled by kernel, each user space object is described as a group ID and the subject process will have the group ID if the application process has corresponding group ID then the access to be allowed, if not, the access will be denied.</p>
+<p>One more function required is that the enforcing entity needs to know other processes groups information. proc file system can be used. In proc file system, there is a file named "status", which describes various information about a process including all groups that the process belong to.</p>
+<h1 class="pg">Implementation</h1>
+<h2>User ID and Group ID Administration for Processes</h2>
+<p>As described above, all the daemons will be run by root, this is natural because all the booting scripts are executed by init process which is a root process, so all the processes executed by booting scripts will be run as root automatically. But there are some exceptions. There are some processes which are executed by booting scripts but not actually daemons such as menu screen and indicator. These processes must drop their privilege to a normal user, so in the beginning of their code, they change their user ID and groups to a normal user.</p>
+<p>All other applications will be executed by AUL (application utility library). When a new application process is requested to be executed, AUL daemon (launchpad) which is a root process receives the request, fork() and execute requested application in the child process. During this process, after forking a process, the launchpad child process changes its user ID to a corresponding user ID, changes matching groups, changes home directory, and execute the application. This is similar to su command in Linux environment.</p>
+<p>When a new application is installed, package manager adds a new user which has same user name with package name but substituting dot '.' to underscore '_'. But this feature is currently out of scope of the SLP.</p>
+<p>The group ID will be described as manifest permission item which described in control file of the debian package. Manifest permission items and group IDs will not correspond 1 to 1, basically one permission item will mean a set of group IDs to enable the permission, the sets might consist of 1 group ID or many group IDs. When a new application is installed, these groups will be assigned to the user ID, this could be implemented by adduser command. But this feature is currently out of scope of the SLP.</p>
+<h2>Changing Owner, Group and Permissions for Files</h2>
+<p>Since SLP uses debian package for the internal build system, all files which are installed by debian are automatically owned by root and their permissions set to 0644 (rw-r--r--), which means only root can modify and other processes only can read. But in the platform there are various files which should be modified by applications also, so we need to modify the ownership and permission intentionally.</p>
+<p>The only way to do this is by using postinst script of each of the debian package. On each package if there are some files should be shared, the package developer should add a few line to postinst file to change owner ship and permission to the files. To change owner, of a file, you have to be a root, if you are using fakeroot, the chown will not be affected.</p>
+*/
+/**
+*@}
+*/
diff --git a/src/include/SLP_security-server_PG.h b/src/include/SLP_security-server_PG.h
new file mode 100644 (file)
index 0000000..c1016ab
--- /dev/null
@@ -0,0 +1,350 @@
+/**
+ *
+ * @ingroup   SLP_PG
+ * @defgroup  Security_Server_PG Security Server
+@{
+
+<h1 class="pg">Introduction</h1>
+<p>In Linux system, access control is enforced in the kernel space objects such as file, socket, directory, and device which are all described as files. In SLP, many objects are defined in user space which cannot be described as file, for example, make a phone call, send a SMS message, connect to the Internet, and modify SIM password. Some of the objects in user space are very sensitive to the platform and the phone business as well as user's property. Therefore the user space objects needed to be protected.</p>
+<p>To protect such user space objects, there must be a kind of credential to decide access result, and the credential must be trusted. Since process has privileges and the objects only has label, so some trusted entity should check the process has right privilege to access objects, and the security hooks to check this privilege should be located in the each middleware service daemons which provide the objects to the applications.</p>
+<p>Security Server uses group IDs of Linux system that are assigned to each process. In detail, if a process requests to get some user-space service to a middleware daemon, the middleware daemon requests to check privilege of some process, then the security server checks given gid is assigned to the process or not. If yes, then return yes, if no, then return no.</p>
+<p>If an application and middleware daemon uses Linux standard IPC such as Unix domain socket, there is no need to introduce 3rd party process to check gid that the process has. But some of service uses non Linux standard IPC such as telephony - using dbus - which the peer's credential is not propagated to the other peer. As a result to meet all the system's environment, we introduce Security Server.</p>
+<p>
+Security Server uses a random token named "cookie" to identify a process, the cookie needed not to be abled to guess easily, so it's quite long (currently 20 bytes), and only kept by Security Server process memory</p>
+
+<h1 class="pg">Security Server Architecture</h1>
+@image html SLP_Security-Server_PG_image001.png
+<p>Above fiture explains software architecture of Security Server. It is client-server structure, and communicates by IPC. The IPC must be point-2-point mechanism such as UNIX domain socket, not server related IPC such as dbus, because it's not easy to guarantee the other peer's security.</p>
+<p>Application or middleware process can call Security Server API to assign a new cookie or checking privilege of the given cookie. In this case, client library authenticates IPC peer and check the peer is Security Server process. In the same sense, Security Server authenticates client also.</p>
+<p>Application requests cookie to Security Server before requesting the service to the middleware daemon. Security Server authenticates the client, generates a random cookie, stores the cookie into local memory, and responds to the client with the cookie value. Client loads the cookie in the request message and sends to the middleware server, then the receiver middleware daemon check the privilege of the given cookie by calling Security Server API. Security Server compares received cookie value with stored cookie, checks and responds to the middleware daemon. Finally middleware daemon knows the client's privilege and it decides continue or block the request.</p>
+
+<h2>Sub components</h2>
+
+<h3>Client library</h3>
+@image html SLP_Security-Server_PG_image002.png
+<p>Client library is linked to application or middleware daemon. Therefore it belongs to the caller process, so uid, pid, and groups are also same. If the application calls cookie request API, the client compose cookie request message and sends to the Security Server and wait for the response. After receiving the response, first checks the response is from Security Server, and if it's true, it stores cookie into cookie container.</p>
+<p>Middleware daemon also links same client library, but by the difference of the calling APIs, the functions are different. Middleware daemon first receives cookie value loaded in service request from the client, and then the middleware calls Security Server API to check the cookie has the privilege to the service and waits for the response. After receiving the response, it authenticates the response is really from Security Server, and continue service by the result of the API.</p>
+
+<h3>Security Server Daemon</h3>
+@image html SLP_Security-Server_PG_image003.png
+<p>Security Server daemon is a Unix domain socket server, but it only has single thread and single process to get rid of race condition for the proc file system and cookie list to be shared. It’s easy to manage, more secure and the Security Server itself doesn't need to maintain a session for a long time.</p>
+<p>When request API is received from the client, Security Server first parses, and authenticates the message, and creates cookie or checks privilege. Cookie is a 20 bytes random string too hard to be guessed. So it's hard to be spoofed.</p>
+<p>Cookie generator generates a cookie based on proc file system information of the client process with group IDs the client belongs to, and privilege checker searches received cookie value with stored cookie list and checks the privilege.</p>
+<p>Cookie list is a linked list implemented in memory and it stores and manages generated cookie.</p>
+
+<h1 class="pg">Dependency</h1>
+<p>The Security Server has high dependency on Linux kernel, precisely the proc file system. Since Security Server refers to proc file system with processes group ID, so the kernel must support group ID representation on the proc file system.</p>
+<p>In kernel version 2.6, there is a file in proc file system "/proc/[pid]/status" which describes various information about the process as text, it has a line named "Groups:" and it lists the group IDs that the process is belonged to. But there is a drawback in this file, it only shows at most 32 group IDs, if number of groups of the process is bigger than 32, it ignores them.</p>
+<p>To enable to show all the groups you have to patch the kernel source code to show more groups than 32, but there is another drawback. All files in the proc file system has size limit to 4k bytes because the file buffer size is 4k bytes, so it's not possible to show all possible groups of the process (64k), but currently number of all groups in the LiMo platform is much lower than the size, so it's not a big problem. But near future we need to apply this patch into kernel mainline source code by any form.</p>
+
+<h1 class="pg">Scenarios</h1>
+@image html SLP_Security-Server_PG_image004.png
+<p>Security Server process view is described in figure above. It's explained in above, so it's not necessary to explain again. But one possible question may arise, that why do we need Security Server, that the service daemon can authenticates application process by the IPC, and the daemon can check proc file system by itself, so it seems that we may not need to have Security Server at all<p>
+@image html SLP_Security-Server_PG_image005.png
+<p>But there is exceptional process view described in figure above. If the middleware's IPC mechanism is dbus, then the daemon cannot guarantee the identity of the requesting application. In this case, there is no possible way to check and authenticate application from the middleware daemon directly. We need a trusted 3rd party to guarantee such identity and privilege, therefore Security Server is required.</p>
+<p>As described above, the cookie value is the key of the security of Security Server. The cookie value must not to be exposed into the platform, the cookie value must be stored securely that only Security Server and the application process knows the value. Even the middleware daemon should not cache the cookie for the security reason</p>
+
+<h1 class="pg">APIs</h1>
+
+<h3 class="pg">security_server_get_gid</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       gid_t security_server_get_gid(const char *object)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       object name as Null terminated string
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns the integer gid of requested object.<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API returns the gid from given object name. This API is only allowed to be called from middleware service daemon which is running under root privilege
+
+<h3 class="pg">security_server_get_object_name</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       gid, max_object_size
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       object as null terminated string
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API is opposite with security_server_get_gid(). It converts given gid to object name which buffer size is max_object_size. If object name is bigger then max_object_size then it returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
+
+<h3 class="pg">security_server_request_cookie</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       gid_t security_server_request_cookie(char *cookie, size_t max_cookie)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       max_cookie
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       cookie
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API requests a cookie to Security Server. max_cookie is the size of buffer cookie to be filled with cookie value, if max_cookie smaller then cookie size, then this API returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
+
+<h3 class="pg">security_server_get_cookie_size</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_get_cookie_size(void)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       size of cookie value
+               </td>
+       </tr>
+</table>
+This API simply returns the size of cookie.
+
+<h3 class="pg">security_server_check_privilege</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_check_privilege(const char *cookie, gid_t privilege)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       cookie, privilege
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API checks the cookie value has privilege for given gid. This API should be called by middleware server only after application embed cookie into the request message and sent to the middleware server. The middleware server should aware with the privilege parameter because it knows the object which the client application tries to access.
+
+
+<h1 class="pg">Implementation Guide</h1>
+
+<h2>Middleware server side</h2>
+<p>
+In middleware, implementation is focused on checking privilege of the requested client application. To call security_server_check_privilege() API, you have to get the gid value first, and this can be achieved by calling security_server_get_gid() API. The pre-condition of this scenario is that the middleware server knows the name of the object. Once you get the gid values, you can cache them for better performance. </p>
+<p>
+Once a client application requests to access the middleware’s object, the client should embed cookie into the request message. If not, the security is not guaranteed. After getting request and embedded cookie, the middleware server call security_server_check_privilege() API to check the client is allowed to access the object, the security server will respond the result. Finally the server need to decide continue the service or not.</p>
+
+@code
+static gid_t g_gid;
+
+int get_gid()
+{
+       int ret;
+       // Get gid of telephony call - example object
+       ret = security_server_get_gid("telephony_call");
+       if(ret < 0)
+       {
+               return -1;
+       }
+       g_gid = ret;
+       return 0;
+}
+
+int main(int argc, char * argv[])
+{
+       char *cookie = NULL;
+       int ret, cookie_size;
+
+
+       ...
+
+
+               // Initially get gid about the object which is interested in
+               if(get_gid() < 0)
+                       exit(-1);
+
+       // get cookie size and malloc it if you want
+       cookie_size = security_server_get_cookie_size();
+       cookie = malloc(cookie_size);
+
+       ...
+
+       // If a request has been received
+       // First parse the request and get the cookie value
+       // Let's assume that the buffer cookie is filled with received cookie value
+       ret = security_server_check_privilege(cookie, cookie_size);
+       if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
+       {
+               // Access denied
+               // Send error message to client application
+       }
+       else if( ret != SECURITY_SERVER_SUCCESS)
+       {
+               // Error occurred
+               // Check error condition 
+       }
+       else
+       {
+               // Access granted
+               // Continue service
+               ...
+       }
+
+
+       ...
+
+
+       free(cookie);
+       ...
+}
+@endcode
+
+<h2>Client application side</h2>
+<p>
+In client application, what you need is just request a cookie and embed it into request message</p>
+
+@code
+int some_platform_api()
+{
+       char *cookie = NULL;
+       int cookie_size, ret;
+
+       ...
+
+
+       // malloc the cookie
+       cookie_size = security_server_get_cookie_size();
+       cookie = malloc(cookie_size);
+
+       ...
+
+
+               // Request cookie from the security server
+               ret = security_server_request_cookie(cookie, cookie_size);
+       if(ret < 0)
+       {
+               // Some error occurred
+               return -1;
+       }
+
+       // embed cookie into the message and send to the server
+
+       ...
+       free(cookie);
+}
+@endcode
+
+*/
+/**
+*@}
+*/
diff --git a/src/include/security-server-comm.h b/src/include/security-server-comm.h
new file mode 100644 (file)
index 0000000..b132caf
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COMM_H
+#define SECURITY_SERVER_COMM_H
+
+/* Message */
+typedef struct
+{
+       unsigned char version;
+       unsigned char msg_id;
+       unsigned short msg_len;
+} basic_header;
+
+typedef struct
+{
+       basic_header basic_hdr;
+       unsigned char return_code;
+} response_header;
+
+#define SECURITY_SERVER_MIDDLEWARE_USER "app"
+
+/* Message Types */
+#define SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST                0x01
+#define SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE       0x02
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST       0x03
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE      0x04
+#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST   0x05
+#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE  0x06
+#define SECURITY_SERVER_MSG_TYPE_GID_REQUEST           0x07
+#define SECURITY_SERVER_MSG_TYPE_GID_RESPONSE          0x08
+#define SECURITY_SERVER_MSG_TYPE_PID_REQUEST           0x09
+#define SECURITY_SERVER_MSG_TYPE_PID_RESPONSE          0x0a
+#define SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST          0x0b
+#define SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE         0x0c
+#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST     0x0d
+#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE    0x0e
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST       0x0f
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE      0x10
+#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST     0x11
+#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE    0x12
+#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST       0x13
+#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE      0x14
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST       0x15
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE      0x16
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST   0x17
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE  0x18
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST   0x19
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE  0x1a
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST    0x1b
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE   0x1c
+#define SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST         0x1d
+#define SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE        0x1e
+#define SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE      0xff
+
+/* Return code */
+#define SECURITY_SERVER_RETURN_CODE_SUCCESS            0x00
+#define SECURITY_SERVER_RETURN_CODE_BAD_REQUEST                0x01
+#define SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED      0x02
+#define SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED     0x03
+#define SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED      0x04
+#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT     0x05
+#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE     0x06
+#define SECURITY_SERVER_RETURN_CODE_NO_PASSWORD                0x07
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST             0x08
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH  0x09
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED     0x0a
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED   0x0b
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED    0x0c
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER       0x0d
+#define SECURITY_SERVER_RETURN_CODE_SERVER_ERROR       0x0e
+
+int return_code_to_error_code(int ret_code);
+int create_new_socket(int *sockfd);
+int safe_server_sock_close(int client_sockfd);
+int connect_to_server(int *fd);
+int accept_client(int server_sockfd);
+int authenticate_client_application(int sockfd, int *pid, int *uid);
+int authenticate_client_middleware(int sockfd, int *pid);
+int authenticate_developer_shell(int sockfd);
+char *read_cmdline_from_proc(pid_t pid);
+int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code);
+int send_cookie(int sockfd, unsigned char *cookie);
+int send_object_name(int sockfd, char *obj);
+int send_gid(int sockfd, int gid);
+int send_cookie_request(int sock_fd);
+int send_gid_request(int sock_fd, const char* object);
+int send_object_name_request(int sock_fd, int gid);
+int send_privilege_check_request(int sock_fd, const char*cookie, int gid);
+int send_privilege_check_new_request(int sock_fd,
+                                     const char *cookie,
+                                     const char *object,
+                                     const char *access_rights);
+int recv_get_gid_response(int sockfd, response_header *hdr, int *gid);
+int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size);
+int recv_cookie(int sockfd, response_header *hdr, char *cookie);
+int recv_privilege_check_response(int sockfd, response_header *hdr);
+int recv_privilege_check_new_response(int sockfd, response_header *hdr);
+int recv_hdr(int client_sockfd, basic_header *basic_hdr);
+int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege);
+int recv_check_privilege_new_request(int sockfd,
+                                     unsigned char *requested_cookie,
+                                     char *object_label,
+                                     char *access_rights);
+int send_pid_request(int sock_fd, const char*cookie);
+int recv_pid_response(int sockfd, response_header *hdr, int *pid);
+int recv_pid_request(int sockfd, unsigned char *requested_cookie);
+int send_pid(int sockfd, int pid);
+int send_smack_request(int sockfd, const char * cookie);
+int recv_smack_response(int sockfd, response_header *hdr, char * label);
+int recv_smack_request(int sockfd, unsigned char *requested_cookie);
+int send_smack(int sockfd, char * label);
+int send_launch_tool_request(int sock_fd, int argc, const char **argv);
+int recv_generic_response(int sockfd, response_header *hdr);
+int recv_launch_tool_request(int sockfd, int argc, char *argv[]);
+int recv_pwd_response(int sockfd, response_header *hdr, unsigned int *current_attempts,
+       unsigned int *max_attempts, unsigned int *valid_days);
+int send_set_pwd_request(int sock_fd, const char*cur_pwd, const char*new_pwd,
+       const unsigned int max_challenge, const unsigned int valid_period_in_days);
+int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days);
+int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge);
+int send_chk_pwd_request(int sock_fd, const char*challenge);
+int check_socket_poll(int sockfd, int event, int timeout);
+int free_argv(char **argv, int argc);
+
+#endif
diff --git a/src/include/security-server-common.h b/src/include/security-server-common.h
new file mode 100644 (file)
index 0000000..03893d2
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COMMON_H
+#define SECURITY_SERVER_COMMON_H
+
+#include <sys/types.h>
+
+/* Definitions *********************************************************/
+/* Return value. Continuing from return value of the client header file */
+#define SECURITY_SERVER_SUCCESS                                0
+#define SECURITY_SERVER_ERROR_SOCKET                   -1
+#define SECURITY_SERVER_ERROR_BAD_REQUEST              -2
+#define SECURITY_SERVER_ERROR_BAD_RESPONSE             -3
+#define SECURITY_SERVER_ERROR_SEND_FAILED              -4
+#define SECURITY_SERVER_ERROR_RECV_FAILED              -5
+#define SECURITY_SERVER_ERROR_NO_SUCH_OBJECT           -6
+#define SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED    -7
+#define SECURITY_SERVER_ERROR_INPUT_PARAM              -8
+#define SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL         -9
+#define SECURITY_SERVER_ERROR_OUT_OF_MEMORY            -10
+#define SECURITY_SERVER_ERROR_ACCESS_DENIED            -11
+#define SECURITY_SERVER_ERROR_SERVER_ERROR             -12
+#define SECURITY_SERVER_ERROR_NO_SUCH_COOKIE           -13
+#define SECURITY_SERVER_ERROR_NO_PASSWORD              -14
+#define SECURITY_SERVER_ERROR_PASSWORD_EXIST           -15
+#define SECURITY_SERVER_ERROR_PASSWORD_MISMATCH                -16
+#define SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER     -17
+#define SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED   -18
+#define SECURITY_SERVER_ERROR_PASSWORD_EXPIRED -19
+#define SECURITY_SERVER_ERROR_PASSWORD_REUSED  -20
+#define SECURITY_SERVER_ERROR_SOCKET_BIND              -21
+#define SECURITY_SERVER_ERROR_FILE_OPERATION           -22
+#define SECURITY_SERVER_ERROR_TIMEOUT                  -23
+#define SECURITY_SERVER_ERROR_POLL                     -24
+#define SECURITY_SERVER_ERROR_UNKNOWN                  -255
+
+/* Miscellaneous Definitions */
+#define SECURITY_SERVER_SOCK_PATH                      "/tmp/.security_server.sock"
+#define SECURITY_SERVER_DEFAULT_COOKIE_PATH            "/tmp/.security_server.coo"
+#define SECURITY_SERVER_DAEMON_PATH                    "/usr/bin/security-server"
+#define SECURITY_SERVER_COOKIE_LEN                     20
+#define MAX_OBJECT_LABEL_LEN                            32
+#define MAX_MODE_STR_LEN                                16
+#define SECURITY_SERVER_MIDDLEWARE_LIST_PATH           "/usr/share/security-server/mw-list"
+#define SECURITY_SERVER_MAX_OBJ_NAME                   30
+#define SECURITY_SERVER_MAX_PATH_LEN                   50
+#define SECURITY_SERVER_MSG_VERSION                    0x01
+#define SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND      10000
+#define SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND      3000
+#define SECURITY_SERVER_DEVELOPER_UID                  5100
+#define SECURITY_SERVER_DEBUG_TOOL_PATH                        "/usr/bin/debug-util"
+#define SECURITY_SERVER_KILL_APP_PATH                  "/usr/bin/kill_app"
+#define SECURITY_SERVER_DATA_DIRECTORY_PATH            "/opt/data/security-server"
+#define SECURITY_SERVER_ATTEMPT_FILE_NAME      "attempts"
+#define SECURITY_SERVER_HISTORY_FILE_NAME      "history"
+#define SECURITY_SERVER_MAX_PASSWORD_LEN               32
+#define SECURITY_SERVER_HASHED_PWD_LEN                 32  /* SHA256 */
+#define SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND          1
+#define SECURITY_SERVER_MAX_PASSWORD_HISTORY   50
+#define SECURITY_SERVER_NUM_THREADS                    10
+
+/* API prefix */
+#ifndef SECURITY_SERVER_API
+#define SECURITY_SERVER_API    __attribute__((visibility("default")))
+#endif
+
+
+
+/* Data types *****************************************************************/
+/* Cookie List data type */
+typedef struct _cookie_list
+{
+       unsigned char   cookie[SECURITY_SERVER_COOKIE_LEN];     /* 20 bytes random Cookie */
+       int             path_len;                               /* Client process cmd line length */
+       int             permission_len;                         /* Client process permissions (aka group IDs) */
+       pid_t           pid;                                    /* Client process's PID */
+       char            *path;                                  /* Client process's cmd line string */
+       int             *permissions;                           /* Array of GID that the client process has */
+    char            *smack_label;                           /* SMACK label of the client process */
+    char    is_roots_process;           /* Is cookie belongs to roots process */
+       struct _cookie_list     *prev;                          /* Next cookie list */
+       struct _cookie_list     *next;                          /* Previous cookie list */
+} cookie_list;
+
+
+/* Function prototypes ******************************************************/
+/* IPC */
+
+void printhex(const unsigned char *data, int size);
+
+/* Debug */
+#ifdef SECURITY_SERVER_DEBUG_TO_CONSOLE /* debug msg will be printed in console */
+#define SEC_SVR_DBG(FMT, ARG ...) fprintf(stderr, "[%s:%d] "FMT"\n", \
+               __FILE__, __LINE__, ##ARG)
+
+#elif SECURITY_SERVER_DEBUG_DLOG       /* debug msg will be printed by dlog daemon */
+#define LOG_TAG "SECURITY_SERVER"
+#include <dlog.h>
+#define SEC_SVR_DBG    SLOGD
+#else /* No debug output */
+#define SEC_SVR_DBG(FMT, ARG ...) {}
+#endif
+
+#endif
diff --git a/src/include/security-server-cookie.h b/src/include/security-server-cookie.h
new file mode 100644 (file)
index 0000000..3acc720
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved\r
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COOKIE_H\r
+#define SECURITY_SERVER_COOKIE_H\r
+\r
+#include "security-server-common.h"\r
+\r
+int free_cookie_item(cookie_list *cookie);
+cookie_list *delete_cookie_item(cookie_list *cookie);
+cookie_list *search_existing_cookie(int pid, const cookie_list *c_list);
+cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege);
+cookie_list *search_cookie_new(const cookie_list *c_list,
+                               const unsigned char *cookie,
+                               const char *object,
+                               const char *access_rights);
+int generate_random_cookie(unsigned char *cookie, int size);
+cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list);
+cookie_list *create_default_cookie(void);
+cookie_list * garbage_collection(cookie_list *cookie);
+cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid);
+void printhex(const unsigned char *data, int size);\r
+\r
+#endif\r
diff --git a/src/include/security-server-password.h b/src/include/security-server-password.h
new file mode 100644 (file)
index 0000000..924153f
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_PASSWORD_H
+#define SECURITY_SERVER_PASSWORD_H
+
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+int process_valid_pwd_request(int sockfd);
+int process_set_pwd_request(int sockfd);
+int process_reset_pwd_request(int sockfd);
+int process_reset_pwd_request(int sockfd);
+int process_chk_pwd_request(int sockfd);
+int process_set_pwd_max_challenge_request(int sockfd);
+int process_set_pwd_validity_request(int sockfd);
+void initiate_try(void);
+
+#endif
diff --git a/src/include/security-server-util.h b/src/include/security-server-util.h
new file mode 100644 (file)
index 0000000..32c9f72
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_UTIL_H
+#define SECURITY_SERVER_UTIL_H
+
+/* Only for test */
+/* These msg type MUST BE REMOVED before release **************************/
+#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST       0x51
+#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE      0x52
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST       0x53
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE       0x54
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST    0x55
+/**********************************************************************/
+
+int util_process_all_cookie(int sockfd, cookie_list* list);
+int util_process_cookie_from_pid(int sockfd, cookie_list* list);
+int util_process_cookie_from_cookie(int sockfd, cookie_list* list);
+
+
+#endif
diff --git a/src/include/security-server.h b/src/include/security-server.h
new file mode 100644 (file)
index 0000000..b927c89
--- /dev/null
@@ -0,0 +1,1027 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_H
+#define SECURITY_SERVER_H
+
+#include <sys/types.h>
+
+/**
+ * @file    security-server.h
+ * @version 1.0
+ * @brief   This file contains APIs of the Security Server
+*/
+
+/**
+ * @defgroup SecurityFW
+ * @{
+ *
+ * @defgroup SECURITY_SERVER Security Server
+ * @version  1.0
+ * @brief    Security Server client library functions
+ *
+*/
+
+/**
+ * @addtogroup SECURITY_SERVER
+ * @{
+*/
+
+/*
+ * ====================================================================================================
+ * <tt>
+ *
+ * Revision History:
+ *
+ *  -- Company Name -- | Modification Date | Description of Changes
+ *  -----------------------------------------------------------------------
+ *   --- Samsung ------ | --- 2010-07-25 -- | First created
+ *
+ *    </tt>
+ */
+
+/**
+ * \name Return Codes
+ * exported by the foundation API.
+ * result codes begin with the start error code and extend into negative direction.
+ * @{
+*/
+#define SECURITY_SERVER_API_SUCCESS                    0
+/*! \brief   indicating the result of the one specific API is successful */
+#define SECURITY_SERVER_API_ERROR_SOCKET               -1
+
+/*! \brief   indicating the socket between client and Security Server has been failed  */
+#define SECURITY_SERVER_API_ERROR_BAD_REQUEST          -2
+
+/*! \brief   indicating the response from Security Server is malformed */
+#define SECURITY_SERVER_API_ERROR_BAD_RESPONSE         -3
+
+/*! \brief   indicating the transmitting request has been failed */
+#define SECURITY_SERVER_API_ERROR_SEND_FAILED          -4
+
+/*! \brief   indicating the receiving response has been failed */
+#define SECURITY_SERVER_API_ERROR_RECV_FAILED          -5
+
+/*! \brief   indicating requesting object is not exist */
+#define SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT       -6
+
+/*! \brief   indicating the authentication between client and server has been failed */
+#define SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED        -7
+
+/*! \brief   indicating the API's input parameter is malformed */
+#define SECURITY_SERVER_API_ERROR_INPUT_PARAM          -8
+
+/*! \brief   indicating the output buffer size which is passed as parameter is too small */
+#define SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL     -9
+
+/*! \brief   indicating system  is running out of memory state */
+#define SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY                -10
+
+/*! \brief   indicating the access has been denied by Security Server */
+#define SECURITY_SERVER_API_ERROR_ACCESS_DENIED                -11
+
+/*! \brief   indicating Security Server has been failed for some reason */
+#define SECURITY_SERVER_API_ERROR_SERVER_ERROR         -12
+
+/*! \brief   indicating given cookie is not exist in the database  */
+#define SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE       -13
+
+/*! \brief   indicating there is no phone password set  */
+#define SECURITY_SERVER_API_ERROR_NO_PASSWORD          -14
+
+/*! \brief   indicating password exists in system  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_EXIST               -15
+
+/*! \brief   indicating password mismatch  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH    -16
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER -17
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED       -18
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED     -19
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_REUSED      -20
+
+/*! \brief   indicating the error with unknown reason */
+#define SECURITY_SERVER_API_ERROR_UNKNOWN              -255
+/** @}*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+/**
+ * \par Description:
+ * Retreives Linux group ID from object name which is passed by parameter
+ *
+ * \par Purpose:
+ * This API may be used before security_server_check_privilege() API by middleware daemon to get group ID of a specific object.
+ *
+ * \par Typical use case:
+ * In middleware daemon, before checking privilege of a service the daemon need to know the GID of the service. This API support the functionality.
+ *
+ * \par Method of function operation:
+ * Opens /etc/group file and searches the object name as group name. If there is matching result, returns GID as integer
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - This API is only allowed to be called by pre-defined middleware daemon
+ *
+ * \param[in] object Name of the object which is kwnown by the caller.
+ *
+ * \return matching gid (positive integer) on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Inhouse middleware
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see /etc/group,
+ * security_server_get_object_name(), security_server_check_privilege()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ *
+ * // You have to make sure that  the input param '*object' is defined in the platform
+ * retval = security_server_get_gid("telephony_makecall");
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_gid(const char *object);
+
+
+
+/**
+ * \par Description:
+ * Retreives object name as mull terminated string from Linux group ID which is passed by parameter
+ *
+ * \par Purpose:
+ * This API may be used to get object name if the caller process only knows GID of the object.
+ *
+ * \par Typical use case:
+ * In middleware daemon, by some reason, need to know object name from the Linux group ID, then call this API to retrieve object name as string
+ *
+ * \par Method of function operation:
+ * Opens /etc/group file and searches matching gid. If there is matching result, returns name of the group as null terminated string
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - This API is only allowed to be called by pre-defined middleware daemon
+ *
+ * \param[in] gid Linux group ID which needed to be retrieved as object name.
+ * \param[out] object Place holder for matching object name for gid.
+ * \param[in] max_object_size Allocated byte size of parameter "object".
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Inhouse middleware.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre output parameter object must be malloced before calling this API not to make memory curruption
+ *
+ * \post None
+ *
+ * \see /etc/group,
+ * security_server_get_gid()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * char objectname[20];
+ *
+ * // Call the API
+ * retval = security_server_get_object_name(6005, objectname, sizeof(objectname));
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size);
+
+
+
+/**
+ * \par Description:
+ * Request cookie to the Security Server. Cookie is a random bit stream which is used as ticket for user space object.
+ *
+ * \par Purpose:
+ * This API may be used by application and client middleware process to get access to middleware daemons.
+ *
+ * \par Typical use case:
+ * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
+ *
+ * \par Method of function operation:
+ * Caller process just send request message. Security Server checks proc file system to get list of gIDs the caller belongs, then create a random cookie and responds to caller.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie needs to be stored relatively secure.
+ *
+ * \param[out] cookie Place holder for cookie value.
+ * \param[in] max_cookie Allocated byte size of parameter "cookie".
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Any process
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre output parameter cookie must be malloced before calling this API not to make memory curruption
+ * Size of the cookie can be retrieved by security_server_get_cookie_size() API.
+ *
+ * \post None
+ *
+ * \see security_server_check_privilege(), security_server_get_cookie_size()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char cookie[cookie_size];
+ *
+ * // Call the API
+ * retval = security_server_request_cookie(cookie, cookie_size);
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_request_cookie(char *cookie, size_t max_cookie);
+
+
+
+/**
+ * \par Description:
+ * This API gets the cookie's byte size which is issued by Security Server.
+ *
+ * \par Purpose:
+ * This API may be used by application and middleware process to get size of cookie before getting and storing cookie value.
+ *
+ * \par Typical use case:
+ * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
+ *
+ * \par Method of function operation:
+ * This API just returns pre-defined integer value as cookie size.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * None
+ *
+ * \return Always returns byte size of the cookie.
+ *
+ * \par Prospective clients:
+ * Any process
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie()
+
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ *
+ * // API calling
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char cookie[cookie_size];
+ *
+ * char objectname[20];
+ * retval = security_server_request_cookie(cookie, cookie_size);
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_cookie_size(void);
+
+
+
+/**
+ * \par Description:
+ * This API checks the cookie is allowed to access to given object.
+ *
+ * \par Purpose:
+ * This API may be used by middleware process to ask the client application has privilege for the given object.
+ *
+ * \par Typical use case:
+ * When middleware server receives request message from client application process with cookie value, it calls this API to ask to Security Server that the client application has privilege to access the service. If yes, then the middleware daemon can continue service, if not, it can return error to client application.
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it checks the cookie has the privilege. It returns success if there is match, if not, it returns error.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie value needs to be stored relatively secure\n
+ * Privilege should be pre-defined by Platform design.
+ *
+ * \param[in] cookie Received cookie value from client application
+ * \param[in] privilege Object group ID which the client application wants to access
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend middleware daemons
+ *
+ * \par Known issues/bugs:
+ * None
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie(), security_server_get_gid(), security_server_get_cookie_size()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ * int call_gid;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char recved_cookie[cookie_size];
+ *
+ * ... // Receiving request with cookie
+ *
+ * call_gid = security_server_get_gid("telephony_makecall");
+ * retval = security_server_check_privilege(recved_cookie, (gid_t)call_gid);
+ * if(retval < 0)
+ * {
+ *     if(retval == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
+ *     {
+ *             printf("%s", "access has been denied\n");
+ *             return;
+ *     }
+ *     printf("%s", "Error has occurred\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_check_privilege(const char *cookie, gid_t privilege);
+
+int security_server_check_privilege_by_cookie(const char *cookie,
+                                              const char *object,
+                                              const char *access_rights);
+
+int security_server_check_privilege_by_sockfd(int sockfd,
+                                              const char *object,
+                                              const char *access_rights);
+
+/**
+ * \par Description:
+ * This API searchs a cookie value and returns PID of the given cookie.
+ *
+ * \par Purpose:
+ * This API may be used by middleware process to ask the client application has privilege for the given object.
+ *
+ * \par Typical use case:
+ * In some cases, a middleware server wants to know PID of the application process. But if the middleware server uses non-direct IPC such as dbus, it's nearly impossible to know and guarantee peer PID. By using this API, the middleware server can retrieve a PID of the requesting process.
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it returns corresponding PID for the cookie.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie value needs to be stored relatively secure\n
+ * This API is abled to be called only by pre-defined middleware servers.
+ *
+ * \param[in] cookie Received cookie value from client application. Cookie is not a null terminated human readable string. Make sure you're code doesn't have any string related process on the cookie.
+ *
+ * \return positive integer on success meaning the PID, 0 means the cookie is for root process, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend middleware daemons
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie(), security_server_get_cookie_size()
+ *
+ * \remarks the cookie is not a null terminated string. Cookie is a BINARY byte stream of such length which can be retrieved by security_server_get_cookie_size() API.
+ * Therefore, please do not use strcpy() family to process cookie value. You MUST use memcpy() function to process cookie value.
+ * You also have to know that the cookie value doesn't carry any null terminator. So you don't need to allocate 1 more byte of the cookie size.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int peerpid;
+ * size_t cookie_size;
+ * gid_t call_gid;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char recved_cookie[cookie_size];
+ *
+ * ... // Receiving request with cookie
+ *
+ * peerpid = security_server_get_cookie_pid(recved_cookie);
+ * if(peerpid < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_get_cookie_pid(const char *cookie);
+
+
+
+/**
+ * \par Description:
+ * This API checks phone validity of password, to check existance, expiration, remaining attempts.
+ *
+ * \par Purpose:
+ * This API should be used by applications which needs phone password check. Caller application should behave properly after this API call.
+ *
+ * \par Typical use case:
+ * Lock screen can call this API before it shows unlock screen, if there is password, lock screen can show password input UI, if not, lock screen can show just unlock screen
+ *
+ * \par Method of function operation:
+ * Sends a validate request to security server and security server replies with password information.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Password file should be stored safely. The password file will be stored by security server and only allowed itself to read/write, and data is will be securely hashed\n
+ *
+ * \param[out] current_attempts Number of password check missed attempts.
+ * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
+ * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
+ *
+ * \return 0 if there is no password set, other negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Applications which can unlock UI
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_set_pwd(), security_server_chk_pwd()
+ *
+ * \remarks If password file is currupted or accitentally deleted, this API may not synchronized with security-server, but security-server will check file status on next request.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
+ * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
+ * {
+ *     printf("%s", "There is no password exists\n");
+ * }
+ * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
+ * {
+ *     printf("%s", "Password is valid by now\n");
+ * }
+ * else
+ * {
+ *     printf("%s", "Something wrong\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_is_pwd_valid(unsigned int *current_attempts,
+                       unsigned int *max_attempts,
+                       unsigned int *valid_secs);
+
+
+
+/**
+ * \par Description:
+ * This API sets phone password only if current password matches.
+ *
+ * \par Purpose:
+ * This API should be used by setting application when the user changes his/her phone password.
+ *
+ * \par Typical use case:
+ * Setting application calls this API to change phone password. Caller needs current password to grant the change.
+ *
+ * \par Method of function operation:
+ * Sends current password with new password to security-server, security-server checks current password and set new password to current only when current password is correct. Caller application can determine maximum number of attempts and expiration time in days
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] cur_pwd Null terminated current password string. It can be NULL pointer if there is no password set yet - by calling security_server_is_pwd_empty()
+ * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ *
+ * \remarks Only setting application can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ * \remarks If current password exists and it's expired, or max attempts reached, you cannot call this API. You have to call security_server_reset_pwd() API.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
+ * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
+ * {
+ *     printf("%s", "There is no password exists\n");
+ *     ret = security_server_set_pwd(NULL, "this_is_new_pwd", 20, 365);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * }
+ * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
+ * {
+ *     printf("%s", "Password is valid by now\n");
+ *     ret = security_server_set_pwd("this_is_current_pwd", "this_is_new_pwd", 20, 365);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * }
+ * else
+ * {
+ *     printf("%s", "Something wrong\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_set_pwd(const char *cur_pwd,
+                       const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days);
+
+
+/**
+ * \par Description:
+ * This API sets validity period for currently setup password.
+ *
+ * \par Purpose:
+ * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
+ *
+ * \par Typical use case:
+ * Authorized application calls this API to change current passwords validity when password policy needs to be changed.
+ *
+ * \par Method of function operation:
+ * Function attempts to find currently set password and changes its current validity to passed number of days. Retry counter for the password is reset to zero.
+ * If there is no password set, function returns proper error code.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * Identifying calling peer is not ready yet, should be based on SMACK somehow.
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ */
+int security_server_set_pwd_validity(const unsigned int valid_period_in_days);
+
+
+/**
+ * \par Description:
+ * This API sets maximum number of attempts for currently setup password.
+ *
+ * \par Purpose:
+ * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
+ *
+ * \par Typical use case:
+ * Authorized application calls this API to change current passwords max attempt number when password policy needs to be changed.
+ *
+ * \par Method of function operation:
+ * Function attempts to find currently set password and changes its max attempt number to passed one. Retry counter for the password is reset to zero.
+ * If there is no password set, function returns proper error code.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * Identifying calling peer is not ready yet, should be based on SMACK somehow.
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ */
+int security_server_set_pwd_max_challenge(const unsigned int max_challenge);
+
+/**
+ * \par Description:
+ * This API sets phone password only if current password is invalid or user forgot the password.
+ *
+ * \par Purpose:
+ * This API should be used by setting application or dedicated processes when the user changes his/her phone password.
+ *
+ * \par Typical use case:
+ * User forgots the password. He calls emergency manager(auto or manual)  for reset password. Emergency manager calls this API and reset phone password.
+ *
+ * \par Method of function operation:
+ * Resetting phone password with input string without any matching current password.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_set_pwd()
+ *
+ * \remarks Only dedicated applications can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ *     ret = security_server_set_pwd("this_is_new_pwd", 20, 365);
+ *     if(retval != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_reset_pwd(const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days);
+
+/**
+ * \par Description:
+ * This API compares stored phone password with challenged input value.
+ *
+ * \par Purpose:
+ * This API should be used by applications which has phone UI lock capability.
+ *
+ * \par Typical use case:
+ * Lock screen calls this API after user typed phone password and pressed okay.
+ *
+ * \par Method of function operation:
+ * Sends challenged password to security-server, security-server compares hashed current password and hashed challenged password.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] challenge Null terminated challenged password string. It must not a NULL pointer.
+ * \param[out] current_attempts Number of password check missed attempts.
+ * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
+ * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Applications which has phone UI lock feature.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_set_pwd()
+ *
+ * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * retval = security_server_chk_pwd("is_this_password", &attmpt, &max_attempt, &expire_sec);
+ * if(retval == SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
+ * {
+ *     printf("%s", "Oh you typed wrong password\n");
+ *     ...
+ * }
+ * else if(retval == SECURITY_SERVER_API_SUCCESS)
+ * {
+ *     printf("%s", "You remember your password.\n");
+ *     ...
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_chk_pwd(const char *challenge,
+                       unsigned int *current_attempt,
+                       unsigned int *max_attempt,
+                       unsigned int *valid_secs);
+
+
+/**
+ * \par Description:
+ * This API set the number of password history which should be maintained. Once this number set, user cannot reuse recent number of passwords which is described in this history value
+ *
+ * \par Purpose:
+ * This API should be used only by dedicated process in the platform.
+ *
+ * \par Typical use case:
+ * Enterprise manager calls this API when the enterprise wants to enforce harder password policy.
+ *
+ * \par Method of function operation:
+ * When enterprise manager (MDM) is trying to change the security policy for phone password, it calls this API background to change the history policy.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] number_of_history Number of history to be checked when user tries to change password. Maximum is currently 50
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * MDM client, Enterprise manager.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_set_pwd()
+ *
+ * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ *
+ * ret = security_server_set_pwd_history(100);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "You have error\n");
+ *             ...
+ *     }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_set_pwd_history(int number_of_history);
+
+
+
+/**
+ * \par Description:
+ * This API launches /usr/bin/debug-util as root privilege.
+ *
+ * \par Purpose:
+ * This API will be used only by SDK with developer privilege to launch debugging tool to debug as the developing applicaion's privilege.
+ *
+ * \par Typical use case:
+ * During appliation development, SDK opens a shell to install, launch, and debug the developing application. But the shell will not have any privilege to control platform. Therefore we need a special utility to manage debugging environement as same privilege level of the application. If this API is called, security server will launch the debug utility as root privilege and the utility will drop its privilege same as developing application
+ *
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it checks uid of the client, and launches /usr/bin/debug-util with given arguements.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Caller process of this API must be owned by developer user.\n
+ * The caller process will be pre-defined.
+ * /usr/bin/debug-util itself must be omitted in the argv. Security server will put this as first argv in the execution procedure
+ *
+ * \param[in] argc Number of arguements.
+ *
+ * \param[in] argv Arguements
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend debugging utility.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see None
+ *
+ * \remarks Calling this API, you have to put argv[1] of the debug-util as argv[0] of this API. Security server will put argv[0] automatically
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * #define DEVELOPER_UID 5500
+ *
+ * int main(int argc, char **argv)
+ * {
+ *     int my_uid, ret;
+ *     uid = getuid();
+ *     if(uid != DEVELOPER_UID)
+ *     {
+ *             // You must be developer user
+ *             exit(1);
+ *     }
+ *
+ *     ret = security_server_launch_debug_tool(argc -1, argv++)
+ *     if(ret != SECURITY_SERVER_SUCCESS)
+ *     {
+ *             // Some error occurred
+ *             exit(1);
+ *     }
+ *     ...
+ * }
+ *
+ * \endcode
+*/
+int security_server_launch_debug_tool(int argc, const char **argv);
+
+/*
+ * This function allows to get process SMACK label by passing cookie assigned
+ * to process. Function returns pointer to allocated buffer with label.
+ * User has to free the buffer after using.
+ *
+ * \param[in] Pointer to cookie
+ *
+ * \return Pointer to SMACK label or NULL
+ *
+ * \par For free label use free(), label allocated by calloc()
+ *      User responsibility is to free resource.
+ */
+char * security_server_get_smacklabel_cookie(const char *cookie);
+
+/*
+ * This function allows to get process SMACK label by passing socket descriptor.
+ * Function returns pointer to allocated buffer with label.
+ * User has to free the buffer after using.
+ *
+ * \param[in] Socket descriptor
+ *
+ * \return Pointer to SMACK label or NULL
+ *
+ * \par For free label use free(), label allocated by calloc().
+ *      User responsibility is to free resource.
+ */
+char * security_server_get_smacklabel_sockfd(int fd);
+
+#ifdef __cplusplus
+}
+#endif
+
+/**
+ * @}
+*/
+
+/**
+ * @}
+*/
+
+#endif
diff --git a/src/main.cpp b/src/main.cpp
deleted file mode 100644 (file)
index 93c9fa7..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        main.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This is main routing for Security Daemon
- */
-
-#include <dpl/log/log.h>
-#include <dpl/single_instance.h>
-
-#include "security_daemon.h"
-
-#include <pthread.h>
-
-static const std::string DAEMON_INSTANCE_UUID =
-    "5ebf3f24-dad6-4a27-88b4-df7970efe7a9";
-
-int main(int argc, char* argv[])
-{
-    DPL::SingleInstance instance;
-    try {
-        if (!instance.TryLock(DAEMON_INSTANCE_UUID)) {
-            LogError("Security Daemon is already running");
-            return -1;
-        }
-    } catch (const DPL::SingleInstance::Exception::LockError &e) {
-        LogError(e.DumpToString());
-        return -1;
-    }
-
-    auto& daemon = SecurityDaemonSingleton::Instance();
-
-    daemon.initialize(argc, argv);
-
-    //Run daemon
-    auto retVal = daemon.execute();
-
-    daemon.shutdown();
-    try {
-        instance.Release();
-    } catch (const DPL::SingleInstance::Exception::LockError &e) {
-        LogError(e.DumpToString());
-    }
-
-    return retVal;
-}
diff --git a/src/mw-list b/src/mw-list
new file mode 100644 (file)
index 0000000..14a8890
--- /dev/null
@@ -0,0 +1,12 @@
+/usr/bin/telephony-server
+/usr/bin/ss-server
+/usr/bin/msg-server
+/usr/bin/alarm-server
+/usr/bin/lbs_server
+/usr/bin/power_manager
+/usr/bin/system_server
+/usr/bin/sec-svr-util
+/usr/bin/mdm-server
+/usr/bin/smartcard-daemon
+/usr/bin/sound_server
+/usr/bin/nfc-manager-daemon
diff --git a/src/security-serverd b/src/security-serverd
new file mode 100644 (file)
index 0000000..36344cc
--- /dev/null
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+# start secure-storage server
+/usr/bin/security-server &
+set_pmon -p security-server
diff --git a/src/security-srv/CMakeLists.txt b/src/security-srv/CMakeLists.txt
deleted file mode 100644 (file)
index fe5bfc0..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-PKG_CHECK_MODULES(SECURITY_SERVER_DEP
-    dlog
-    openssl
-    libsmack
-    REQUIRED
-    )
-
-SET(SECURITY_SERVER_PATH ${PROJECT_SOURCE_DIR}/src/security-srv)
-
-SET(SECURITY_SERVER_SOURCES
-    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
-    ${SECURITY_SERVER_PATH}/server/security-server-cookie.c
-    ${SECURITY_SERVER_PATH}/server/security-server-main.c
-    ${SECURITY_SERVER_PATH}/server/security-server-password.c
-    ${SECURITY_SERVER_PATH}/util/security-server-util-common.c
-    )
-
-SET_SOURCE_FILES_PROPERTIES(
-    ${SECURITY_SERVER_SOURCES}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -DSECURITY_SERVER_DEBUG_DLOG")
-
-INCLUDE_DIRECTORIES(
-    ${SECURITY_SERVER_PATH}/include
-    ${SECURITY_SERVER_DEP_INCLUDE_DIRS}
-    )
-
-ADD_EXECUTABLE(${TARGET_SECURITY_SERVER} ${SECURITY_SERVER_SOURCES})
-
-TARGET_LINK_LIBRARIES(${TARGET_SECURITY_SERVER}
-    ${SECURITY_SERVER_DEP_LIBRARIES}
-    )
-
-################################################################################
-
-SET(SECURITY_CLIENT_VERSION_MAJOR 1)
-SET(SECURITY_CLIENT_VERSION ${SECURITY_CLIENT_VERSION_MAJOR}.0.1)
-
-SET(SECURITY_CLIENT_SOURCES
-    ${SECURITY_SERVER_PATH}/client/security-server-client.c
-    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
-    )
-
-ADD_LIBRARY(${TARGET_SECURITY_CLIENT} SHARED ${SECURITY_CLIENT_SOURCES})
-
-SET_TARGET_PROPERTIES(
-    ${TARGET_SECURITY_CLIENT}
-    PROPERTIES
-        LINK_FLAGS "-module -avoid-version"
-        COMPILE_FLAGS "-D_GNU_SOURCE -DSECURITY_SERVER_DEBUG_DLOG -fPIC"
-        SOVERSION ${SECURITY_CLIENT_VERSION_MAJOR}
-        VERSION ${SECURITY_CLIENT_VERSION}
-    )
-
-TARGET_LINK_LIBRARIES(${TARGET_SECURITY_CLIENT}
-    ${SECURITY_SERVER_DEP_LIBRARIES}
-    )
-
-################################################################################
-
-INSTALL(TARGETS ${TARGET_SECURITY_CLIENT} DESTINATION lib)
-
-INSTALL(TARGETS ${TARGET_SECURITY_SERVER} DESTINATION bin)
-
-INSTALL(FILES
-    ${SECURITY_SERVER_PATH}/include/security-server.h
-    DESTINATION /usr/include/security-server
-    )
-
-INSTALL(FILES
-    ${SECURITY_SERVER_PATH}/mw-list
-    DESTINATION /usr/share/security-server
-    )
-
-INSTALL(FILES
-    ${SECURITY_SERVER_PATH}/security-serverd
-    DESTINATION /etc/rc.d/init.d
-    )
-
-################################################################################
-
-#CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
-#INSTALL
-
-################################################################################
diff --git a/src/security-srv/client/security-server-client.c b/src/security-srv/client/security-server-client.c
deleted file mode 100644 (file)
index 68e83a0..0000000
+++ /dev/null
@@ -1,1111 +0,0 @@
-/*
- * security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <unistd.h>
-#include <string.h>
-#include <sys/smack.h>
-#include <fcntl.h>
-
-#include "security-server.h"
-#include "security-server-common.h"
-#include "security-server-comm.h"
-
-#if 0
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0xF)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-
-char *read_cmdline_from_proc(pid_t pid)
-{
-       int memsize = 32;
-       char path[32];
-       char *cmdline = NULL;
-
-       snprintf(path, sizeof(path), "/proc/%d/exe", pid);
-
-       cmdline = malloc(32);
-       if(cmdline == NULL)
-       {
-               SEC_SVR_DBG("%s", "Out of memory");
-               goto error;
-       }
-
-       while(1)
-       {
-               bzero(cmdline, memsize);
-               /* readlink() may have security hole in normal symbolic link. *
-                * But this link is located at proc fs that only kernel can change */
-               readlink(path, cmdline, memsize);       /* FlawFinder: ignore */
-SEC_SVR_DBG("pid: %d, cmdline: %s", pid, cmdline);
-
-               /* Check it's truncated */
-               if(cmdline[memsize -1] != 0)
-               {
-                       cmdline = (char *)realloc(cmdline, sizeof(char) * (memsize + 32));
-                       memsize += 32;
-                       if(cmdline == NULL)
-                       {
-                               SEC_SVR_DBG("%s", "Out of memory");
-                               goto error;
-                       }
-               }
-               else
-                       break;
-       }
-
-error:
-       return cmdline;
-}
-#endif
-
-
-/* We may need to filter error code */
-int convert_to_public_error_code(int err_code)
-{
-       /* Do we need this? */
-       return err_code;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_get_gid(const char *object)
-{
-       int sockfd = -1, retval, gid;
-       response_header hdr;
-
-       if(object == NULL)
-       {
-               SEC_SVR_DBG("%s", "Client: object is null or object is too big");
-               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-               goto error;
-       }
-       if( strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME )
-       {
-               SEC_SVR_DBG("%s", "object is null or object is too big");
-               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       if(strlen(object) == 0)
-       {
-               SEC_SVR_DBG("Client: object is is empty");
-               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       SEC_SVR_DBG("%s", "Client: security_server_get_gid() is called");
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Connection failed: %d", retval);
-               goto error;
-       }
-       SEC_SVR_DBG("%s", "Client: Security server has been connected");
-
-       /* make request packet and send to server*/
-       retval = send_gid_request(sockfd, object);
-       SEC_SVR_DBG("%s", "Client: gid request has been sent");
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Send gid request failed: %d", retval);
-               goto error;
-       }
-
-       /* Receive response */
-       retval = recv_get_gid_response(sockfd, &hdr, &gid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
-               goto error;
-       }
-       SEC_SVR_DBG("%s", "Client: get gid response has been received");
-
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GID_RESPONSE)       /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: It'll be an error. return code:%d", hdr.return_code);
-                       retval = return_code_to_error_code(hdr.return_code);
-                       goto error;
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client: Something wrong with response:%d", hdr.basic_hdr.msg_id);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-                       goto error;
-               }
-       }
-
-       SEC_SVR_DBG("received gid is %d", gid);
-       retval = gid;
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-       /* If error happened */
-       if(retval < 0)
-               retval = convert_to_public_error_code(retval);
-
-       return retval;
-}
-
-
-
-
-       SECURITY_SERVER_API
-int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(object == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: connect to server failed: %d", retval);
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_object_name_request(sockfd, gid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: cannot send request: %d", retval);
-               goto error;
-       }
-
-       retval = recv_get_object_name(sockfd, &hdr, object, max_object_size);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
-               goto error;
-       }
-
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE)       /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: There is error on response: return code:%d", hdr.basic_hdr.msg_id);
-                       retval = return_code_to_error_code(hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client: Some unexpected error happene: return code:%d", hdr.basic_hdr.msg_id);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_request_cookie(char *cookie, size_t max_cookie)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(cookie == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-       if(max_cookie < SECURITY_SERVER_COOKIE_LEN)
-       {
-               retval = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
-               goto error;
-       }
-
-       SEC_SVR_DBG("%s", "Client: security_server_request_cookie() is called");
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("%s", "Client: connection failed");
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_cookie_request(sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: send cookie failed: %d", retval);
-               goto error;
-       }
-       SEC_SVR_DBG("%s", "Client: cookie request sent");
-       retval = recv_cookie(sockfd, &hdr, cookie);
-
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE)    /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client ERROR: There is an error on response. return code:%d", hdr.return_code);
-                       retval = return_code_to_error_code(hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-       SEC_SVR_DBG("%s", "Client: cookie received");
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-
-
-
-       SECURITY_SERVER_API
-int security_server_check_privilege(const char *cookie, gid_t privilege)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(cookie == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_privilege_check_request(sockfd, cookie, privilege);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_privilege_check_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE)   /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-       SECURITY_SERVER_API
-int security_server_check_privilege_by_cookie(const char *cookie,
-                                              const char *object,
-                                              const char *access_rights)
-{
-       int sockfd = -1, retval;
-        int olen, alen;
-       response_header hdr;
-
-       if(cookie == NULL || object == NULL || access_rights == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-        olen = strlen(object);
-        alen = strlen(access_rights);
-
-        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-        retval = send_privilege_check_new_request(
-                     sockfd, cookie, object, access_rights);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_privilege_check_new_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE)
-        /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d",
-                                    hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-
-error:
-       if(sockfd >= 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-       SECURITY_SERVER_API
-int security_server_check_privilege_by_sockfd(int sockfd,
-                                              const char *object,
-                                              const char *access_rights)
-{
-    char *subject;
-    int ret;
-    ret = smack_new_label_from_socket(sockfd, &subject);
-    if (ret != 0)
-    {
-        return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    }
-    ret = smack_have_access(subject, object, access_rights);
-    SEC_SVR_DBG("check by sockfd, subject >%s< object >%s< rights >%s< ====> %d",
-                subject, object, access_rights, ret);
-    free(subject);
-    if (ret == 1)
-    {
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-    else
-    {
-        return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-    }
-}
-
-
-       SECURITY_SERVER_API
-int security_server_get_cookie_size(void)
-{
-       return SECURITY_SERVER_COOKIE_LEN;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_get_cookie_pid(const char *cookie)
-{
-       int sockfd = -1, retval, pid = -1;
-       response_header hdr;
-
-       if(cookie == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_pid_request(sockfd, cookie);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_pid_response(sockfd, &hdr, &pid);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_PID_RESPONSE)       /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-       if(hdr.return_code == SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE)
-       {
-               SEC_SVR_DBG("%s"," Client: There is no such cookie exist");
-       }
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       if(retval == 0)
-               return pid;
-
-       return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_launch_debug_tool(int argc, const char **argv)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(argc < 1 || argv == NULL || argv[0] == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       if(argc == 1)
-       {
-               if(strcmp(argv[0], SECURITY_SERVER_KILL_APP_PATH) != 0)
-               {
-                       retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-                       goto error;
-               }
-       }
-
-       /* Check the caller is developer shell */
-       retval = getuid();
-       if(retval != SECURITY_SERVER_DEVELOPER_UID)
-       {
-               SEC_SVR_DBG("Client: It's not allowed to call this API by uid %d", retval);
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               goto error;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_launch_tool_request(sockfd, argc, argv);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_generic_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE)      /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_is_pwd_valid(unsigned int *current_attempts,
-       unsigned int *max_attempts,
-       unsigned int *valid_secs)
-{
-       int sockfd = -1, retval = SECURITY_SERVER_ERROR_UNKNOWN;
-       response_header hdr;
-
-       if(current_attempts == NULL || max_attempts == NULL ||valid_secs == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       /* Authenticate self that is setting app  goes here */
-       /* 1st, check cmdline which is setting app */
-       /* 2nd, check /proc/self/attr/current for the SMACK label */
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_valid_pwd_request(sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_pwd_response(sockfd, &hdr, current_attempts, max_attempts, valid_secs);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE) /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_set_pwd(const char *cur_pwd,
-                       const char *new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       /* Authenticate self that is setting app  goes here */
-       /* 1st, check cmdline which is setting app */
-       /* 2nd, check /proc/self/attr/current for the SMACK label */
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_set_pwd_request(sockfd, cur_pwd, new_pwd, max_challenge, valid_period_in_days);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_generic_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE)   /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-       SECURITY_SERVER_API
-int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
-{
-    int sockfd = -1, retval;
-    response_header hdr;
-
-    retval = connect_to_server(&sockfd);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        goto error;
-    }
-
-    /* make request packet */
-    retval = send_set_pwd_validity_request(sockfd, valid_period_in_days);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        SEC_SVR_DBG("Client: Send failed: %d", retval);
-        goto error;
-    }
-
-    retval = recv_generic_response(sockfd, &hdr);
-
-    retval = return_code_to_error_code(hdr.return_code);
-    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE)   /* Wrong response */
-    {
-        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-        {
-            /* There must be some error */
-            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-        }
-        else
-        {
-            /* Something wrong with response */
-            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-        }
-        goto error;
-    }
-error:
-    if(sockfd > 0)
-        close(sockfd);
-
-    retval = convert_to_public_error_code(retval);
-    return retval;
-}
-
-       SECURITY_SERVER_API
-int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
-{
-    int sockfd = -1, retval;
-    response_header hdr;
-
-    retval = connect_to_server(&sockfd);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        goto error;
-    }
-
-    /* make request packet */
-    retval = send_set_pwd_max_challenge_request(sockfd, max_challenge);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        SEC_SVR_DBG("Client: Send failed: %d", retval);
-        goto error;
-    }
-
-    retval = recv_generic_response(sockfd, &hdr);
-
-    retval = return_code_to_error_code(hdr.return_code);
-    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE)   /* Wrong response */
-    {
-        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-        {
-            /* There must be some error */
-            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-        }
-        else
-        {
-            /* Something wrong with response */
-            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-        }
-        goto error;
-    }
-error:
-    if(sockfd > 0)
-        close(sockfd);
-
-    retval = convert_to_public_error_code(retval);
-    return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_reset_pwd(const char *new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       /* Authenticate self that is setting app  goes here */
-       /* 1st, check cmdline which is setting app */
-       /* 2nd, check /proc/self/attr/current for the SMACK label */
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_reset_pwd_request(sockfd, new_pwd, max_challenge, valid_period_in_days);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_generic_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE) /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-
-
-       SECURITY_SERVER_API
-int security_server_chk_pwd(const char *challenge,
-       unsigned int *current_attempt,
-       unsigned int *max_attempts,
-       unsigned int *valid_secs)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(challenge == NULL || strlen(challenge) > SECURITY_SERVER_MAX_PASSWORD_LEN
-               || current_attempt == NULL || max_attempts == NULL || valid_secs == NULL)
-       {
-               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-               goto error;
-       }
-
-       /* Authenticate self goes here */
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_chk_pwd_request(sockfd, challenge);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-
-       retval = recv_pwd_response(sockfd, &hdr, current_attempt, max_attempts, valid_secs);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE)   /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-       SECURITY_SERVER_API
-int security_server_set_pwd_history(int number_of_history)
-{
-       int sockfd = -1, retval;
-       response_header hdr;
-
-       if(number_of_history > SECURITY_SERVER_MAX_PASSWORD_HISTORY || number_of_history < 0)
-               return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-       /* Authenticate self that is setting app  goes here */
-       /* 1st, check cmdline which is setting app */
-       /* 2nd, check /proc/self/attr/current for the SMACK label */
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_set_pwd_history_request(sockfd, number_of_history);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Send failed: %d", retval);
-               goto error;
-       }
-       retval = recv_generic_response(sockfd, &hdr);
-
-       retval = return_code_to_error_code(hdr.return_code);
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE)   /* Wrong response */
-       {
-               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-               {
-                       /* There must be some error */
-                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-               }
-               else
-               {
-                       /* Something wrong with response */
-                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-               goto error;
-       }
-error:
-       if(sockfd > 0)
-               close(sockfd);
-
-       retval = convert_to_public_error_code(retval);
-       return retval;
-}
-
-SECURITY_SERVER_API
-char * security_server_get_smacklabel_cookie(const char * cookie)
-{
-    char * label = NULL;
-    int sockfd = -1, retval, pid = -1;
-    response_header hdr;
-
-    if(cookie == NULL)
-    {
-        retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
-        goto error;
-    }
-
-    retval = connect_to_server(&sockfd);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        goto error;
-    }
-
-    /* make request packet */
-    retval = send_smack_request(sockfd, cookie);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Error on socket */
-        SEC_SVR_DBG("Client: Send failed: %d", retval);
-        goto error;
-    }
-
-    //allocating buffer for storing SMACK label received from server
-    label = calloc(SMACK_LABEL_LEN + 1, 1);
-    if(NULL == label)
-    {
-        SEC_SVR_DBG("Client ERROR: Memory allocation error");
-        goto error;
-    }
-
-    retval = recv_smack_response(sockfd, &hdr, label);
-
-    retval = return_code_to_error_code(hdr.return_code);
-    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE)        /* Wrong response */
-    {
-        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
-        {
-            /* There must be some error */
-            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
-        }
-        else
-        {
-            /* Something wrong with response */
-            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
-            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
-        }
-        goto error;
-    }
-    if(hdr.return_code == SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE)
-    {
-        SEC_SVR_DBG("%s"," Client: There is no such cookie exist");
-    }
-
-error:
-    if(sockfd > 0)
-        close(sockfd);
-
-    retval = convert_to_public_error_code(retval);
-    if(retval == 0)
-        return label;
-
-    if(NULL != label)
-        free(label);
-
-    return NULL;
-}
-
-       SECURITY_SERVER_API
-char * security_server_get_smacklabel_sockfd(int fd)
-{
-       char * label = NULL;
-
-       if(smack_new_label_from_socket(fd, &label) != 0)
-       {
-               SEC_SVR_DBG("Client ERROR: Unable to get socket SMACK label");
-               return NULL;
-       }
-
-       return label;
-}
-
-
diff --git a/src/security-srv/communication/security-server-comm.c b/src/security-srv/communication/security-server-comm.c
deleted file mode 100644 (file)
index 56a4d14..0000000
+++ /dev/null
@@ -1,2497 +0,0 @@
-/*
- * security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <sys/poll.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <fcntl.h>
-#include <pwd.h>
-#include <sys/un.h>
-#include <errno.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <limits.h>
-
-#include "security-server-common.h"
-#include "security-server-comm.h"
-
-void printhex(const unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0xF)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-char *read_cmdline_from_proc(pid_t pid)
-{
-       int memsize = 32;
-       char path[32];
-       char *cmdline = NULL, *tempptr = NULL;
-       FILE *fp = NULL;
-
-       snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
-
-       fp = fopen(path, "r");
-       if(fp == NULL)
-       {
-               SEC_SVR_DBG("Cannot open cmdline on pid[%d]", pid);
-               return NULL;
-       }
-
-       cmdline = malloc(32);
-       if(cmdline == NULL)
-       {
-               SEC_SVR_DBG("%s", "Out of memory");
-               fclose(fp);
-               return NULL;
-       }
-
-       bzero(cmdline, memsize);
-       if(fgets(cmdline, 32, fp) == NULL)
-       {
-               SEC_SVR_DBG("%s", "Cannot read cmdline");
-               free(cmdline);
-               fclose(fp);
-               return NULL;
-       }
-
-       while(cmdline[memsize -2] != 0)
-       {
-               cmdline[memsize -1] = (char) fgetc(fp);
-               tempptr = realloc(cmdline, memsize + 32);
-               if(tempptr == NULL)
-               {
-                       fclose(fp);
-                       SEC_SVR_DBG("%s", "Out of memory");
-                       return NULL;
-               }
-               cmdline = tempptr;
-               bzero(cmdline + memsize, 32);
-               fgets(cmdline + memsize, 32, fp);
-               memsize += 32;
-       }
-
-       if(fp != NULL)
-               fclose(fp);
-       return cmdline;
-}
-
-/* Return code in packet is positive integer *
- * We need to convert them to error code which are negative integer */
-int return_code_to_error_code(int ret_code)
-{
-       int ret;
-       switch(ret_code)
-       {
-               case SECURITY_SERVER_RETURN_CODE_SUCCESS:
-               case SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED:
-                       ret = SECURITY_SERVER_SUCCESS;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_BAD_REQUEST:
-                       ret = SECURITY_SERVER_ERROR_BAD_REQUEST;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED:
-                       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED:
-                       ret = SECURITY_SERVER_ERROR_ACCESS_DENIED;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT:
-                       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_SERVER_ERROR:
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE:
-                       ret = SECURITY_SERVER_ERROR_NO_SUCH_COOKIE;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_NO_PASSWORD:
-                       ret = SECURITY_SERVER_ERROR_NO_PASSWORD;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXIST;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
-                       break;
-               case SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED:
-                       ret = SECURITY_SERVER_ERROR_PASSWORD_REUSED;
-                       break;
-               default:
-                       ret = SECURITY_SERVER_ERROR_UNKNOWN;
-                       break;
-       }
-       return ret;
-}
-
-int check_socket_poll(int sockfd, int event, int timeout)
-{
-       struct pollfd poll_fd[1];
-       int retval = SECURITY_SERVER_ERROR_POLL;
-
-       poll_fd[0].fd = sockfd;
-       poll_fd[0].events = event;
-       retval = poll(poll_fd, 1, timeout);
-       if(retval < 0)
-       {
-               SEC_SVR_DBG("poll() error. errno=%d", errno);
-               if(errno != EINTR)
-                       return SECURITY_SERVER_ERROR_POLL;
-               else
-               {
-                       /* Chile process has been closed. Not poll() problem. Call it once again */
-                       return check_socket_poll(sockfd, event, timeout);
-               }
-       }
-
-       /* Timed out */
-       if(retval == 0)
-       {
-               return SECURITY_SERVER_ERROR_TIMEOUT;
-       }
-
-       if(poll_fd[0].revents != event)
-       {
-               SEC_SVR_DBG("Something wrong on the peer socket. event=0x%x", poll_fd[0].revents);
-               return SECURITY_SERVER_ERROR_POLL;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int safe_server_sock_close(int client_sockfd)
-{
-       struct pollfd poll_fd[1];
-       int retval;
-       retval = SECURITY_SERVER_ERROR_POLL;
-       poll_fd[0].fd = client_sockfd;
-       poll_fd[0].events = POLLRDHUP;
-       retval = poll(poll_fd, 1, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       SEC_SVR_DBG("%s", "Server: Closing server socket");
-       close(client_sockfd);
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Create a Unix domain socket and bind */
-int create_new_socket(int *sockfd)
-{
-       int retval = 0, localsockfd = 0, flags;
-       struct sockaddr_un serveraddr;
-       mode_t sock_mode;
-
-       /* Deleted garbage Unix domain socket file */
-       retval = remove(SECURITY_SERVER_SOCK_PATH);
-
-    if (retval == -1 && errno != ENOENT) {
-        retval = SECURITY_SERVER_ERROR_UNKNOWN;
-        localsockfd = -1;
-        SEC_SVR_DBG("%s", "Unable to remove /tmp/.security_server.sock");
-        goto error;
-    }
-
-       /* Create Unix domain socket */
-       if((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 )
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               localsockfd = -1;
-               SEC_SVR_DBG("%s", "Socket creation failed");
-               goto error;
-       }
-
-       if(smack_fsetlabel(localsockfd, "@", SMACK_LABEL_IPOUT) != 0)
-       {
-               SEC_SVR_DBG("%s", "SMACK labeling failed");
-               if(errno != EOPNOTSUPP)
-               {
-                       retval = SECURITY_SERVER_ERROR_SOCKET;
-            close(localsockfd);
-                       localsockfd = -1;
-                       goto error;
-               }
-       }
-       if(smack_fsetlabel(localsockfd, "*", SMACK_LABEL_IPIN) != 0)
-       {       SEC_SVR_DBG("%s", "SMACK labeling failed");
-               if(errno != EOPNOTSUPP)
-               {
-                       retval = SECURITY_SERVER_ERROR_SOCKET;
-            close(localsockfd);
-                       localsockfd = -1;
-                       goto error;
-               }
-       }
-
-       /* Make socket as non blocking */
-       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
-                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               close(localsockfd);
-               localsockfd = -1;
-               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
-               goto error;
-       }
-
-       bzero (&serveraddr, sizeof(serveraddr));
-       serveraddr.sun_family = AF_UNIX;
-       strncpy(serveraddr.sun_path, SECURITY_SERVER_SOCK_PATH,
-                       strlen(SECURITY_SERVER_SOCK_PATH));
-       serveraddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
-
-       /* Bind the socket */
-       if((bind(localsockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET_BIND;
-               SEC_SVR_DBG("%s", "Cannot bind");
-               close(localsockfd);
-               localsockfd = -1;
-               goto error;
-       }
-
-
-       /* Change permission to accept all processes that has different uID/gID */
-       sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO);
-       /* Flawfinder hits this chmod function as level 5 CRITICAL as race condition flaw *
-        * Flawfinder recommends to user fchmod insted of chmod
-        * But, fchmod doesn't work on socket file so there is no other choice at this point */
-       if(chmod(SECURITY_SERVER_SOCK_PATH, sock_mode) < 0)             /* Flawfinder: ignore */
-       {
-               SEC_SVR_DBG("%s", "chmod() error");
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               close(localsockfd);
-               localsockfd = -1;
-               goto error;
-       }
-
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       *sockfd = localsockfd;
-       return retval;
-}
-
-/* Authenticate peer that it's really security server.
- * Check UID that is root
- */
-int authenticate_server(int sockfd)
-{
-       int retval;
-       struct ucred cr;
-       unsigned int cl = sizeof(cr);
-/*     char *cmdline = NULL;*/
-
-       /* get socket peer credential */
-       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               SEC_SVR_DBG("%s", "getsockopt() failed");
-               goto error;
-       }
-
-       /* Security server must run as root */
-       if(cr.uid != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               SEC_SVR_DBG("Peer is not root: uid=%d", cr.uid);
-               goto error;
-       }
-       else
-               retval = SECURITY_SERVER_SUCCESS;
-
-       /* Read command line of the PID from proc fs */
-       /* This is commented out because non root process cannot read link of /proc/pid/exe */
-/*     cmdline = read_cmdline_from_proc(cr.pid);
-
-       if(strcmp(cmdline, SECURITY_SERVER_DAEMON_PATH) != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               SEC_SVR_DBG("Cmdline is different. auth failed. cmdline=%s", cmdline);
-       }
-       else
-       {
-               retval = SECURITY_SERVER_SUCCESS;
-               SEC_SVR_DBG("Server authenticatd. %s, sockfd=%d", cmdline, sockfd);
-       }
-*/
-error:
-/*     if(cmdline != NULL)
-               free(cmdline);
-*/
-       return retval;
-}
-
-/* Create a socket and connect to Security Server */
-int connect_to_server(int *fd)
-{
-       struct sockaddr_un clientaddr;
-       int client_len = 0, localsockfd, ret, flags;
-       *fd = -1;
-
-       /* Create a socket */
-       localsockfd = socket(AF_UNIX, SOCK_STREAM, 0);
-       if(localsockfd < 0)
-       {
-               SEC_SVR_DBG("%s", "Error on socket()");
-               return SECURITY_SERVER_ERROR_SOCKET;
-       }
-
-       /* Make socket as non blocking */
-       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
-                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-       {
-               close(localsockfd);
-               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
-               return SECURITY_SERVER_ERROR_SOCKET;
-       }
-
-       bzero(&clientaddr, sizeof(clientaddr));
-       clientaddr.sun_family = AF_UNIX;
-       strncpy(clientaddr.sun_path, SECURITY_SERVER_SOCK_PATH, strlen(SECURITY_SERVER_SOCK_PATH));
-       clientaddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
-       client_len = sizeof(clientaddr);
-
-       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
-       if( ret < 0)
-       {
-               if(errno == EINPROGRESS)
-               {
-                       SEC_SVR_DBG("%s", "Connection is in progress");
-                       ret = check_socket_poll(localsockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-                       if(ret == SECURITY_SERVER_ERROR_POLL)
-                       {
-                               SEC_SVR_DBG("%s", "poll() error");
-                               close(localsockfd);
-                               return SECURITY_SERVER_ERROR_SOCKET;
-                       }
-                       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-                       {
-                               SEC_SVR_DBG("%s", "poll() timeout");
-                               close(localsockfd);
-                               return SECURITY_SERVER_ERROR_SOCKET;
-                       }
-                       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
-                       if(ret < 0)
-                       {
-                               SEC_SVR_DBG("%s", "connection failed");
-                               close(localsockfd);
-                               return SECURITY_SERVER_ERROR_SOCKET;
-                       }
-               }
-               else
-               {
-                       SEC_SVR_DBG("%s", "Connection failed");
-                       close(localsockfd);
-                       return SECURITY_SERVER_ERROR_SOCKET;
-               }
-       }
-
-       /* Authenticate the peer is actually security server */
-       ret = authenticate_server(localsockfd);
-       if(ret  != SECURITY_SERVER_SUCCESS)
-       {
-               close(localsockfd);
-               SEC_SVR_DBG("Authentication failed. %d", ret);
-               return ret;
-       }
-       *fd = localsockfd;
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Accept a new client connection */
-int accept_client(int server_sockfd)
-{
-       /* Call poll() to wait for socket connection */
-       int retval, localsockfd;
-       struct sockaddr_un clientaddr;
-       unsigned int client_len;
-
-       client_len = sizeof(clientaddr);
-
-       /* Check poll */
-       retval = check_socket_poll(server_sockfd, POLLIN, SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "Error on polling");
-               return SECURITY_SERVER_ERROR_SOCKET;
-       }
-
-       /* Timed out */
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               /*SEC_SVR_DBG("%s", "accept() timeout");*/
-               return SECURITY_SERVER_ERROR_TIMEOUT;
-       }
-
-       localsockfd = accept(server_sockfd,
-                       (struct sockaddr *)&clientaddr,
-                       &client_len);
-
-       if(localsockfd < 0)
-       {
-               SEC_SVR_DBG("Cannot accept client. errno=%d", errno);
-               return SECURITY_SERVER_ERROR_SOCKET;
-       }
-       return localsockfd;
-}
-
-/* Minimal check of request packet */
-int validate_header(basic_header hdr)
-{
-       if(hdr.version != SECURITY_SERVER_MSG_VERSION)
-               return SECURITY_SERVER_ERROR_BAD_REQUEST;
-
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send generic response packet to client
- *
- * Generic Response Packet Format
- 0                   1                   2                   3
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
-|---------------------------------------------------------------|
-| version=0x01  |  Message ID   |Message Length (without header)|
-|---------------------------------------------------------------|
-|  return code  |
------------------
-*/
-int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code)
-{
-       response_header hdr;
-       int size;
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = msgid;
-       hdr.basic_hdr.msg_len = 0;
-       hdr.return_code = return_code;
-
-       /* Check poll */
-       size = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(size == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(size == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to client */
-       size = write(sockfd, &hdr, sizeof(hdr));
-
-       if(size < sizeof(hdr))
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send cookie response to client
- *
- * Get Cookie response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- *  |---------------------------------------------------------------|
- *  | version=0x01  |MessageID=0x02 |       Message Length =20      |
- *  |---------------------------------------------------------------|
- *  |  return code  |                                               |
- *  -----------------                                               |
- *  |                 cookie (20 bytes)                             |
- *  |---------------------------------------------------------------|
-*/
-int send_cookie(int sockfd, unsigned char *cookie)
-{
-       response_header hdr;
-       unsigned char msg[SECURITY_SERVER_COOKIE_LEN + sizeof(hdr)];
-       int ret;
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE;
-       hdr.basic_hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-       memcpy(msg, &hdr, sizeof(hdr));
-       memcpy(msg + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       ret = write(sockfd, msg, sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN);
-       if(ret <  sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN)
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Error on write: %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send Object name response *
- * Get Object name response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x06 |       Message Length          |
- * |---------------------------------------------------------------|
- * |  return code  |                                               |
- * -----------------                                               |
- * |                 object name                                   |
- * |---------------------------------------------------------------|
-*/
-int send_object_name(int sockfd, char *obj)
-{
-       response_header hdr;
-       unsigned char msg[strlen(obj) + sizeof(hdr)];
-       int ret;
-
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = 0x06;
-       hdr.basic_hdr.msg_len = strlen(obj);
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-       memcpy(msg, &hdr, sizeof(hdr));
-       memcpy(msg + sizeof(hdr), obj, strlen(obj));
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       ret = write(sockfd, msg, sizeof(hdr) + strlen(obj));
-       if(ret <  sizeof(hdr) + strlen(obj))
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Error on write: %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send GID response to client
- *
- * Get GID response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x08 |       Message Length = 4      |
- * |---------------------------------------------------------------|
- * |  return code  |           gid (first 3 words)                 |
- * |---------------------------------------------------------------|
- * |gid(last word) |
- * |---------------|
-*/
-int send_gid(int sockfd, int gid)
-{
-       response_header hdr;
-       unsigned char msg[sizeof(gid) + sizeof(hdr)];
-       int ret;
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_RESPONSE;
-       hdr.basic_hdr.msg_len = sizeof(gid);
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-       /* Perpare packet */
-       memcpy(msg, &hdr, sizeof(hdr));
-       memcpy(msg + sizeof(hdr), &gid, sizeof(gid));
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send it */
-       ret = write(sockfd, msg, sizeof(hdr) + sizeof(gid));
-       if(ret <  sizeof(hdr) + sizeof(gid))
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Error on write(): %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send PID response to client
- *
- * Get PID response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0a |       Message Length = 4      |
- * |---------------------------------------------------------------|
- * |  return code  |           pid (first 3 words)                 |
- * |---------------------------------------------------------------|
- * |pid(last word) |
- * |---------------|
-*/
-int send_pid(int sockfd, int pid)
-{
-       response_header hdr;
-       unsigned char msg[sizeof(pid) + sizeof(hdr)];
-       int ret;
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_RESPONSE;
-       hdr.basic_hdr.msg_len = sizeof(pid);
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-       /* Perpare packet */
-       memcpy(msg, &hdr, sizeof(hdr));
-       memcpy(msg + sizeof(hdr), &pid, sizeof(pid));
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send it */
-       ret = write(sockfd, msg, sizeof(hdr) + sizeof(pid));
-       if(ret <  sizeof(hdr) + sizeof(pid))
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Error on write(): %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send SMACK label to client with lenght N
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x1e |  Message Length = SMACK_LABEL_LEN + 1
- * |---------------------------------------------------------------|
- * |  return code  |           SMACK label byte 0                  |
- * |---------------------------------------------------------------|
- * |                      ..................                       |
- * |---------------------------------------------------------------|
- * |                      SMACK label byte N                       |
- * |---------------------------------------------------------------|
-*/
-int send_smack(int sockfd, char * label)
-{
-       response_header hdr;
-    //added 1 to the size is for NULL terminating label
-    int LABEL_SIZE = SMACK_LABEL_LEN + 1;
-    int PACKET_SIZE = sizeof(hdr) + LABEL_SIZE;
-       unsigned char msg[PACKET_SIZE];
-       int ret;
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE;
-       hdr.basic_hdr.msg_len = LABEL_SIZE;
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-       /* Perpare packet */
-       memcpy(msg, &hdr, sizeof(hdr));
-       memcpy(msg + sizeof(hdr), label, LABEL_SIZE);
-    memset(msg + sizeof(hdr) + SMACK_LABEL_LEN, 0x00, 1); //adding NULL ad the label end
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send it */
-       ret = write(sockfd, msg, PACKET_SIZE);
-       if(ret <  PACKET_SIZE)
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Error on write(): %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send Check password response to client
- *
- * Check password response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |   MessageID   |       Message Length = 12     |
- * |---------------------------------------------------------------|
- * |  return code  |           attempts (first 3 words)            |
- * |---------------------------------------------------------------|
- * |attempts(rest) |          max_attempts (first 3 words)         |
- * |---------------|-----------------------------------------------|
- * | max_attempts  |          expire_in_days (first 3 words)       |
- * |---------------------------------------------------------------|
- * |expire_in_days |
- * |----------------
- */
-int send_pwd_response(const int sockfd,
-       const unsigned char msg_id,
-       const unsigned char return_code,
-       const unsigned int current_attempts,
-       const unsigned int max_attempts,
-       const unsigned int expire_time)
-{
-       response_header hdr;
-       unsigned int expire_secs;
-       unsigned char msg[sizeof(hdr) + sizeof(current_attempts) + sizeof(max_attempts) + sizeof(expire_secs)];
-       int ret, ptr = 0;
-
-
-       /* Assemble header */
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = msg_id;
-       hdr.basic_hdr.msg_len = sizeof(unsigned int) * 3;
-       hdr.return_code = return_code;
-
-       /* Perpare packet */
-       memcpy(msg, &hdr, sizeof(hdr));
-       ptr += sizeof(hdr);
-       memcpy(msg + ptr, &current_attempts, sizeof(current_attempts));
-       ptr += sizeof(current_attempts);
-       memcpy(msg + ptr, &max_attempts, sizeof(max_attempts));
-       ptr += sizeof(max_attempts);
-       memcpy(msg + ptr, &expire_time, sizeof(expire_time));
-       ptr += sizeof(expire_time);
-
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "Server: poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "Server: poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send it */
-       ret = write(sockfd, msg, ptr);
-       if(ret <  ptr)
-       {
-               /* Error on writing */
-               SEC_SVR_DBG("Server: ERROR on write(): %d", ret);
-               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-               return ret;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send cookie request packet to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x01 |       Message Length = 0      |
- * |---------------------------------------------------------------|
- */
-int send_cookie_request(int sock_fd)
-{
-       basic_header hdr;
-       int retval;
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST;
-       hdr.msg_len = 0;
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, &hdr, sizeof(hdr));
-       if(retval < sizeof(hdr))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send GID request message to security server
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x07 |   Message Length = variable   |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                   Object name (variable)                      |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_gid_request(int sock_fd, const char* object)
-{
-       basic_header hdr;
-       int retval = 0, send_len = 0;
-       unsigned char *buf = NULL;
-
-       if(strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME)
-       {
-               /* Object name is too big*/
-               SEC_SVR_DBG("Object name is too big %dbytes", strlen(object));
-               return SECURITY_SERVER_ERROR_INPUT_PARAM;
-       }
-
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_REQUEST;
-       hdr.msg_len = strlen(object);
-
-       send_len = sizeof(hdr) + strlen(object);
-
-       buf = malloc(send_len);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "out of memory");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), object, strlen(object));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       retval = write(sock_fd, buf, send_len);
-       if(retval < send_len)
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d. errno=%d, sockfd=%d", retval, errno, sock_fd);
-               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       else
-               retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(buf != NULL)
-               free(buf);
-
-       return retval;
-}
-
-/* Send object name request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x05 |       Message Length = 4      |
- * |---------------------------------------------------------------|
- * |                               gid                             |
- * |---------------------------------------------------------------|
- */
-int send_object_name_request(int sock_fd, int gid)
-{
-       basic_header hdr;
-       int retval;
-       unsigned char buf[sizeof(hdr) + sizeof(gid)];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST;
-       hdr.msg_len = sizeof(gid);
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), &gid, sizeof(gid));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, sizeof(buf));
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send privilege check request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x03 |      Message Length = 24      |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                                                               |
- * |                      Cookie (20bytes)                         |
- * |                                                               |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                            GID                                |
- * |---------------------------------------------------------------|
- */
-int send_privilege_check_request(int sock_fd, const char*cookie, int gid)
-{
-       basic_header hdr;
-       int retval;
-       unsigned char buf[sizeof(hdr) + sizeof(gid) + SECURITY_SERVER_COOKIE_LEN];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST;
-       hdr.msg_len = sizeof(gid) + SECURITY_SERVER_COOKIE_LEN;
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &gid, sizeof(gid));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, sizeof(buf));
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int send_privilege_check_new_request(int sock_fd,
-                                     const char *cookie,
-                                     const char *object,
-                                     const char *access_rights)
-{
-       basic_header hdr;
-       int retval;
-        int olen, alen;
-        int size;
-
-        olen = strlen(object);
-        alen = strlen(access_rights);
-        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
-        {
-                return SECURITY_SERVER_ERROR_INPUT_PARAM;
-        }
-
-       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN +
-                          2*sizeof(int) + MAX_OBJECT_LABEL_LEN + MAX_MODE_STR_LEN];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST;
-       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &olen, sizeof(int));
-        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + sizeof(int),
-               &alen, sizeof(int));
-       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int), object, olen);
-       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen,
-               access_rights, alen);
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-        size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
-       /* Send to server */
-       retval = write(sock_fd, buf, size);
-       if(retval < size)
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send SMACK request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x1d |      Message Length = 20      |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                                                               |
- * |                      Cookie (20bytes)                         |
- * |                                                               |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_smack_request(int sock_fd, const char * cookie)
-{
-       basic_header hdr;
-       int retval;
-       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST;
-       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, sizeof(buf));
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send PID check request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x09 |      Message Length = 20      |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                                                               |
- * |                      Cookie (20bytes)                         |
- * |                                                               |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_pid_request(int sock_fd, const char*cookie)
-{
-       basic_header hdr;
-       int retval;
-       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_REQUEST;
-       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, sizeof(buf));
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-
-/* Send debug tool launch request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0b |       Message Length          |
- * |---------------------------------------------------------------|
- * |                        total # of args                        |
- * |---------------------------------------------------------------|
- * |                        1st argv length                        |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                            1st argv                           |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                        2nd argv length                        |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                            2nd argv                           |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                                ...                            |
- * |---------------------------------------------------------------|
- * |                        nth argv length                        |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                            nth argv                           |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_launch_tool_request(int sock_fd, int argc, const char **argv)
-{
-       basic_header hdr;
-       int retval, total_length = 0, ptr, i, tempnum;
-       unsigned char *buf = NULL;
-
-       for (i=0;i<argc;i++)
-       {
-               if(argv[i] == NULL)
-               {
-                       SEC_SVR_DBG("Error: %dth argv is NULL", i);
-                       return SECURITY_SERVER_ERROR_INPUT_PARAM;
-               }
-               total_length += strlen(argv[i]);
-       }
-
-       if(total_length < 1)
-       {
-               SEC_SVR_DBG("Error: There is a problem in argv. [%d]", total_length);
-               return SECURITY_SERVER_ERROR_INPUT_PARAM;
-       }
-       total_length += sizeof(hdr) + sizeof(int) +(argc * sizeof(int));
-
-       if(total_length > 0xffff)
-       {
-               SEC_SVR_DBG("Buffer overflow. too big payload. [%d]", total_length);
-               return SECURITY_SERVER_ERROR_INPUT_PARAM;
-       }
-
-       buf = malloc(total_length);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "Error: failed to malloc()");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST;
-       hdr.msg_len = (unsigned short)total_length;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr = sizeof(hdr);
-       memcpy(buf + ptr, &argc, sizeof(int));
-       ptr += sizeof(hdr);
-
-       /* Assemple each argv length and value */
-       for(i=0;i<argc;i++)
-       {
-               tempnum = strlen(argv[i]);
-               memcpy(buf + ptr, &tempnum, sizeof(int));
-               ptr += sizeof(int);
-               memcpy(buf + ptr, argv[i], tempnum);
-               ptr += tempnum;
-       }
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, total_length);
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(buf != NULL)
-               free(buf);
-       return retval;
-}
-
-/* Send validate password request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0d |       Message Length          |
- * |---------------------------------------------------------------|
- */
-int send_valid_pwd_request(int sock_fd)
-{
-       basic_header hdr;
-       int retval;
-
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST;
-       hdr.msg_len = 0;
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, &hdr, sizeof(hdr));
-       if(retval < sizeof(hdr))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       return retval;
-}
-
-/* Send password set request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0f |       Message Length          |
- * |---------------------------------------------------------------|
- * |  cur_pwd_len  |  new_pwd_len  |                               |
- * |--------------------------------                               |
- * |                            cur pwd                            |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                            new pwd                            |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                         max attempts                          |
- * |---------------------------------------------------------------|
- * |                         valid days                            |
- * |---------------------------------------------------------------|
- */
-int send_set_pwd_request(int sock_fd,
-                       const char*cur_pwd,
-                       const char*new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days)
-{
-       basic_header hdr;
-       int retval, total_length = 0, ptr;
-       unsigned char *buf = NULL, cur_pwd_len, new_pwd_len;
-
-       if(cur_pwd == NULL)
-               cur_pwd_len = 0;
-       else
-               cur_pwd_len = strlen(cur_pwd);
-       new_pwd_len = strlen(new_pwd);
-
-       total_length += sizeof(hdr) + sizeof(char) + sizeof(char) + cur_pwd_len
-               + new_pwd_len + sizeof(unsigned int) + sizeof(unsigned int);
-
-       buf = malloc(total_length);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "Error: failed to malloc()");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST;
-       hdr.msg_len = (unsigned short)total_length;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr = sizeof(hdr);
-       memcpy(buf + ptr, &cur_pwd_len, sizeof(char));
-       ptr += sizeof(char);
-       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
-       ptr += sizeof(char);
-       if(cur_pwd != NULL)
-       {
-               memcpy(buf + ptr, cur_pwd, cur_pwd_len);
-               ptr += cur_pwd_len;
-       }
-       memcpy(buf + ptr, new_pwd, new_pwd_len);
-       ptr += new_pwd_len;
-       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
-       ptr += sizeof(unsigned int);
-       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, total_length);
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(buf != NULL)
-               free(buf);
-       return retval;
-}
-
-/* Send password validity change request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0f |       Message Length          |
- * |---------------------------------------------------------------|
- * |                         valid days                            |
- * |---------------------------------------------------------------|
- */
-int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days)
-{
-    basic_header hdr;
-    int retval, total_length = 0, ptr;
-    unsigned char *buf = NULL;
-
-    total_length = sizeof(hdr) + sizeof(unsigned int);
-
-    buf = malloc(total_length);
-    if(buf == NULL)
-    {
-        SEC_SVR_DBG("%s", "Error: failed to malloc()");
-        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-    }
-
-    /* Assemble header */
-    hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST;
-    hdr.msg_len = (unsigned short)total_length;
-    memcpy(buf, &hdr, sizeof(hdr));
-    ptr = sizeof(hdr);
-    memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
-
-    /* Check poll */
-    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if(retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_DBG("%s", "poll() error");
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-
-    }
-    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_DBG("%s", "poll() timeout");
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-
-    /* Send to server */
-    retval = write(sock_fd, buf, total_length);
-    if(retval < sizeof(buf))
-    {
-        /* Write error */
-        SEC_SVR_DBG("Error on write(): %d", retval);
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-    retval = SECURITY_SERVER_SUCCESS;
-
-error:
-    if(buf != NULL)
-        free(buf);
-    return retval;
-}
-
-/* Send password max challenge request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x0f |       Message Length          |
- * |---------------------------------------------------------------|
- * |                         max challenge                         |
- * |---------------------------------------------------------------|
- */
-int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge)
-{
-    basic_header hdr;
-    int retval, total_length = 0, ptr;
-    unsigned char *buf = NULL;
-
-    total_length = sizeof(hdr) + sizeof(unsigned int);
-
-    buf = malloc(total_length);
-    if(buf == NULL)
-    {
-        SEC_SVR_DBG("%s", "Error: failed to malloc()");
-        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-    }
-
-    /* Assemble header */
-    hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST;
-    hdr.msg_len = (unsigned short)total_length;
-    memcpy(buf, &hdr, sizeof(hdr));
-    ptr = sizeof(hdr);
-    memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
-
-    /* Check poll */
-    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if(retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_DBG("%s", "poll() error");
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-
-    }
-    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_DBG("%s", "poll() timeout");
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-
-    /* Send to server */
-    retval = write(sock_fd, buf, total_length);
-    if(retval < sizeof(buf))
-    {
-        /* Write error */
-        SEC_SVR_DBG("Error on write(): %d", retval);
-        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-    retval = SECURITY_SERVER_SUCCESS;
-
-error:
-    if(buf != NULL)
-        free(buf);
-    return retval;
-}
-
-/* Send password reset request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x11 |       Message Length          |
- * |---------------------------------------------------------------|
- * |  new_pwd_len  |                                               |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                            new pwd                            |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                         max attempts                          |
- * |---------------------------------------------------------------|
- * |                         valid days                            |
- * |---------------------------------------------------------------|
- */
-int send_reset_pwd_request(int sock_fd,
-                       const char*new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days)
-{
-       basic_header hdr;
-       int retval, total_length = 0, ptr;
-       unsigned char *buf = NULL, new_pwd_len;
-
-       new_pwd_len = strlen(new_pwd);
-
-       total_length += sizeof(hdr) + sizeof(char) + new_pwd_len + sizeof(unsigned int) +
-               sizeof(unsigned int);
-
-       buf = malloc(total_length);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "Error: failed to malloc()");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST;
-       hdr.msg_len = (unsigned short)total_length;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr = sizeof(hdr);
-       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
-       ptr += sizeof(char);
-       memcpy(buf + ptr, new_pwd, new_pwd_len);
-       ptr += new_pwd_len;
-       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
-       ptr += sizeof(unsigned int);
-       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, total_length);
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(buf != NULL)
-               free(buf);
-       return retval;
-}
-
-/* Send password check request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x13 |       Message Length          |
- * |---------------------------------------------------------------|
- * | challenge_len |                                               |
- * |---------------                                                |
- * |                          challenge                            |
- * |---------------------------------------------------------------|
- */
-int send_chk_pwd_request(int sock_fd, const char*challenge)
-{
-       basic_header hdr;
-       int retval, total_length = 0, ptr;
-       unsigned char *buf = NULL, challenge_len;
-
-       challenge_len = strlen(challenge);
-
-       total_length += sizeof(hdr) + sizeof(char) + challenge_len;
-
-       buf = malloc(total_length);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "Error: failed to malloc()");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST;
-       hdr.msg_len = (unsigned short)total_length;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr = sizeof(hdr);
-       memcpy(buf + ptr, &challenge_len, sizeof(char));
-       ptr += sizeof(char);
-       memcpy(buf + ptr, challenge, challenge_len);
-       ptr += sizeof(char);
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, total_length);
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(buf != NULL)
-               free(buf);
-       return retval;
-}
-
-/* Send password history set request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x15 |       Message Length          |
- * |---------------------------------------------------------------|
- * | challenge_len |
- * |----------------
- */
-int send_set_pwd_history_request(int sock_fd, int num)
-{
-       basic_header hdr;
-       int retval, total_length = 0, ptr;
-       unsigned char history;
-       unsigned char buf[sizeof(hdr) + sizeof(history)];
-
-       total_length = sizeof(hdr) + sizeof(char);
-       history = (unsigned char) num;
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST;
-       hdr.msg_len = (unsigned short)total_length;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr = sizeof(hdr);
-       memcpy(buf + ptr, &history, sizeof(char));
-       ptr += sizeof(char);
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-
-       /* Send to server */
-       retval = write(sock_fd, buf, ptr);
-       if(retval < sizeof(buf))
-       {
-               /* Write error */
-               SEC_SVR_DBG("Error on write(): %d", retval);
-               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-
-error:
-       return retval;
-}
-
-/* Receive request header */
-int recv_hdr(int client_sockfd, basic_header *basic_hdr)
-{
-       int retval;
-
-       /* Check poll */
-       retval = check_socket_poll(client_sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SOCKET;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_TIMEOUT;
-       }
-
-       /* Receive request header first */
-       retval = read(client_sockfd, basic_hdr, sizeof(basic_header));
-       if(retval < sizeof(basic_header))
-       {
-               SEC_SVR_DBG("read failed. closing socket %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       /* Validate header */
-       retval = validate_header(*basic_hdr);
-       return retval;
-}
-
-
-/* Receive check privilege request packet body */
-int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege)
-{
-       int retval;
-       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(retval < SECURITY_SERVER_COOKIE_LEN)
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       retval = read(sockfd, requested_privilege, sizeof(int));
-       if(retval < sizeof(int))
-       {
-               SEC_SVR_DBG("privilege size is too small: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Receive check privilege request packet body (new mode)*/
-int recv_check_privilege_new_request(int sockfd,
-                                     unsigned char *requested_cookie,
-                                     char *object_label,
-                                     char *access_rights)
-{
-       int retval;
-        int olen, alen;
-
-       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(retval < SECURITY_SERVER_COOKIE_LEN)
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       retval = read(sockfd, &olen, sizeof(int));
-       if(retval < sizeof(int) || olen < 0 || olen > MAX_OBJECT_LABEL_LEN)
-       {
-               SEC_SVR_DBG("error reading object_label len: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       retval = read(sockfd, &alen, sizeof(int));
-       if(retval < sizeof(int) || alen < 0 || alen > MAX_MODE_STR_LEN)
-       {
-               SEC_SVR_DBG("error reading access_rights len: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       retval = read(sockfd, object_label, olen);
-       if(retval < olen)
-       {
-               SEC_SVR_DBG("error reading object_label: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-        object_label[olen] = '\0';
-
-       retval = read(sockfd, access_rights, olen);
-       if(retval < alen)
-       {
-               SEC_SVR_DBG("error reading access_rights: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-        access_rights[alen] = '\0';
-
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Receive pid request packet body */
-int recv_pid_request(int sockfd, unsigned char *requested_cookie)
-{
-       int retval;
-       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(retval < SECURITY_SERVER_COOKIE_LEN)
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* receiving cookie from package */
-int recv_smack_request(int sockfd, unsigned char *requested_cookie)
-{
-       int retval;
-       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(retval < SECURITY_SERVER_COOKIE_LEN)
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Receive pid request packet body */
-int recv_launch_tool_request(int sockfd, int argc, char *argv[])
-{
-       int retval, i, argv_len;
-
-       argv[0] = malloc(strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1);
-       strncpy(argv[0], SECURITY_SERVER_DEBUG_TOOL_PATH, (strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1));
-
-       for(i=1;i<argc;i++)
-       {
-               retval = read(sockfd, &argv_len, sizeof(int));
-               if(retval < sizeof(int))
-               {
-                       SEC_SVR_DBG("Error: argv length recieve failed: %d", retval);
-                       free_argv(argv, argc);
-                       return SECURITY_SERVER_ERROR_RECV_FAILED;
-               }
-
-               if(argv_len <= 0 || argv_len >= INT_MAX)
-               {
-                       SEC_SVR_DBG("Error: argv length out of boundaries");
-                       free_argv(argv, argc);
-                       return SECURITY_SERVER_ERROR_RECV_FAILED;
-               }
-
-               argv[i] = malloc(argv_len + 1);
-               if(argv[i] == NULL)
-               {
-                       SEC_SVR_DBG("Error: malloc() failed: %d", retval);
-                       free_argv(argv, argc);
-                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-               }
-
-               memset(argv[i], 0x00, argv_len + 1);
-               retval = read(sockfd, argv[i], argv_len);
-               if(retval < argv_len)
-               {
-                       SEC_SVR_DBG("Error: argv recieve failed: %d", retval);
-                       free_argv(argv, argc);
-                       return SECURITY_SERVER_ERROR_RECV_FAILED;
-               }
-       }
-
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_generic_response(int sockfd, response_header *hdr)
-{
-       int retval;
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "Client: poll() error");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "Client: poll() timeout");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       /* Receive response */
-       retval = read(sockfd, hdr, sizeof(response_header));
-       if(retval < sizeof(response_header) )
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
-       {
-               SEC_SVR_DBG("Client: return code is not success: %d", hdr->return_code);
-               return return_code_to_error_code(hdr->return_code);
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_get_gid_response(int sockfd, response_header *hdr, int *gid)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(retval != SECURITY_SERVER_SUCCESS)
-               return return_code_to_error_code(hdr->return_code);
-
-       retval = read(sockfd, gid, sizeof(int));
-       if(retval < sizeof(int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size)
-{
-       int retval;
-       char *local_obj_name = NULL;
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       /* Read response */
-       retval = read(sockfd, hdr, sizeof(response_header));
-       if(retval < sizeof(hdr) )
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("cannot recv respons: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       if(hdr->return_code == SECURITY_SERVER_RETURN_CODE_SUCCESS)
-       {
-               if(max_object_size < hdr->basic_hdr.msg_len)
-               {
-                       SEC_SVR_DBG("Object name is too small need %d bytes, but %d bytes", hdr->basic_hdr.msg_len, max_object_size);
-                       return SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
-               }
-               if(hdr->basic_hdr.msg_len > SECURITY_SERVER_MAX_OBJ_NAME)
-               {
-                       SEC_SVR_DBG("Received object name is too big. %d", hdr->basic_hdr.msg_len);
-                       return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-               }
-
-               local_obj_name = malloc(hdr->basic_hdr.msg_len + 1);
-               if(local_obj_name == NULL)
-               {
-                       SEC_SVR_DBG("%s", "Out of memory error");
-                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-               }
-
-               retval = read(sockfd, local_obj_name, hdr->basic_hdr.msg_len);
-               if(retval < (hdr->basic_hdr.msg_len))
-               {
-                       /* Error on socket */
-                       SEC_SVR_DBG("read() failed: %d", retval);
-                       if(local_obj_name != NULL)
-                               free(local_obj_name);
-                       return SECURITY_SERVER_ERROR_RECV_FAILED;
-               }
-               memcpy(object, local_obj_name, hdr->basic_hdr.msg_len);
-               object[hdr->basic_hdr.msg_len] = 0;
-               retval = SECURITY_SERVER_SUCCESS;
-       }
-       else
-       {
-               SEC_SVR_DBG("Error received. return code: %d", hdr->return_code);
-               retval = return_code_to_error_code(hdr->return_code);
-               return retval;
-       }
-
-       if(local_obj_name != NULL)
-               free(local_obj_name);
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_cookie(int sockfd, response_header *hdr, char *cookie)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(retval != SECURITY_SERVER_SUCCESS)
-               return return_code_to_error_code(hdr->return_code);
-
-       retval = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(retval < SECURITY_SERVER_COOKIE_LEN)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("read() failed: %d", retval);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_privilege_check_response(int sockfd, response_header *hdr)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
-                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
-       {
-               SEC_SVR_DBG("response error: %d", hdr->return_code);
-               return return_code_to_error_code(hdr->return_code);
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_privilege_check_new_response(int sockfd, response_header *hdr)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
-                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
-       {
-               SEC_SVR_DBG("response error: %d", hdr->return_code);
-               return return_code_to_error_code(hdr->return_code);
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_smack_response(int sockfd, response_header *hdr, char * label)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(retval != SECURITY_SERVER_SUCCESS)
-               return return_code_to_error_code(hdr->return_code);
-
-       retval = read(sockfd, label, SMACK_LABEL_LEN + 1);
-       if(retval < sizeof(int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_pid_response(int sockfd, response_header *hdr, int *pid)
-{
-       int retval;
-
-       retval = recv_generic_response(sockfd, hdr);
-       if(retval != SECURITY_SERVER_SUCCESS)
-               return return_code_to_error_code(hdr->return_code);
-
-       retval = read(sockfd, pid, sizeof(int));
-       if(retval < sizeof(int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_pwd_response(int sockfd, response_header *hdr,
-       unsigned int *current_attempts,
-       unsigned int *max_attempts,
-       unsigned int *valid_secs)
-{
-       int retval;
-       *current_attempts = 0;
-       *max_attempts = 0;
-       *valid_secs = 0;
-
-       retval = recv_generic_response(sockfd, hdr);
-
-       switch(retval)
-       {
-               case SECURITY_SERVER_ERROR_PASSWORD_EXIST:
-               case SECURITY_SERVER_ERROR_NO_PASSWORD:
-               case SECURITY_SERVER_ERROR_PASSWORD_MISMATCH:
-               case SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER:
-               case SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
-               case SECURITY_SERVER_ERROR_PASSWORD_EXPIRED:
-               case SECURITY_SERVER_ERROR_PASSWORD_REUSED:
-               case SECURITY_SERVER_SUCCESS:
-                       break;
-               default:
-                       return return_code_to_error_code(hdr->return_code);
-       }
-
-       retval = read(sockfd, current_attempts, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       retval = read(sockfd, max_attempts, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       retval = read(sockfd, valid_secs, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Client: Receive failed %d", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-    //if come here there were no errors
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Authenticate client application *
- * Currently it only gets peer's credential information only *
- * If we need, we can extend in the futer */
-int authenticate_client_application(int sockfd, int *pid, int *uid)
-{
-       int retval = 0;
-       struct ucred cr;
-       unsigned int cl = sizeof(cr);
-
-       /* get PID of socket peer */
-       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               SEC_SVR_DBG("%s", "getsockopt failed");
-               *pid = 0;
-               goto error;
-       }
-       *pid = cr.pid;
-       *uid = cr.uid;
-
-       /* Authenticate client that it's real client application */
-       /* TBA */
-
-error:
-       return retval;
-}
-
-/* Checking client is pre-defined middleware daemons *
- * Check privilege API is only allowed to middleware daemons *
- * cmd line list of middleware daemons are listed in
- * /usr/share/security-server/mw-list */
-int search_middleware_cmdline(char *cmdline)
-{
-       FILE *fp = NULL;
-       int ret;
-       char middleware[SECURITY_SERVER_MAX_PATH_LEN];
-
-       /* Open the list file */
-       fp = fopen(SECURITY_SERVER_MIDDLEWARE_LIST_PATH, "r");
-       if(fp == NULL)
-       {
-               /* error on file */
-               SEC_SVR_DBG("%s", "Error oening mw-list file");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-
-       /* Search each line */
-       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-       while(fgets(middleware, SECURITY_SERVER_MAX_PATH_LEN, fp) != NULL)
-       {
-               if(strncmp(middleware, cmdline, strlen(middleware)-1) == 0)
-               {
-                       /* found */
-                       SEC_SVR_DBG("%s", "found matching cmd line");
-                       ret = SECURITY_SERVER_SUCCESS;
-                       break;
-               }
-
-       }
-       if(fp != NULL)
-               fclose(fp);
-       return ret;
-}
-
-/* Authenticate the application is middleware daemon
- * The middleware must run as root (or middleware user) and the cmd line must be
- * pre listed for authentication to succeed */
-int authenticate_client_middleware(int sockfd, int *pid)
-{
-       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-       struct ucred cr;
-       unsigned int cl = sizeof(cr);
-       char *cmdline = NULL;
-       struct passwd pw, *ppw;
-       size_t buf_size;
-       char *buf;
-       static uid_t middleware_uid = 0;
-
-       *pid = 0;
-
-       /* get PID of socket peer */
-       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               SEC_SVR_DBG("%s", "Error on getsockopt");
-               goto error;
-       }
-
-       if (!middleware_uid)
-       {
-               buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
-               if (buf_size == -1)
-                       buf_size = 1024;
-
-               buf = malloc(buf_size);
-
-               /* This test isn't essential, skip it in case of error */
-               if (buf) {
-                       if (getpwnam_r(SECURITY_SERVER_MIDDLEWARE_USER, &pw, buf, buf_size, &ppw) == 0 && ppw)
-                               middleware_uid = pw.pw_uid;
-
-                       free(buf);
-               }
-       }
-
-       /* Middleware services need to run as root or middleware/app user */
-       if(cr.uid != 0 && cr.uid != middleware_uid)
-       {
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
-               goto error;
-       }
-
-       /* Read command line of the PID from proc fs */
-       cmdline = read_cmdline_from_proc(cr.pid);
-       if(cmdline  == NULL)
-       {
-               /* It's weired. no file in proc file system, */
-               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
-               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
-               goto error;
-       }
-
-       /* Search cmdline of the peer that is really middleware executable */
-       retval = search_middleware_cmdline(cmdline);
-       *pid = cr.pid;
-
-error:
-       if(cmdline != NULL)
-               free(cmdline);
-
-       return retval;
-}
-
-/* Authenticate the application is middleware daemon
- * The middleware must run as root and the cmd line must be pre listed */
-int authenticate_developer_shell(int sockfd)
-{
-       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-       struct ucred cr;
-       unsigned int cl = sizeof(cr);
-       char *cmdline = NULL;
-
-       /* get PID of socket peer */
-       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-       {
-               retval = SECURITY_SERVER_ERROR_SOCKET;
-               SEC_SVR_DBG("%s", "Error on getsockopt");
-               goto error;
-       }
-
-       /* All middlewares will run as root */
-       if(cr.uid != SECURITY_SERVER_DEVELOPER_UID)
-       {
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
-               goto error;
-       }
-
-       /* Read command line of the PID from proc fs */
-       cmdline = read_cmdline_from_proc(cr.pid);
-       if(cmdline  == NULL)
-       {
-               /* It's weired. no file in proc file system, */
-               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
-               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
-               goto error;
-       }
-
-       /* Search cmdline of the peer that is really debug tool */
-       if(strncmp(cmdline, SECURITY_SERVER_DEBUG_TOOL_PATH, strlen(SECURITY_SERVER_DEBUG_TOOL_PATH)) != 0)
-       {
-               SEC_SVR_DBG("Error: Wrong cmdline [%s]", cmdline);
-               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-               goto error;
-       }
-       retval = SECURITY_SERVER_SUCCESS;
-       SEC_SVR_DBG("%s", "Client Authenticated");
-
-error:
-       if(cmdline != NULL)
-               free(cmdline);
-
-       return retval;
-}
-
-int free_argv(char **argv, int argc)
-{
-       int i;
-       if(argv == NULL)
-       {
-               SEC_SVR_DBG("%s", "Cannot free NULL pointer");
-               return SECURITY_SERVER_ERROR_INPUT_PARAM;
-       }
-       for (i=0;i<argc;i++)
-       {
-               if(argv[i] != NULL)
-                       free(argv[i]);
-       }
-       free(argv);
-       return SECURITY_SERVER_SUCCESS;
-}
-
diff --git a/src/security-srv/include/SLP_security-model_PG.h b/src/security-srv/include/SLP_security-model_PG.h
deleted file mode 100644 (file)
index 0f2dc07..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * @defgroup SLP_PG_SECURITY Security and Permissions
- * @ingroup SLP_PG
- * @{
- *     @brief  <em class="ref">Also see </em>  [ @ref SecurityFW ]
- *     @defgroup CertificateManager_PG
- *     @defgroup Security_Server_PG
- *     @defgroup SecureStorage_PG
- *     @}
- *     @defgroup SLP_PG_SECURITY
- *     @ingroup SLP_PG
- *     @{
-
-<h1 class="pg">Security Requirements</h1>
-<h2>Privileges </h2>
-<p>All processes MUST have least privilege to operate their own purpose. middleware daemons might run as root to satisfy their functional requirements, but there MUST BE NO application process which is running as root. In this document application represents all processes which has user interface to the end user.</p>
-<p>Each application process should have different privileges to satisfy least privilege, therefore there should be an entity to take care of process privileges.</p>
-<p>If an application process requires higher (system or root) privilege to provide some function, the function must be implemented in a middleware daemon and the function must be provided as an API to application</p>
-<h2>Application Sandboxing</h2>
-<p>All applications MUST NOT interfere each other. Interference covers killing other processes, modify or delete other application's files, overwrite or read other application process' memory area, masquerading other applications, and reading other application's sensitive files.</p>
-<h2>Middleware Resource Protection</h2>
-<p>All middleware resources MUST be protected by unauthorized access from applications. If the middleware is a daemon process, the process must not be interfered by applications, if the middleware is a library and the resources of the middleware are files, then the files must not be modified by unauthorized process.</p>
-<p>The resources must be protected at the resource level, not API level because API could be easily detoured</p>
-<h2>Privilege Escalation</h2>
-<p>There should be no privilege escalation, but by some management and/or manufacturing reason, unpredicted privilege escalation might be necessary. In this situation the modules which require privilege escalation MUST be highly reviewed and managed by developers and security manager.</p>
-<h1 class="pg">Security Model</h1>
-<h2>Background Information</h2>
-<h3>Discretionary Access Control</h3>
-<p>Linux kernel have supported discretionary access control (DAC) from the very beginning which controls access based on user ID, group ID of a process and owner of file that the process tries to access. This access control mechanism has been evolved with the Linux system evolution, additionally, SLP is not an embedded Linux platform but a normal Linux platform, therefore SLP has full support on DAC.</p>
-<p>In Linux all process is executed with user ID and groups, normally inherited by parent process. The processes which are executed in booting script will be executed as root user because the parent process "init" is root process. Any other user processes including user shell will be executed as an user that is logged in by the console login process. The groups that the process belongs to are also inherited by parent process, the list of group ID is assigned when the user is logged in based on "/etc/group" file. A process can be belonged more than thousand of groups (max 65,536 but I think too many groups might occur some problem).</p>
-<p>Only root process can change user ID and groups of the process by calling setuid() and setgroups() function, so if a root process is changed user to non root, then it can never change its user ID and groups again.</p>
-<p>There is a special feature to change user ID even the process is not owned by root user. If the executable file has setuid sticky bit, then the process will be executed as the owner of executable files. This is very important for access control because it can produce "privilege escalation" which can harm the platform security. In Linux PC, utilities such as "sudo" and "su" has this feature because these command need to change user to root or other user ID. These utilities first executed as root user and then changes to other user ID if needed.</p>
-<p>In Linux file system, all files are labeled with security context which describes owner user ID and group ID of the file and the permission of each accessible entity which are owner, group, and others. Permissions are consisting of read, write, and execute for each entity. If accessing process's user ID is same to owner of the file to be accessed, then the owner's permission is applied, if the process has the group that is labeled on the file, then the group's permission is applied, if not, then the other's permission is applied. All these functions are implemented in Linux kernel, so you don't need anything more for the feature. By the way, root process bypasses all the permission checking, that is root process can access all files. You can refer to Linux fundamental documents for this feature.</p>
-<p>The owner of a file can change permission of the file but, cannot change owner of the file. Only root process can change owner of the file, so if you want to change owner of a file, you have to be root.</p>
-<h3>Mandatory Access Control</h3>
-<p>DAC is great security feature of Linux, but sometime DAC is not sufficient to protect platform. DAC is based on user ID, group and file’s permissions, the granularity is limited to user ID level, in some way platform may need more precise access control than DAC. Mandatory Access Control (MAC) provides this security feature to give better and precise access control based on labeling and policy.</p>
-<p>MAC was not a part of standard Linux in the beginning, but since there were several requirements, so from kernel 2.6 version, some of the MAC mechanisms have been added to main line kernel source as optional features.</p>
-<p>MAC needs security context labeling and policy to control. Usually, all files have its security context described in extended attribute(xattr) of file system or some other places if xattr is not supported. Policy describes which subject (process) has permission to do something (operation) to some object. It doesn’t refer to owner and permission of the DAC field, just refer to security context of subject and object, and then searches allowed operations. Object can be files, directories, system calls, sockets and so on, each MAC mechanism has different set of objects.</p>
-<p>Using MAC, even root process can be denied to access some important object and some chosen root process can be allowed. Currently there are many MAC mechanisms such as SELinux, App-Armor, SMACK, RBAC, grsecurity and so on, and each of them has different objectives and approach.</p>
-<h2>Security Model</h2>
-<p>Since SLP is a Linux platform, its security model is similar to other Linux platform’s security model. In SLP, DAC and MAC are used, but biggest difference is that we need user space access control such as telephony, system management and so on.</p>
-<h3>Discretionary Access Control</h3>
-<p>- <b><i>User ID policy for processes</i></b></p>
-<p>All middleware daemons are running as root user ID, it's natural because daemons are executed by init process which is root process. There are a few exceptions that are not running as root even though the process is executed by init process. They are menu-screen, voice-call-daemon, and indicator. The reason is that the exceptional processes are executed by init process but they are not middleware, but applications. These special processes maybe increased at any time.</p>
-<p>Normal applications are executed as non root user ID. To achieve application sandboxing, all applications should run as all different user IDs, but it might occur complexity to the platform, so all the inhouse applications are executed as same user, and each 3rd party application will be executed as each different user ID.</p>
-<p><b><i>- Group ID for fine grained access control</i></b></p>
-<p>In Linux, a single process can be owned by a single user ID, but it can be belonged to multiple group IDs (max 65,536). In current desktop Linux such as Ubuntu, they use group ID to enforce access control for shared objects, such as CD-ROM, printer, audio, and so on. In SLP, we will use group ID as same usage, but the object will be different than normal desktop Linux, such as telephony, contact, and so on.</p>
-<p>As a result, each application will be given different group IDs based on its required privilege.</p>
-<p><i><b>- Security context on files</b></i></p>
-<p>For security and safety reason, basically all files in SLP owned by root as other Linux platform does, and then, non root user process cannot modify any files. The permission of normal files will be "rw-r--r--" which means only owner can modify or delete and the group member and others only can read, this is also same as other Linux platform. Lastly permission of executive files will be "rwxr-xr-x", so anybody can execute them, and also same as others.</p>
-<p>But there are many special files to be shared and modified by non root processes for example database files and device files in dev file system. In these cases, group ID of file is used. A shared file is owned by root but belonged to proper group ID which describes the file's content or object. The permission of the file could be "rw-rw-r--" to allow the processes belonged to the group can modify the file.</p>
-<p>There are some secret files to be protected by unauthorized read operation, then we can use same method as above but only difference will be no read permission to others, such as "rw-------", or "rw-rw----".</p>
-<p>Finally, there will be newly created files from middleware daemons and applications. There is default umask "022" , so if the created file is from middleware daemon, then the context of the file will be "root:root rw-r--r--", which means only root can modify and other users can read the file, if an application creates a file, then context wiil be "app_user:app_user rw-r--r--", so only the application can modify the file. This is normal usage but there must be some special cases which the file should be shared within applications. But, chown command and function only works under root privilege so applications cannot change owner of created files, so only thing possible is to change permission by chmod function. But there is only one option, share to none or share to all.</p>
-<h3>Mandatory Access Control</h3>
-<p>Mandatory access control(MAC) is currently out of scope of the SLP because there is almost no concrete threat which could be protected by MAC. Only one possible threat is that the network access by unauthorized process when there is a connected interface is already created. The adversary can monitor network interface status and if there is a new interface created, then it can use socket directly and it's possible to send some data by the socket. It's not possible to protect only by DAC.</p>
-<h2>User Space</h2>
-<p>There are many objects in user space such as making a phone call, sending a SMS message, which are not recognizable by kernel because thses objects are implemented in a daemon process, applications will request access by IPC and the kernel cannot manage inside of IPC messages. In these cases we must have a user space trusted entity which judges and controls access to such objects, which sits between applications and middleware daemons.</p>
-<p>To enable this, the entity must get identity of the subject application and object to be accessed, but it's not easy because some of the IPC mechanisms don't support peer's identity acquisition. For example all the dbus messages are routed by dbus daemon, so the receiver only guarantees dbus daemon sent the message, not the original sender of the message. Therefore, we have to support such mechanism to guarantee the original sender's identity to the final receiver along with reliable and secure access decision mechanism.</p>
-<p>To enforce access control, there must be an access policy which should be stored securely and it must be reliable. In SLP we utilized group ID for this policy. All processes have their user ID and groups which are controlled by kernel, each user space object is described as a group ID and the subject process will have the group ID if the application process has corresponding group ID then the access to be allowed, if not, the access will be denied.</p>
-<p>One more function required is that the enforcing entity needs to know other processes groups information. proc file system can be used. In proc file system, there is a file named "status", which describes various information about a process including all groups that the process belong to.</p>
-<h1 class="pg">Implementation</h1>
-<h2>User ID and Group ID Administration for Processes</h2>
-<p>As described above, all the daemons will be run by root, this is natural because all the booting scripts are executed by init process which is a root process, so all the processes executed by booting scripts will be run as root automatically. But there are some exceptions. There are some processes which are executed by booting scripts but not actually daemons such as menu screen and indicator. These processes must drop their privilege to a normal user, so in the beginning of their code, they change their user ID and groups to a normal user.</p>
-<p>All other applications will be executed by AUL (application utility library). When a new application process is requested to be executed, AUL daemon (launchpad) which is a root process receives the request, fork() and execute requested application in the child process. During this process, after forking a process, the launchpad child process changes its user ID to a corresponding user ID, changes matching groups, changes home directory, and execute the application. This is similar to su command in Linux environment.</p>
-<p>When a new application is installed, package manager adds a new user which has same user name with package name but substituting dot '.' to underscore '_'. But this feature is currently out of scope of the SLP.</p>
-<p>The group ID will be described as manifest permission item which described in control file of the debian package. Manifest permission items and group IDs will not correspond 1 to 1, basically one permission item will mean a set of group IDs to enable the permission, the sets might consist of 1 group ID or many group IDs. When a new application is installed, these groups will be assigned to the user ID, this could be implemented by adduser command. But this feature is currently out of scope of the SLP.</p>
-<h2>Changing Owner, Group and Permissions for Files</h2>
-<p>Since SLP uses debian package for the internal build system, all files which are installed by debian are automatically owned by root and their permissions set to 0644 (rw-r--r--), which means only root can modify and other processes only can read. But in the platform there are various files which should be modified by applications also, so we need to modify the ownership and permission intentionally.</p>
-<p>The only way to do this is by using postinst script of each of the debian package. On each package if there are some files should be shared, the package developer should add a few line to postinst file to change owner ship and permission to the files. To change owner, of a file, you have to be a root, if you are using fakeroot, the chown will not be affected.</p>
-*/
-/**
-*@}
-*/
diff --git a/src/security-srv/include/SLP_security-server_PG.h b/src/security-srv/include/SLP_security-server_PG.h
deleted file mode 100644 (file)
index c1016ab..0000000
+++ /dev/null
@@ -1,350 +0,0 @@
-/**
- *
- * @ingroup   SLP_PG
- * @defgroup  Security_Server_PG Security Server
-@{
-
-<h1 class="pg">Introduction</h1>
-<p>In Linux system, access control is enforced in the kernel space objects such as file, socket, directory, and device which are all described as files. In SLP, many objects are defined in user space which cannot be described as file, for example, make a phone call, send a SMS message, connect to the Internet, and modify SIM password. Some of the objects in user space are very sensitive to the platform and the phone business as well as user's property. Therefore the user space objects needed to be protected.</p>
-<p>To protect such user space objects, there must be a kind of credential to decide access result, and the credential must be trusted. Since process has privileges and the objects only has label, so some trusted entity should check the process has right privilege to access objects, and the security hooks to check this privilege should be located in the each middleware service daemons which provide the objects to the applications.</p>
-<p>Security Server uses group IDs of Linux system that are assigned to each process. In detail, if a process requests to get some user-space service to a middleware daemon, the middleware daemon requests to check privilege of some process, then the security server checks given gid is assigned to the process or not. If yes, then return yes, if no, then return no.</p>
-<p>If an application and middleware daemon uses Linux standard IPC such as Unix domain socket, there is no need to introduce 3rd party process to check gid that the process has. But some of service uses non Linux standard IPC such as telephony - using dbus - which the peer's credential is not propagated to the other peer. As a result to meet all the system's environment, we introduce Security Server.</p>
-<p>
-Security Server uses a random token named "cookie" to identify a process, the cookie needed not to be abled to guess easily, so it's quite long (currently 20 bytes), and only kept by Security Server process memory</p>
-
-<h1 class="pg">Security Server Architecture</h1>
-@image html SLP_Security-Server_PG_image001.png
-<p>Above fiture explains software architecture of Security Server. It is client-server structure, and communicates by IPC. The IPC must be point-2-point mechanism such as UNIX domain socket, not server related IPC such as dbus, because it's not easy to guarantee the other peer's security.</p>
-<p>Application or middleware process can call Security Server API to assign a new cookie or checking privilege of the given cookie. In this case, client library authenticates IPC peer and check the peer is Security Server process. In the same sense, Security Server authenticates client also.</p>
-<p>Application requests cookie to Security Server before requesting the service to the middleware daemon. Security Server authenticates the client, generates a random cookie, stores the cookie into local memory, and responds to the client with the cookie value. Client loads the cookie in the request message and sends to the middleware server, then the receiver middleware daemon check the privilege of the given cookie by calling Security Server API. Security Server compares received cookie value with stored cookie, checks and responds to the middleware daemon. Finally middleware daemon knows the client's privilege and it decides continue or block the request.</p>
-
-<h2>Sub components</h2>
-
-<h3>Client library</h3>
-@image html SLP_Security-Server_PG_image002.png
-<p>Client library is linked to application or middleware daemon. Therefore it belongs to the caller process, so uid, pid, and groups are also same. If the application calls cookie request API, the client compose cookie request message and sends to the Security Server and wait for the response. After receiving the response, first checks the response is from Security Server, and if it's true, it stores cookie into cookie container.</p>
-<p>Middleware daemon also links same client library, but by the difference of the calling APIs, the functions are different. Middleware daemon first receives cookie value loaded in service request from the client, and then the middleware calls Security Server API to check the cookie has the privilege to the service and waits for the response. After receiving the response, it authenticates the response is really from Security Server, and continue service by the result of the API.</p>
-
-<h3>Security Server Daemon</h3>
-@image html SLP_Security-Server_PG_image003.png
-<p>Security Server daemon is a Unix domain socket server, but it only has single thread and single process to get rid of race condition for the proc file system and cookie list to be shared. It’s easy to manage, more secure and the Security Server itself doesn't need to maintain a session for a long time.</p>
-<p>When request API is received from the client, Security Server first parses, and authenticates the message, and creates cookie or checks privilege. Cookie is a 20 bytes random string too hard to be guessed. So it's hard to be spoofed.</p>
-<p>Cookie generator generates a cookie based on proc file system information of the client process with group IDs the client belongs to, and privilege checker searches received cookie value with stored cookie list and checks the privilege.</p>
-<p>Cookie list is a linked list implemented in memory and it stores and manages generated cookie.</p>
-
-<h1 class="pg">Dependency</h1>
-<p>The Security Server has high dependency on Linux kernel, precisely the proc file system. Since Security Server refers to proc file system with processes group ID, so the kernel must support group ID representation on the proc file system.</p>
-<p>In kernel version 2.6, there is a file in proc file system "/proc/[pid]/status" which describes various information about the process as text, it has a line named "Groups:" and it lists the group IDs that the process is belonged to. But there is a drawback in this file, it only shows at most 32 group IDs, if number of groups of the process is bigger than 32, it ignores them.</p>
-<p>To enable to show all the groups you have to patch the kernel source code to show more groups than 32, but there is another drawback. All files in the proc file system has size limit to 4k bytes because the file buffer size is 4k bytes, so it's not possible to show all possible groups of the process (64k), but currently number of all groups in the LiMo platform is much lower than the size, so it's not a big problem. But near future we need to apply this patch into kernel mainline source code by any form.</p>
-
-<h1 class="pg">Scenarios</h1>
-@image html SLP_Security-Server_PG_image004.png
-<p>Security Server process view is described in figure above. It's explained in above, so it's not necessary to explain again. But one possible question may arise, that why do we need Security Server, that the service daemon can authenticates application process by the IPC, and the daemon can check proc file system by itself, so it seems that we may not need to have Security Server at all<p>
-@image html SLP_Security-Server_PG_image005.png
-<p>But there is exceptional process view described in figure above. If the middleware's IPC mechanism is dbus, then the daemon cannot guarantee the identity of the requesting application. In this case, there is no possible way to check and authenticate application from the middleware daemon directly. We need a trusted 3rd party to guarantee such identity and privilege, therefore Security Server is required.</p>
-<p>As described above, the cookie value is the key of the security of Security Server. The cookie value must not to be exposed into the platform, the cookie value must be stored securely that only Security Server and the application process knows the value. Even the middleware daemon should not cache the cookie for the security reason</p>
-
-<h1 class="pg">APIs</h1>
-
-<h3 class="pg">security_server_get_gid</h3>
-<table>
-       <tr>
-               <td>
-                       API Name:
-               </td>
-               <td>
-                       gid_t security_server_get_gid(const char *object)
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Input Parameter:
-               </td>
-               <td>
-                       object name as Null terminated string
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Output Parameter:
-               </td>
-               <td>
-                       N/A
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Return value:
-               </td>
-               <td>
-                       On success, returns the integer gid of requested object.<br>
-                       On fail, returns negative integer
-               </td>
-       </tr>
-</table>
-This API returns the gid from given object name. This API is only allowed to be called from middleware service daemon which is running under root privilege
-
-<h3 class="pg">security_server_get_object_name</h3>
-<table>
-       <tr>
-               <td>
-                       API Name:
-               </td>
-               <td>
-                       int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Input Parameter:
-               </td>
-               <td>
-                       gid, max_object_size
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Output Parameter:
-               </td>
-               <td>
-                       object as null terminated string
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Return value:
-               </td>
-               <td>
-                       On success, returns 0<br>
-                       On fail, returns negative integer
-               </td>
-       </tr>
-</table>
-This API is opposite with security_server_get_gid(). It converts given gid to object name which buffer size is max_object_size. If object name is bigger then max_object_size then it returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
-
-<h3 class="pg">security_server_request_cookie</h3>
-<table>
-       <tr>
-               <td>
-                       API Name:
-               </td>
-               <td>
-                       gid_t security_server_request_cookie(char *cookie, size_t max_cookie)
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Input Parameter:
-               </td>
-               <td>
-                       max_cookie
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Output Parameter:
-               </td>
-               <td>
-                       cookie
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Return value:
-               </td>
-               <td>
-                       On success, returns 0<br>
-                       On fail, returns negative integer
-               </td>
-       </tr>
-</table>
-This API requests a cookie to Security Server. max_cookie is the size of buffer cookie to be filled with cookie value, if max_cookie smaller then cookie size, then this API returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
-
-<h3 class="pg">security_server_get_cookie_size</h3>
-<table>
-       <tr>
-               <td>
-                       API Name:
-               </td>
-               <td>
-                       int security_server_get_cookie_size(void)
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Input Parameter:
-               </td>
-               <td>
-                       N/A
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Output Parameter:
-               </td>
-               <td>
-                       N/A
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Return value:
-               </td>
-               <td>
-                       size of cookie value
-               </td>
-       </tr>
-</table>
-This API simply returns the size of cookie.
-
-<h3 class="pg">security_server_check_privilege</h3>
-<table>
-       <tr>
-               <td>
-                       API Name:
-               </td>
-               <td>
-                       int security_server_check_privilege(const char *cookie, gid_t privilege)
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Input Parameter:
-               </td>
-               <td>
-                       cookie, privilege
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Output Parameter:
-               </td>
-               <td>
-                       N/A
-               </td>
-       </tr>
-       <tr>
-               <td>
-                       Return value:
-               </td>
-               <td>
-                       On success, returns 0<br>
-                       On fail, returns negative integer
-               </td>
-       </tr>
-</table>
-This API checks the cookie value has privilege for given gid. This API should be called by middleware server only after application embed cookie into the request message and sent to the middleware server. The middleware server should aware with the privilege parameter because it knows the object which the client application tries to access.
-
-
-<h1 class="pg">Implementation Guide</h1>
-
-<h2>Middleware server side</h2>
-<p>
-In middleware, implementation is focused on checking privilege of the requested client application. To call security_server_check_privilege() API, you have to get the gid value first, and this can be achieved by calling security_server_get_gid() API. The pre-condition of this scenario is that the middleware server knows the name of the object. Once you get the gid values, you can cache them for better performance. </p>
-<p>
-Once a client application requests to access the middleware’s object, the client should embed cookie into the request message. If not, the security is not guaranteed. After getting request and embedded cookie, the middleware server call security_server_check_privilege() API to check the client is allowed to access the object, the security server will respond the result. Finally the server need to decide continue the service or not.</p>
-
-@code
-static gid_t g_gid;
-
-int get_gid()
-{
-       int ret;
-       // Get gid of telephony call - example object
-       ret = security_server_get_gid("telephony_call");
-       if(ret < 0)
-       {
-               return -1;
-       }
-       g_gid = ret;
-       return 0;
-}
-
-int main(int argc, char * argv[])
-{
-       char *cookie = NULL;
-       int ret, cookie_size;
-
-
-       ...
-
-
-               // Initially get gid about the object which is interested in
-               if(get_gid() < 0)
-                       exit(-1);
-
-       // get cookie size and malloc it if you want
-       cookie_size = security_server_get_cookie_size();
-       cookie = malloc(cookie_size);
-
-       ...
-
-       // If a request has been received
-       // First parse the request and get the cookie value
-       // Let's assume that the buffer cookie is filled with received cookie value
-       ret = security_server_check_privilege(cookie, cookie_size);
-       if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-       {
-               // Access denied
-               // Send error message to client application
-       }
-       else if( ret != SECURITY_SERVER_SUCCESS)
-       {
-               // Error occurred
-               // Check error condition 
-       }
-       else
-       {
-               // Access granted
-               // Continue service
-               ...
-       }
-
-
-       ...
-
-
-       free(cookie);
-       ...
-}
-@endcode
-
-<h2>Client application side</h2>
-<p>
-In client application, what you need is just request a cookie and embed it into request message</p>
-
-@code
-int some_platform_api()
-{
-       char *cookie = NULL;
-       int cookie_size, ret;
-
-       ...
-
-
-       // malloc the cookie
-       cookie_size = security_server_get_cookie_size();
-       cookie = malloc(cookie_size);
-
-       ...
-
-
-               // Request cookie from the security server
-               ret = security_server_request_cookie(cookie, cookie_size);
-       if(ret < 0)
-       {
-               // Some error occurred
-               return -1;
-       }
-
-       // embed cookie into the message and send to the server
-
-       ...
-       free(cookie);
-}
-@endcode
-
-*/
-/**
-*@}
-*/
diff --git a/src/security-srv/include/security-server-comm.h b/src/security-srv/include/security-server-comm.h
deleted file mode 100644 (file)
index b132caf..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_COMM_H
-#define SECURITY_SERVER_COMM_H
-
-/* Message */
-typedef struct
-{
-       unsigned char version;
-       unsigned char msg_id;
-       unsigned short msg_len;
-} basic_header;
-
-typedef struct
-{
-       basic_header basic_hdr;
-       unsigned char return_code;
-} response_header;
-
-#define SECURITY_SERVER_MIDDLEWARE_USER "app"
-
-/* Message Types */
-#define SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST                0x01
-#define SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE       0x02
-#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST       0x03
-#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE      0x04
-#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST   0x05
-#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE  0x06
-#define SECURITY_SERVER_MSG_TYPE_GID_REQUEST           0x07
-#define SECURITY_SERVER_MSG_TYPE_GID_RESPONSE          0x08
-#define SECURITY_SERVER_MSG_TYPE_PID_REQUEST           0x09
-#define SECURITY_SERVER_MSG_TYPE_PID_RESPONSE          0x0a
-#define SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST          0x0b
-#define SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE         0x0c
-#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST     0x0d
-#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE    0x0e
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST       0x0f
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE      0x10
-#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST     0x11
-#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE    0x12
-#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST       0x13
-#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE      0x14
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST       0x15
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE      0x16
-#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST   0x17
-#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE  0x18
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST   0x19
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE  0x1a
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST    0x1b
-#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE   0x1c
-#define SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST         0x1d
-#define SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE        0x1e
-#define SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE      0xff
-
-/* Return code */
-#define SECURITY_SERVER_RETURN_CODE_SUCCESS            0x00
-#define SECURITY_SERVER_RETURN_CODE_BAD_REQUEST                0x01
-#define SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED      0x02
-#define SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED     0x03
-#define SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED      0x04
-#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT     0x05
-#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE     0x06
-#define SECURITY_SERVER_RETURN_CODE_NO_PASSWORD                0x07
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST             0x08
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH  0x09
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED     0x0a
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED   0x0b
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED    0x0c
-#define SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER       0x0d
-#define SECURITY_SERVER_RETURN_CODE_SERVER_ERROR       0x0e
-
-int return_code_to_error_code(int ret_code);
-int create_new_socket(int *sockfd);
-int safe_server_sock_close(int client_sockfd);
-int connect_to_server(int *fd);
-int accept_client(int server_sockfd);
-int authenticate_client_application(int sockfd, int *pid, int *uid);
-int authenticate_client_middleware(int sockfd, int *pid);
-int authenticate_developer_shell(int sockfd);
-char *read_cmdline_from_proc(pid_t pid);
-int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code);
-int send_cookie(int sockfd, unsigned char *cookie);
-int send_object_name(int sockfd, char *obj);
-int send_gid(int sockfd, int gid);
-int send_cookie_request(int sock_fd);
-int send_gid_request(int sock_fd, const char* object);
-int send_object_name_request(int sock_fd, int gid);
-int send_privilege_check_request(int sock_fd, const char*cookie, int gid);
-int send_privilege_check_new_request(int sock_fd,
-                                     const char *cookie,
-                                     const char *object,
-                                     const char *access_rights);
-int recv_get_gid_response(int sockfd, response_header *hdr, int *gid);
-int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size);
-int recv_cookie(int sockfd, response_header *hdr, char *cookie);
-int recv_privilege_check_response(int sockfd, response_header *hdr);
-int recv_privilege_check_new_response(int sockfd, response_header *hdr);
-int recv_hdr(int client_sockfd, basic_header *basic_hdr);
-int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege);
-int recv_check_privilege_new_request(int sockfd,
-                                     unsigned char *requested_cookie,
-                                     char *object_label,
-                                     char *access_rights);
-int send_pid_request(int sock_fd, const char*cookie);
-int recv_pid_response(int sockfd, response_header *hdr, int *pid);
-int recv_pid_request(int sockfd, unsigned char *requested_cookie);
-int send_pid(int sockfd, int pid);
-int send_smack_request(int sockfd, const char * cookie);
-int recv_smack_response(int sockfd, response_header *hdr, char * label);
-int recv_smack_request(int sockfd, unsigned char *requested_cookie);
-int send_smack(int sockfd, char * label);
-int send_launch_tool_request(int sock_fd, int argc, const char **argv);
-int recv_generic_response(int sockfd, response_header *hdr);
-int recv_launch_tool_request(int sockfd, int argc, char *argv[]);
-int recv_pwd_response(int sockfd, response_header *hdr, unsigned int *current_attempts,
-       unsigned int *max_attempts, unsigned int *valid_days);
-int send_set_pwd_request(int sock_fd, const char*cur_pwd, const char*new_pwd,
-       const unsigned int max_challenge, const unsigned int valid_period_in_days);
-int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days);
-int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge);
-int send_chk_pwd_request(int sock_fd, const char*challenge);
-int check_socket_poll(int sockfd, int event, int timeout);
-int free_argv(char **argv, int argc);
-
-#endif
diff --git a/src/security-srv/include/security-server-common.h b/src/security-srv/include/security-server-common.h
deleted file mode 100644 (file)
index 03893d2..0000000
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_COMMON_H
-#define SECURITY_SERVER_COMMON_H
-
-#include <sys/types.h>
-
-/* Definitions *********************************************************/
-/* Return value. Continuing from return value of the client header file */
-#define SECURITY_SERVER_SUCCESS                                0
-#define SECURITY_SERVER_ERROR_SOCKET                   -1
-#define SECURITY_SERVER_ERROR_BAD_REQUEST              -2
-#define SECURITY_SERVER_ERROR_BAD_RESPONSE             -3
-#define SECURITY_SERVER_ERROR_SEND_FAILED              -4
-#define SECURITY_SERVER_ERROR_RECV_FAILED              -5
-#define SECURITY_SERVER_ERROR_NO_SUCH_OBJECT           -6
-#define SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED    -7
-#define SECURITY_SERVER_ERROR_INPUT_PARAM              -8
-#define SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL         -9
-#define SECURITY_SERVER_ERROR_OUT_OF_MEMORY            -10
-#define SECURITY_SERVER_ERROR_ACCESS_DENIED            -11
-#define SECURITY_SERVER_ERROR_SERVER_ERROR             -12
-#define SECURITY_SERVER_ERROR_NO_SUCH_COOKIE           -13
-#define SECURITY_SERVER_ERROR_NO_PASSWORD              -14
-#define SECURITY_SERVER_ERROR_PASSWORD_EXIST           -15
-#define SECURITY_SERVER_ERROR_PASSWORD_MISMATCH                -16
-#define SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER     -17
-#define SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED   -18
-#define SECURITY_SERVER_ERROR_PASSWORD_EXPIRED -19
-#define SECURITY_SERVER_ERROR_PASSWORD_REUSED  -20
-#define SECURITY_SERVER_ERROR_SOCKET_BIND              -21
-#define SECURITY_SERVER_ERROR_FILE_OPERATION           -22
-#define SECURITY_SERVER_ERROR_TIMEOUT                  -23
-#define SECURITY_SERVER_ERROR_POLL                     -24
-#define SECURITY_SERVER_ERROR_UNKNOWN                  -255
-
-/* Miscellaneous Definitions */
-#define SECURITY_SERVER_SOCK_PATH                      "/tmp/.security_server.sock"
-#define SECURITY_SERVER_DEFAULT_COOKIE_PATH            "/tmp/.security_server.coo"
-#define SECURITY_SERVER_DAEMON_PATH                    "/usr/bin/security-server"
-#define SECURITY_SERVER_COOKIE_LEN                     20
-#define MAX_OBJECT_LABEL_LEN                            32
-#define MAX_MODE_STR_LEN                                16
-#define SECURITY_SERVER_MIDDLEWARE_LIST_PATH           "/usr/share/security-server/mw-list"
-#define SECURITY_SERVER_MAX_OBJ_NAME                   30
-#define SECURITY_SERVER_MAX_PATH_LEN                   50
-#define SECURITY_SERVER_MSG_VERSION                    0x01
-#define SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND      10000
-#define SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND      3000
-#define SECURITY_SERVER_DEVELOPER_UID                  5100
-#define SECURITY_SERVER_DEBUG_TOOL_PATH                        "/usr/bin/debug-util"
-#define SECURITY_SERVER_KILL_APP_PATH                  "/usr/bin/kill_app"
-#define SECURITY_SERVER_DATA_DIRECTORY_PATH            "/opt/data/security-server"
-#define SECURITY_SERVER_ATTEMPT_FILE_NAME      "attempts"
-#define SECURITY_SERVER_HISTORY_FILE_NAME      "history"
-#define SECURITY_SERVER_MAX_PASSWORD_LEN               32
-#define SECURITY_SERVER_HASHED_PWD_LEN                 32  /* SHA256 */
-#define SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND          1
-#define SECURITY_SERVER_MAX_PASSWORD_HISTORY   50
-#define SECURITY_SERVER_NUM_THREADS                    10
-
-/* API prefix */
-#ifndef SECURITY_SERVER_API
-#define SECURITY_SERVER_API    __attribute__((visibility("default")))
-#endif
-
-
-
-/* Data types *****************************************************************/
-/* Cookie List data type */
-typedef struct _cookie_list
-{
-       unsigned char   cookie[SECURITY_SERVER_COOKIE_LEN];     /* 20 bytes random Cookie */
-       int             path_len;                               /* Client process cmd line length */
-       int             permission_len;                         /* Client process permissions (aka group IDs) */
-       pid_t           pid;                                    /* Client process's PID */
-       char            *path;                                  /* Client process's cmd line string */
-       int             *permissions;                           /* Array of GID that the client process has */
-    char            *smack_label;                           /* SMACK label of the client process */
-    char    is_roots_process;           /* Is cookie belongs to roots process */
-       struct _cookie_list     *prev;                          /* Next cookie list */
-       struct _cookie_list     *next;                          /* Previous cookie list */
-} cookie_list;
-
-
-/* Function prototypes ******************************************************/
-/* IPC */
-
-void printhex(const unsigned char *data, int size);
-
-/* Debug */
-#ifdef SECURITY_SERVER_DEBUG_TO_CONSOLE /* debug msg will be printed in console */
-#define SEC_SVR_DBG(FMT, ARG ...) fprintf(stderr, "[%s:%d] "FMT"\n", \
-               __FILE__, __LINE__, ##ARG)
-
-#elif SECURITY_SERVER_DEBUG_DLOG       /* debug msg will be printed by dlog daemon */
-#define LOG_TAG "SECURITY_SERVER"
-#include <dlog.h>
-#define SEC_SVR_DBG    SLOGD
-#else /* No debug output */
-#define SEC_SVR_DBG(FMT, ARG ...) {}
-#endif
-
-#endif
diff --git a/src/security-srv/include/security-server-cookie.h b/src/security-srv/include/security-server-cookie.h
deleted file mode 100644 (file)
index 3acc720..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved\r
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_COOKIE_H\r
-#define SECURITY_SERVER_COOKIE_H\r
-\r
-#include "security-server-common.h"\r
-\r
-int free_cookie_item(cookie_list *cookie);
-cookie_list *delete_cookie_item(cookie_list *cookie);
-cookie_list *search_existing_cookie(int pid, const cookie_list *c_list);
-cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege);
-cookie_list *search_cookie_new(const cookie_list *c_list,
-                               const unsigned char *cookie,
-                               const char *object,
-                               const char *access_rights);
-int generate_random_cookie(unsigned char *cookie, int size);
-cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list);
-cookie_list *create_default_cookie(void);
-cookie_list * garbage_collection(cookie_list *cookie);
-cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid);
-void printhex(const unsigned char *data, int size);\r
-\r
-#endif\r
diff --git a/src/security-srv/include/security-server-password.h b/src/security-srv/include/security-server-password.h
deleted file mode 100644 (file)
index 924153f..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_PASSWORD_H
-#define SECURITY_SERVER_PASSWORD_H
-
-#include "security-server-common.h"
-#include "security-server-comm.h"
-
-int process_valid_pwd_request(int sockfd);
-int process_set_pwd_request(int sockfd);
-int process_reset_pwd_request(int sockfd);
-int process_reset_pwd_request(int sockfd);
-int process_chk_pwd_request(int sockfd);
-int process_set_pwd_max_challenge_request(int sockfd);
-int process_set_pwd_validity_request(int sockfd);
-void initiate_try(void);
-
-#endif
diff --git a/src/security-srv/include/security-server-util.h b/src/security-srv/include/security-server-util.h
deleted file mode 100644 (file)
index 32c9f72..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_UTIL_H
-#define SECURITY_SERVER_UTIL_H
-
-/* Only for test */
-/* These msg type MUST BE REMOVED before release **************************/
-#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST       0x51
-#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE      0x52
-#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST       0x53
-#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE       0x54
-#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST    0x55
-/**********************************************************************/
-
-int util_process_all_cookie(int sockfd, cookie_list* list);
-int util_process_cookie_from_pid(int sockfd, cookie_list* list);
-int util_process_cookie_from_cookie(int sockfd, cookie_list* list);
-
-
-#endif
diff --git a/src/security-srv/include/security-server.h b/src/security-srv/include/security-server.h
deleted file mode 100644 (file)
index b927c89..0000000
+++ /dev/null
@@ -1,1027 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#ifndef SECURITY_SERVER_H
-#define SECURITY_SERVER_H
-
-#include <sys/types.h>
-
-/**
- * @file    security-server.h
- * @version 1.0
- * @brief   This file contains APIs of the Security Server
-*/
-
-/**
- * @defgroup SecurityFW
- * @{
- *
- * @defgroup SECURITY_SERVER Security Server
- * @version  1.0
- * @brief    Security Server client library functions
- *
-*/
-
-/**
- * @addtogroup SECURITY_SERVER
- * @{
-*/
-
-/*
- * ====================================================================================================
- * <tt>
- *
- * Revision History:
- *
- *  -- Company Name -- | Modification Date | Description of Changes
- *  -----------------------------------------------------------------------
- *   --- Samsung ------ | --- 2010-07-25 -- | First created
- *
- *    </tt>
- */
-
-/**
- * \name Return Codes
- * exported by the foundation API.
- * result codes begin with the start error code and extend into negative direction.
- * @{
-*/
-#define SECURITY_SERVER_API_SUCCESS                    0
-/*! \brief   indicating the result of the one specific API is successful */
-#define SECURITY_SERVER_API_ERROR_SOCKET               -1
-
-/*! \brief   indicating the socket between client and Security Server has been failed  */
-#define SECURITY_SERVER_API_ERROR_BAD_REQUEST          -2
-
-/*! \brief   indicating the response from Security Server is malformed */
-#define SECURITY_SERVER_API_ERROR_BAD_RESPONSE         -3
-
-/*! \brief   indicating the transmitting request has been failed */
-#define SECURITY_SERVER_API_ERROR_SEND_FAILED          -4
-
-/*! \brief   indicating the receiving response has been failed */
-#define SECURITY_SERVER_API_ERROR_RECV_FAILED          -5
-
-/*! \brief   indicating requesting object is not exist */
-#define SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT       -6
-
-/*! \brief   indicating the authentication between client and server has been failed */
-#define SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED        -7
-
-/*! \brief   indicating the API's input parameter is malformed */
-#define SECURITY_SERVER_API_ERROR_INPUT_PARAM          -8
-
-/*! \brief   indicating the output buffer size which is passed as parameter is too small */
-#define SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL     -9
-
-/*! \brief   indicating system  is running out of memory state */
-#define SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY                -10
-
-/*! \brief   indicating the access has been denied by Security Server */
-#define SECURITY_SERVER_API_ERROR_ACCESS_DENIED                -11
-
-/*! \brief   indicating Security Server has been failed for some reason */
-#define SECURITY_SERVER_API_ERROR_SERVER_ERROR         -12
-
-/*! \brief   indicating given cookie is not exist in the database  */
-#define SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE       -13
-
-/*! \brief   indicating there is no phone password set  */
-#define SECURITY_SERVER_API_ERROR_NO_PASSWORD          -14
-
-/*! \brief   indicating password exists in system  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_EXIST               -15
-
-/*! \brief   indicating password mismatch  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH    -16
-
-/*! \brief   indicating password retry timeout is not occurred yet  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER -17
-
-/*! \brief   indicating password retry timeout is not occurred yet  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED       -18
-
-/*! \brief   indicating password retry timeout is not occurred yet  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED     -19
-
-/*! \brief   indicating password retry timeout is not occurred yet  */
-#define SECURITY_SERVER_API_ERROR_PASSWORD_REUSED      -20
-
-/*! \brief   indicating the error with unknown reason */
-#define SECURITY_SERVER_API_ERROR_UNKNOWN              -255
-/** @}*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-
-/**
- * \par Description:
- * Retreives Linux group ID from object name which is passed by parameter
- *
- * \par Purpose:
- * This API may be used before security_server_check_privilege() API by middleware daemon to get group ID of a specific object.
- *
- * \par Typical use case:
- * In middleware daemon, before checking privilege of a service the daemon need to know the GID of the service. This API support the functionality.
- *
- * \par Method of function operation:
- * Opens /etc/group file and searches the object name as group name. If there is matching result, returns GID as integer
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - This API is only allowed to be called by pre-defined middleware daemon
- *
- * \param[in] object Name of the object which is kwnown by the caller.
- *
- * \return matching gid (positive integer) on success, or negative error code on error.
- *
- * \par Prospective clients:
- * Inhouse middleware
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see /etc/group,
- * security_server_get_object_name(), security_server_check_privilege()
- *
- * \remarks None
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- *
- * // You have to make sure that  the input param '*object' is defined in the platform
- * retval = security_server_get_gid("telephony_makecall");
- * if(retval < 0)
- * {
- *     printf("%s", "Error has occurred\n");
- *     exit(0);
- * }
- * ...
- * \endcode
-*/
-int security_server_get_gid(const char *object);
-
-
-
-/**
- * \par Description:
- * Retreives object name as mull terminated string from Linux group ID which is passed by parameter
- *
- * \par Purpose:
- * This API may be used to get object name if the caller process only knows GID of the object.
- *
- * \par Typical use case:
- * In middleware daemon, by some reason, need to know object name from the Linux group ID, then call this API to retrieve object name as string
- *
- * \par Method of function operation:
- * Opens /etc/group file and searches matching gid. If there is matching result, returns name of the group as null terminated string
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - This API is only allowed to be called by pre-defined middleware daemon
- *
- * \param[in] gid Linux group ID which needed to be retrieved as object name.
- * \param[out] object Place holder for matching object name for gid.
- * \param[in] max_object_size Allocated byte size of parameter "object".
- *
- * \return 0 on success, or negative error code on error.
- *
- * \par Prospective clients:
- * Inhouse middleware.
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre output parameter object must be malloced before calling this API not to make memory curruption
- *
- * \post None
- *
- * \see /etc/group,
- * security_server_get_gid()
- *
- * \remarks None
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- * char objectname[20];
- *
- * // Call the API
- * retval = security_server_get_object_name(6005, objectname, sizeof(objectname));
- * if(retval < 0)
- * {
- *     printf("%s", "Error has occurred\n");
- *     exit(0);
- * }
- * ...
- * \endcode
-*/
-int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size);
-
-
-
-/**
- * \par Description:
- * Request cookie to the Security Server. Cookie is a random bit stream which is used as ticket for user space object.
- *
- * \par Purpose:
- * This API may be used by application and client middleware process to get access to middleware daemons.
- *
- * \par Typical use case:
- * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
- *
- * \par Method of function operation:
- * Caller process just send request message. Security Server checks proc file system to get list of gIDs the caller belongs, then create a random cookie and responds to caller.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * Cookie needs to be stored relatively secure.
- *
- * \param[out] cookie Place holder for cookie value.
- * \param[in] max_cookie Allocated byte size of parameter "cookie".
- *
- * \return 0 on success, or negative error code on error.
- *
- * \par Prospective clients:
- * Any process
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre output parameter cookie must be malloced before calling this API not to make memory curruption
- * Size of the cookie can be retrieved by security_server_get_cookie_size() API.
- *
- * \post None
- *
- * \see security_server_check_privilege(), security_server_get_cookie_size()
- *
- * \remarks None
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- * size_t cookie_size;
- * cookie_size = security_server_get_cookie_size();
- * unsigned char cookie[cookie_size];
- *
- * // Call the API
- * retval = security_server_request_cookie(cookie, cookie_size);
- * if(retval < 0)
- * {
- *     printf("%s", "Error has occurred\n");
- *     exit(0);
- * }
- * ...
- * \endcode
-*/
-int security_server_request_cookie(char *cookie, size_t max_cookie);
-
-
-
-/**
- * \par Description:
- * This API gets the cookie's byte size which is issued by Security Server.
- *
- * \par Purpose:
- * This API may be used by application and middleware process to get size of cookie before getting and storing cookie value.
- *
- * \par Typical use case:
- * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
- *
- * \par Method of function operation:
- * This API just returns pre-defined integer value as cookie size.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * None
- *
- * \return Always returns byte size of the cookie.
- *
- * \par Prospective clients:
- * Any process
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_request_cookie()
-
- * \remarks None
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- * size_t cookie_size;
- *
- * // API calling
- * cookie_size = security_server_get_cookie_size();
- * unsigned char cookie[cookie_size];
- *
- * char objectname[20];
- * retval = security_server_request_cookie(cookie, cookie_size);
- * if(retval < 0)
- * {
- *     printf("%s", "Error has occurred\n");
- *     exit(0);
- * }
- * ...
- * \endcode
-*/
-int security_server_get_cookie_size(void);
-
-
-
-/**
- * \par Description:
- * This API checks the cookie is allowed to access to given object.
- *
- * \par Purpose:
- * This API may be used by middleware process to ask the client application has privilege for the given object.
- *
- * \par Typical use case:
- * When middleware server receives request message from client application process with cookie value, it calls this API to ask to Security Server that the client application has privilege to access the service. If yes, then the middleware daemon can continue service, if not, it can return error to client application.
- *
- * \par Method of function operation:
- * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it checks the cookie has the privilege. It returns success if there is match, if not, it returns error.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * Cookie value needs to be stored relatively secure\n
- * Privilege should be pre-defined by Platform design.
- *
- * \param[in] cookie Received cookie value from client application
- * \param[in] privilege Object group ID which the client application wants to access
- *
- * \return 0 on success, or negative error code on error.
- *
- * \par Prospective clients:
- * Only pre-defiend middleware daemons
- *
- * \par Known issues/bugs:
- * None
- * \pre None
- *
- * \post None
- *
- * \see security_server_request_cookie(), security_server_get_gid(), security_server_get_cookie_size()
- *
- * \remarks None
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- * size_t cookie_size;
- * int call_gid;
- * cookie_size = security_server_get_cookie_size();
- * unsigned char recved_cookie[cookie_size];
- *
- * ... // Receiving request with cookie
- *
- * call_gid = security_server_get_gid("telephony_makecall");
- * retval = security_server_check_privilege(recved_cookie, (gid_t)call_gid);
- * if(retval < 0)
- * {
- *     if(retval == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
- *     {
- *             printf("%s", "access has been denied\n");
- *             return;
- *     }
- *     printf("%s", "Error has occurred\n");
- * }
- * ...
- *
- * \endcode
-*/
-int security_server_check_privilege(const char *cookie, gid_t privilege);
-
-int security_server_check_privilege_by_cookie(const char *cookie,
-                                              const char *object,
-                                              const char *access_rights);
-
-int security_server_check_privilege_by_sockfd(int sockfd,
-                                              const char *object,
-                                              const char *access_rights);
-
-/**
- * \par Description:
- * This API searchs a cookie value and returns PID of the given cookie.
- *
- * \par Purpose:
- * This API may be used by middleware process to ask the client application has privilege for the given object.
- *
- * \par Typical use case:
- * In some cases, a middleware server wants to know PID of the application process. But if the middleware server uses non-direct IPC such as dbus, it's nearly impossible to know and guarantee peer PID. By using this API, the middleware server can retrieve a PID of the requesting process.
- *
- * \par Method of function operation:
- * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it returns corresponding PID for the cookie.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * Cookie value needs to be stored relatively secure\n
- * This API is abled to be called only by pre-defined middleware servers.
- *
- * \param[in] cookie Received cookie value from client application. Cookie is not a null terminated human readable string. Make sure you're code doesn't have any string related process on the cookie.
- *
- * \return positive integer on success meaning the PID, 0 means the cookie is for root process, negative integer error code on error.
- *
- * \par Prospective clients:
- * Only pre-defiend middleware daemons
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_request_cookie(), security_server_get_cookie_size()
- *
- * \remarks the cookie is not a null terminated string. Cookie is a BINARY byte stream of such length which can be retrieved by security_server_get_cookie_size() API.
- * Therefore, please do not use strcpy() family to process cookie value. You MUST use memcpy() function to process cookie value.
- * You also have to know that the cookie value doesn't carry any null terminator. So you don't need to allocate 1 more byte of the cookie size.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int peerpid;
- * size_t cookie_size;
- * gid_t call_gid;
- * cookie_size = security_server_get_cookie_size();
- * unsigned char recved_cookie[cookie_size];
- *
- * ... // Receiving request with cookie
- *
- * peerpid = security_server_get_cookie_pid(recved_cookie);
- * if(peerpid < 0)
- * {
- *     printf("%s", "Error has occurred\n");
- * }
- * ...
- *
- * \endcode
-*/
-int security_server_get_cookie_pid(const char *cookie);
-
-
-
-/**
- * \par Description:
- * This API checks phone validity of password, to check existance, expiration, remaining attempts.
- *
- * \par Purpose:
- * This API should be used by applications which needs phone password check. Caller application should behave properly after this API call.
- *
- * \par Typical use case:
- * Lock screen can call this API before it shows unlock screen, if there is password, lock screen can show password input UI, if not, lock screen can show just unlock screen
- *
- * \par Method of function operation:
- * Sends a validate request to security server and security server replies with password information.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * Password file should be stored safely. The password file will be stored by security server and only allowed itself to read/write, and data is will be securely hashed\n
- *
- * \param[out] current_attempts Number of password check missed attempts.
- * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
- * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
- *
- * \return 0 if there is no password set, other negative integer error code on error.
- *
- * \par Prospective clients:
- * Applications which can unlock UI
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_set_pwd(), security_server_chk_pwd()
- *
- * \remarks If password file is currupted or accitentally deleted, this API may not synchronized with security-server, but security-server will check file status on next request.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int ret;
- * unsigned int attempt, max_attempt, expire_sec;
- *
- * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
- * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
- * {
- *     printf("%s", "There is no password exists\n");
- * }
- * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
- * {
- *     printf("%s", "Password is valid by now\n");
- * }
- * else
- * {
- *     printf("%s", "Something wrong\n");
- * }
- * ...
- *
- * \endcode
-*/
-int security_server_is_pwd_valid(unsigned int *current_attempts,
-                       unsigned int *max_attempts,
-                       unsigned int *valid_secs);
-
-
-
-/**
- * \par Description:
- * This API sets phone password only if current password matches.
- *
- * \par Purpose:
- * This API should be used by setting application when the user changes his/her phone password.
- *
- * \par Typical use case:
- * Setting application calls this API to change phone password. Caller needs current password to grant the change.
- *
- * \par Method of function operation:
- * Sends current password with new password to security-server, security-server checks current password and set new password to current only when current password is correct. Caller application can determine maximum number of attempts and expiration time in days
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
- *
- * \param[in] cur_pwd Null terminated current password string. It can be NULL pointer if there is no password set yet - by calling security_server_is_pwd_empty()
- * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
- * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
- * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
- *
- * \return 0 on seccuess, negative integer error code on error.
- *
- * \par Prospective clients:
- * Platform's THE ONLY setting application and some dedicated privileged processes
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
- *
- * \remarks Only setting application can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
- * \remarks If current password exists and it's expired, or max attempts reached, you cannot call this API. You have to call security_server_reset_pwd() API.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int ret;
- * unsigned int attempt, max_attempt, expire_sec;
- *
- * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
- * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
- * {
- *     printf("%s", "There is no password exists\n");
- *     ret = security_server_set_pwd(NULL, "this_is_new_pwd", 20, 365);
- *     if(ret != SECURITY_SERVER_API_SUCCESS)
- *     {
- *             printf("%s", "we have error\n");
- *             ...
- *     }
- * }
- * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
- * {
- *     printf("%s", "Password is valid by now\n");
- *     ret = security_server_set_pwd("this_is_current_pwd", "this_is_new_pwd", 20, 365);
- *     if(ret != SECURITY_SERVER_API_SUCCESS)
- *     {
- *             printf("%s", "we have error\n");
- *             ...
- *     }
- * }
- * else
- * {
- *     printf("%s", "Something wrong\n");
- * }
- * ...
- *
- * \endcode
-*/
-int security_server_set_pwd(const char *cur_pwd,
-                       const char *new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days);
-
-
-/**
- * \par Description:
- * This API sets validity period for currently setup password.
- *
- * \par Purpose:
- * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
- *
- * \par Typical use case:
- * Authorized application calls this API to change current passwords validity when password policy needs to be changed.
- *
- * \par Method of function operation:
- * Function attempts to find currently set password and changes its current validity to passed number of days. Retry counter for the password is reset to zero.
- * If there is no password set, function returns proper error code.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
- *
- * \return 0 on success, negative integer error code on error.
- *
- * \par Prospective clients:
- * Platform's THE ONLY setting application and some dedicated privileged processes
- *
- * \par Known issues/bugs:
- * Identifying calling peer is not ready yet, should be based on SMACK somehow.
- *
- * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
- */
-int security_server_set_pwd_validity(const unsigned int valid_period_in_days);
-
-
-/**
- * \par Description:
- * This API sets maximum number of attempts for currently setup password.
- *
- * \par Purpose:
- * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
- *
- * \par Typical use case:
- * Authorized application calls this API to change current passwords max attempt number when password policy needs to be changed.
- *
- * \par Method of function operation:
- * Function attempts to find currently set password and changes its max attempt number to passed one. Retry counter for the password is reset to zero.
- * If there is no password set, function returns proper error code.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
- *
- * \return 0 on success, negative integer error code on error.
- *
- * \par Prospective clients:
- * Platform's THE ONLY setting application and some dedicated privileged processes
- *
- * \par Known issues/bugs:
- * Identifying calling peer is not ready yet, should be based on SMACK somehow.
- *
- * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
- */
-int security_server_set_pwd_max_challenge(const unsigned int max_challenge);
-
-/**
- * \par Description:
- * This API sets phone password only if current password is invalid or user forgot the password.
- *
- * \par Purpose:
- * This API should be used by setting application or dedicated processes when the user changes his/her phone password.
- *
- * \par Typical use case:
- * User forgots the password. He calls emergency manager(auto or manual)  for reset password. Emergency manager calls this API and reset phone password.
- *
- * \par Method of function operation:
- * Resetting phone password with input string without any matching current password.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
- *
- * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
- * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
- * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
- *
- * \return 0 on seccuess, negative integer error code on error.
- *
- * \par Prospective clients:
- * Platform's THE ONLY setting application and some dedicated privileged processes
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_set_pwd()
- *
- * \remarks Only dedicated applications can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int ret;
- * unsigned int attempt, max_attempt, expire_sec;
- *
- *     ret = security_server_set_pwd("this_is_new_pwd", 20, 365);
- *     if(retval != SECURITY_SERVER_API_SUCCESS)
- *     {
- *             printf("%s", "we have error\n");
- *             ...
- *     }
- * ...
- *
- * \endcode
-*/
-int security_server_reset_pwd(const char *new_pwd,
-                       const unsigned int max_challenge,
-                       const unsigned int valid_period_in_days);
-
-/**
- * \par Description:
- * This API compares stored phone password with challenged input value.
- *
- * \par Purpose:
- * This API should be used by applications which has phone UI lock capability.
- *
- * \par Typical use case:
- * Lock screen calls this API after user typed phone password and pressed okay.
- *
- * \par Method of function operation:
- * Sends challenged password to security-server, security-server compares hashed current password and hashed challenged password.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
- *
- * \param[in] challenge Null terminated challenged password string. It must not a NULL pointer.
- * \param[out] current_attempts Number of password check missed attempts.
- * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
- * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
- *
- * \return 0 on seccuess, negative integer error code on error.
- *
- * \par Prospective clients:
- * Applications which has phone UI lock feature.
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_is_pwd_valid(), security_server_set_pwd()
- *
- * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- * unsigned int attempt, max_attempt, expire_sec;
- *
- * retval = security_server_chk_pwd("is_this_password", &attmpt, &max_attempt, &expire_sec);
- * if(retval == SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
- * {
- *     printf("%s", "Oh you typed wrong password\n");
- *     ...
- * }
- * else if(retval == SECURITY_SERVER_API_SUCCESS)
- * {
- *     printf("%s", "You remember your password.\n");
- *     ...
- * }
- * ...
- *
- * \endcode
-*/
-int security_server_chk_pwd(const char *challenge,
-                       unsigned int *current_attempt,
-                       unsigned int *max_attempt,
-                       unsigned int *valid_secs);
-
-
-/**
- * \par Description:
- * This API set the number of password history which should be maintained. Once this number set, user cannot reuse recent number of passwords which is described in this history value
- *
- * \par Purpose:
- * This API should be used only by dedicated process in the platform.
- *
- * \par Typical use case:
- * Enterprise manager calls this API when the enterprise wants to enforce harder password policy.
- *
- * \par Method of function operation:
- * When enterprise manager (MDM) is trying to change the security policy for phone password, it calls this API background to change the history policy.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
- *
- * \param[in] number_of_history Number of history to be checked when user tries to change password. Maximum is currently 50
- *
- * \return 0 on seccuess, negative integer error code on error.
- *
- * \par Prospective clients:
- * MDM client, Enterprise manager.
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see security_server_set_pwd()
- *
- * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * ...
- * int retval;
- *
- * ret = security_server_set_pwd_history(100);
- *     if(ret != SECURITY_SERVER_API_SUCCESS)
- *     {
- *             printf("%s", "You have error\n");
- *             ...
- *     }
- * ...
- *
- * \endcode
-*/
-int security_server_set_pwd_history(int number_of_history);
-
-
-
-/**
- * \par Description:
- * This API launches /usr/bin/debug-util as root privilege.
- *
- * \par Purpose:
- * This API will be used only by SDK with developer privilege to launch debugging tool to debug as the developing applicaion's privilege.
- *
- * \par Typical use case:
- * During appliation development, SDK opens a shell to install, launch, and debug the developing application. But the shell will not have any privilege to control platform. Therefore we need a special utility to manage debugging environement as same privilege level of the application. If this API is called, security server will launch the debug utility as root privilege and the utility will drop its privilege same as developing application
- *
- *
- * \par Method of function operation:
- * When Security Server receives this request, it checks uid of the client, and launches /usr/bin/debug-util with given arguements.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * Caller process of this API must be owned by developer user.\n
- * The caller process will be pre-defined.
- * /usr/bin/debug-util itself must be omitted in the argv. Security server will put this as first argv in the execution procedure
- *
- * \param[in] argc Number of arguements.
- *
- * \param[in] argv Arguements
- *
- * \return 0 on success, negative integer error code on error.
- *
- * \par Prospective clients:
- * Only pre-defiend debugging utility.
- *
- * \par Known issues/bugs:
- * None
- *
- * \pre None
- *
- * \post None
- *
- * \see None
- *
- * \remarks Calling this API, you have to put argv[1] of the debug-util as argv[0] of this API. Security server will put argv[0] automatically
- *
- * \par Sample code:
- * \code
- * #include <security-server.h>
- * #define DEVELOPER_UID 5500
- *
- * int main(int argc, char **argv)
- * {
- *     int my_uid, ret;
- *     uid = getuid();
- *     if(uid != DEVELOPER_UID)
- *     {
- *             // You must be developer user
- *             exit(1);
- *     }
- *
- *     ret = security_server_launch_debug_tool(argc -1, argv++)
- *     if(ret != SECURITY_SERVER_SUCCESS)
- *     {
- *             // Some error occurred
- *             exit(1);
- *     }
- *     ...
- * }
- *
- * \endcode
-*/
-int security_server_launch_debug_tool(int argc, const char **argv);
-
-/*
- * This function allows to get process SMACK label by passing cookie assigned
- * to process. Function returns pointer to allocated buffer with label.
- * User has to free the buffer after using.
- *
- * \param[in] Pointer to cookie
- *
- * \return Pointer to SMACK label or NULL
- *
- * \par For free label use free(), label allocated by calloc()
- *      User responsibility is to free resource.
- */
-char * security_server_get_smacklabel_cookie(const char *cookie);
-
-/*
- * This function allows to get process SMACK label by passing socket descriptor.
- * Function returns pointer to allocated buffer with label.
- * User has to free the buffer after using.
- *
- * \param[in] Socket descriptor
- *
- * \return Pointer to SMACK label or NULL
- *
- * \par For free label use free(), label allocated by calloc().
- *      User responsibility is to free resource.
- */
-char * security_server_get_smacklabel_sockfd(int fd);
-
-#ifdef __cplusplus
-}
-#endif
-
-/**
- * @}
-*/
-
-/**
- * @}
-*/
-
-#endif
diff --git a/src/security-srv/mw-list b/src/security-srv/mw-list
deleted file mode 100644 (file)
index 14a8890..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-/usr/bin/telephony-server
-/usr/bin/ss-server
-/usr/bin/msg-server
-/usr/bin/alarm-server
-/usr/bin/lbs_server
-/usr/bin/power_manager
-/usr/bin/system_server
-/usr/bin/sec-svr-util
-/usr/bin/mdm-server
-/usr/bin/smartcard-daemon
-/usr/bin/sound_server
-/usr/bin/nfc-manager-daemon
diff --git a/src/security-srv/security-serverd b/src/security-srv/security-serverd
deleted file mode 100644 (file)
index 36344cc..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-# start secure-storage server
-/usr/bin/security-server &
-set_pmon -p security-server
diff --git a/src/security-srv/server/security-server-cookie.c b/src/security-srv/server/security-server-cookie.c
deleted file mode 100644 (file)
index a084a11..0000000
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
- *  security-server
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <unistd.h>
-#include <string.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <sys/smack.h>
-
-#include "security-server-cookie.h"
-
-/* Delete useless cookie item *
- * then connect prev and next */
-int free_cookie_item(cookie_list *cookie)
-{
-       if(cookie->path != NULL)
-               free(cookie->path);
-       if(cookie->permissions != NULL)
-               free(cookie->permissions);
-        if(cookie->smack_label != NULL)
-                free(cookie->smack_label);
-       if(cookie->prev != NULL)
-               cookie->prev->next = cookie->next;
-       if(cookie->next != NULL)
-               cookie->next->prev = cookie->prev;
-       free(cookie);
-       cookie = NULL;
-       return 0;
-}
-
-/* Cut the link of the current cookie item and connect previous link and next line *
- * That is remove a cookie item *
- * Returns next cookie item  if exist, NULL for no more cookie item */
-cookie_list *delete_cookie_item(cookie_list *cookie)
-{
-       cookie_list *retval = NULL;
-       if(cookie == NULL)
-       {
-               SEC_SVR_DBG("%s", "Cannot delete null cookie");
-               return retval;
-       }
-
-       /* Reconnect cookie item */
-       if(cookie->next != NULL)
-       {
-               cookie->prev->next = cookie->next;
-               cookie->next->prev = cookie->prev;
-               retval = cookie->next;
-       }
-       else
-       {
-               cookie->prev->next = NULL;
-       }
-       
-       free_cookie_item(cookie);
-       return retval;
-}
-
-cookie_list * garbage_collection(cookie_list *cookie)
-{
-       char path[17];
-       cookie_list *retval = NULL;
-       struct stat statbuf;
-       int ret;
-
-       while(cookie != NULL)
-       {
-               /* Skip default cookie */
-               if(cookie->pid ==0)
-                       return cookie;
-
-               /* Try to find the PID directory from proc fs */
-               snprintf(path, sizeof(path), "/proc/%d", cookie->pid);
-               path[16] = 0;
-               ret = stat(path, &statbuf);
-               if(ret != 0)
-               {
-                       /* If it's not exist, delete the cookie */
-                       if(errno == ENOENT)
-                       {
-                               SEC_SVR_DBG("Garbage found. PID:%d, deleting...", cookie->pid);
-                               cookie = delete_cookie_item(cookie);
-                               continue;
-                       }
-                       else
-                       {
-                               /* Some error occurred */
-                               SEC_SVR_DBG("Error occurred on stat: errno = %d", errno);
-                               return cookie;
-                       }
-               }
-               else
-               {
-                       /* This is not a garbage. returning */
-                       return cookie;
-               }
-       }
-       return retval;
-}
-
-/* Search existing cookie from the cookie list for the client process *
- * At the same time, it collects garbage cookie which PID is no longer exist and delete them */
-cookie_list *search_existing_cookie(int pid, const cookie_list *c_list)
-{
-       cookie_list *current =(cookie_list *)c_list, *cookie = NULL;
-       char *cmdline = NULL, *debug_cmdline = NULL;
-
-       /* Search from the list */
-       while(current != NULL)
-       {
-               /* print_cookie(current);*/
-               current = garbage_collection(current);
-               if(current == NULL)
-                       break;
-
-               /* PID must be same */
-               if(current->pid == pid)
-               {
-                       /* Found cookie for the pid. Check the cookie is reused by dirrent executable */
-                       /* Check the path of the process */
-                       cmdline = (char*)read_cmdline_from_proc(pid);
-                       if(cmdline == NULL)
-                       {
-                               SEC_SVR_DBG("%s", "cannot read cmdline");
-                               return NULL;
-                       }
-                       /* Check the path is different */
-                       if(strncmp(cmdline, current->path, current->path_len) != 0 || strlen(cmdline) != current->path_len)
-                       {
-                               SEC_SVR_DBG("pid [%d] has been reused by %s. deleting the old cookie.", pid, cmdline);
-                               debug_cmdline = malloc(current->path_len + 1);
-                               if(debug_cmdline == NULL)
-                               {
-                                       SEC_SVR_DBG("%s", "out of memory error");
-                                       free(cmdline);
-                                       return NULL;
-                               }
-                               strncpy(debug_cmdline, current->path, current->path_len);
-                               debug_cmdline[current->path_len] = 0;
-                               SEC_SVR_DBG("[%s] --> [%s]", cmdline, debug_cmdline);
-                               if(debug_cmdline != NULL)
-                               {
-                                       free(debug_cmdline);
-                                       debug_cmdline = NULL;
-                               }
-                               /* Okay. delete current cookie */
-                               current = delete_cookie_item(current);
-                               if(cmdline != NULL)
-                               {
-                                       free(cmdline);
-                                       cmdline = NULL;
-                               }
-                               continue;
-                       }
-                       else
-                       {
-                               SEC_SVR_DBG("%s", "cookie found");
-                               cookie = current;
-                       }
-
-                       if(cmdline != NULL)
-                       {
-                               free(cmdline);
-                               cmdline = NULL;
-                       }
-               }
-               current = current->next;
-       }
-       return cookie;
-}
-
-/* Search existing cookie from the cookie list for matching pid *
- * Default cookie (meaning PID 0) is not allowed in here */
-cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid)
-{
-       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
-
-       /* Search from the list */
-       while(current != NULL)
-       {
-               /* print_cookie(current);*/
-               /* PID must be same */
-               current = garbage_collection(current);
-               if(current == NULL)
-                       break;
-
-               if(current->pid == pid)
-               {
-                       SEC_SVR_DBG("%s", "cookie has been found");
-                       retval = current;
-                       goto finish;
-               }
-               current = current->next;
-       }
-finish:
-       return retval;
-}
-
-/* Search existing cookie from the cookie list for matching cookie and privilege */
-/* If privilege is 0, just search cookie exists or not */
-cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege)
-{
-       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
-       int i;
-
-       /* Search from the list */
-       while(current != NULL)
-       {
-               /* print_cookie(current);*/
-               /* PID must be same */
-               current = garbage_collection(current);
-               if(current == NULL)
-                       break;
-
-        //searching for cookie
-               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
-               {
-                       SEC_SVR_DBG("%s", "cookie has been found");
-
-            //check if this cookie belongs to root process
-            if(current->is_roots_process == 1)
-            {
-                SEC_SVR_DBG("%s", "Root process cookie, special privileges");
-                //we can skip privilege checking
-                retval = current;
-                goto finish;
-            }
-
-                       for(i=0 ; i < current->permission_len ; i++)
-                       {
-                               if(privilege == current->permissions[i])
-                               {
-                                       SEC_SVR_DBG("Found privilege %d", privilege);
-                                       retval = current;
-                                       goto finish;
-                               }
-                       }
-               }
-               current = current->next;
-       }
-finish:
-       return retval;
-}
-
-
-cookie_list *search_cookie_new(const cookie_list *c_list,
-                               const unsigned char *cookie,
-                               const char *object,
-                               const char *access_rights)
-{
-       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
-        int ret;
-       int i;
-
-       /* Search from the list */
-       while(current != NULL)
-       {
-               /* print_cookie(current);*/
-               /* PID must be same */
-               current = garbage_collection(current);
-               if(current == NULL)
-                       break;
-
-               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
-               {
-                       SEC_SVR_DBG("%s", "cookie has been found");
-
-                                ret = smack_have_access(current->smack_label, object, access_rights);
-          SEC_SVR_DBG("smack_have_access, subject >%s< object >%s< access >%s< ===> %d",
-                    current->smack_label, object, access_rights, ret);
-                                if (ret == 1)
-                                {
-                                        retval = current;
-                                        goto finish;
-                                }
-               }
-               current = current->next;
-       }
-finish:
-       return retval;
-}
-
-
-/* Generage a random stream value of size to cookie *
- * by reading /dev/uranddom file */
-int generate_random_cookie(unsigned char *cookie, int size)
-{
-       int fd, ret;
-
-    if (cookie == NULL) {
-        SEC_SVR_DBG("%s", "Null pointer passed to function");
-        return SECURITY_SERVER_ERROR_UNKNOWN;
-    }
-       fd = open("/dev/urandom", O_RDONLY);
-       if(fd < 0)
-       {
-               SEC_SVR_DBG("%s", "Cannot open /dev/urandom");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       ret = read(fd, cookie, size);
-       if(ret < size)
-       {
-               SEC_SVR_DBG("Cannot read /dev/urandom: %d", ret);
-               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
-               goto error;
-       }
-       ret = SECURITY_SERVER_SUCCESS;
-error:
-       if(fd >= 0)
-               close(fd);
-       return ret;
-}
-
-/* Create a cookie item from PID */
-cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list)
-{
-       int ret, tempint;
-       cookie_list *added = NULL, *current = NULL;
-       char path[24], *cmdline = NULL;
-       char *buf = NULL, inputed, *tempptr = NULL;
-       char delim[] = ": ", *token = NULL;
-       int *permissions = NULL, perm_num = 1, cnt, i, *tempperm = NULL;
-        char *smack_label = NULL;
-       FILE *fp = NULL;
-
-       current = search_existing_cookie(pid, c_list);
-       if(current != NULL)
-       {
-               /* There is a cookie for this process already */
-               added = current;
-               SEC_SVR_DBG("%s", "Existing cookie found");
-               goto error;
-       }
-
-       /* Read command line of the PID from proc fs */
-       cmdline = (char *)read_cmdline_from_proc(pid);
-       if(cmdline == NULL)
-       {
-               SEC_SVR_DBG("Error on reading /proc/%d/cmdline", pid);
-               goto error;
-       }
-
-       /*
-        * modified by security part
-        *  - get gid from /etc/group
-        */
-       /* Read group info of the PID from proc fs - /proc/[PID]/status */
-       snprintf(path, sizeof(path), "/proc/%d/status", pid);
-       fp = fopen(path, "r");
-
-       /* Find the line which starts with 'Groups:' */
-       i = 0;
-       
-       while(1)
-       {
-               buf = (char*)malloc(sizeof(char) * 128);
-               if(buf == NULL)
-               {
-                       SEC_SVR_DBG("%s", "Error on malloc()");
-                       goto error;
-               }
-               memset(buf, 0x00, 128);
-               cnt = 128;
-
-               /* get one line from /proc/[PID]/status */
-               while(1)
-               {
-                       tempint = fgetc(fp);
-                       inputed = (char)tempint;
-                       if(tempint == EOF)
-                               goto out_of_while;
-                       else if(inputed == '\n')
-                       {
-                               buf[i] = '\0';
-                               break;
-                       }
-                       else if((i == cnt) && (inputed != '\n'))
-                       {
-                               tempptr = (char*)realloc(buf, sizeof(char) * (i + 128));
-                               if(tempptr == NULL)
-                               {
-                                       SEC_SVR_DBG("%s", "Error on realloc()");
-                                       goto error;
-                               }
-                               buf = tempptr;
-                               buf[i++] = inputed;
-                               cnt = i + 128;
-                       }
-                       else
-                               buf[i++] = inputed;
-               }
-               i = 0;
-
-               /* find 'Groups:' */
-               if(strncmp(buf, "Groups:", 7) == 0)
-               {
-                       /* get gid from the line and insert to 'permissions' array */
-                       token = strtok(buf, delim); // first string is "Groups"
-                       while((token = strtok(NULL, delim)))
-                       {
-                               tempperm = realloc(permissions, sizeof(int) * perm_num);
-                               if(tempperm == NULL)
-                               {
-                                       SEC_SVR_DBG("%s", "Error on realloc()");
-                                       goto error;
-                               }
-                               permissions = tempperm;
-                               errno = 0;
-                               permissions[perm_num - 1] = strtoul(token, 0, 10);
-                               if (errno != 0)
-                               {
-                                       SEC_SVR_DBG("cannot change string to integer [%s]", token);
-                                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                                       goto error;
-                               }
-                               perm_num++;
-                       }
-                       perm_num--;
-
-                       /* goto out of while loop */
-                       break;
-               }
-               if(buf != NULL)
-               {
-                       free(buf);
-                       buf = NULL;
-               }
-       }
-out_of_while:
-               
-       /* Each group ID is stored in each line of the file */
-//     while(fgets(permline, sizeof(permline), fp) != NULL)
-//     {
-//             permissions = realloc(permissions, sizeof(int) * perm_num);
-//             if(permissions == NULL)
-//             {
-//                     SEC_SVR_DBG("%s", "Error on realloc()");
-//                     goto error;
-//             }
-//             permissions[perm_num -1] = strtoul(permline, 0, 10);
-//             perm_num++;
-//     }
-//     perm_num--;
-       /*
-        * modifying end
-        */
-
-       /* Go to last cookie from the list */
-       current = c_list;
-       while(current->next != NULL)
-       {
-               current = current->next;
-       }
-
-       /* Create a new one and assign values */
-       added = malloc(sizeof(cookie_list));
-       if(added == NULL)
-               goto error;
-
-       ret = generate_random_cookie(added->cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(ret != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Error on making random cookie: %d", ret);
-               free(added);
-               added = NULL;
-               goto error;
-       }
-
-        /* Check SMACK label */
-        ret = smack_new_label_from_socket(sockfd, &smack_label);
-        if (ret != 0)
-       {
-               SEC_SVR_DBG("Error checking peer label: %d", ret);
-               free(added);
-               added = NULL;
-               goto error;
-       }
-
-       added->path_len = strlen(cmdline);
-       added->path = calloc(1, strlen(cmdline));
-       memcpy(added->path, cmdline, strlen(cmdline));
-
-       added->permission_len = perm_num;
-       added->pid = pid;
-       added->permissions = permissions;
-       added->smack_label = smack_label;
-       added->prev = current;
-       current->next = added;
-       added->next = NULL;
-
-error:
-       if(cmdline != NULL)
-               free(cmdline);
-       if(fp != NULL)
-               fclose(fp);
-       if(buf != NULL)
-               free(buf);
-
-       if(added == NULL && permissions != NULL)
-               free(permissions);
-
-       return added;
-}
-
-/* Check stored default cookie, if it's not exist make a new one and store it */
-int check_stored_cookie(unsigned char *cookie, int size)
-{
-       int fd, ret;
-
-       /* First, check the default cookie is stored */
-       fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_RDONLY);
-       if(fd < 0)
-       {
-               if(errno != ENOENT)
-               {
-                       SEC_SVR_DBG("Cannot open default cookie. errno=%d", errno);
-                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       unlink(SECURITY_SERVER_DEFAULT_COOKIE_PATH);
-               }
-
-               ret = generate_random_cookie(cookie, size);
-
-               /* Save cookie to disk */
-               fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_WRONLY | O_CREAT, 0600);
-               if (fd < 0)
-               {
-                       SEC_SVR_DBG("Cannot open default cookie errno=%d", errno);
-                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       goto error;
-               }
-               ret = write(fd, cookie, size);
-               if(ret < size)
-               {
-                       SEC_SVR_DBG("%s", "Cannot save default cookie");
-                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       goto error;
-               }
-
-               close(fd);
-               return SECURITY_SERVER_SUCCESS;
-       }
-
-       ret = read (fd, cookie, size);
-       if(ret < size)
-       {
-               SEC_SVR_DBG("Cannot read default cookie errno=%d", errno);
-               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
-               goto error;
-       }
-       ret = SECURITY_SERVER_SUCCESS;
-
-error:
-       if(fd >= 0)
-               close(fd);
-       return ret;
-}
-/* Create a cookie item from PID */
-
-/* Create a default cookie when security server is executed *
- * Default cookie is for root processes that needs cookie */
-cookie_list *create_default_cookie(void)
-{
-       cookie_list *first = NULL;
-       int ret;
-
-       first = malloc(sizeof(cookie_list));
-
-       ret = check_stored_cookie(first->cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(ret != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Error on making random cookie: %d", ret);
-               free(first);
-               return NULL;
-       }
-
-       first->path_len = 0;
-       first->permission_len = 0;
-       first->pid = 0;
-       first->path = NULL;
-       first->permissions = NULL;
-        first->smack_label = NULL;
-       first->prev = NULL;
-       first->next = NULL;
-       return first;
-}
diff --git a/src/security-srv/server/security-server-main.c b/src/security-srv/server/security-server-main.c
deleted file mode 100644 (file)
index 94fe1f5..0000000
+++ /dev/null
@@ -1,1326 +0,0 @@
-/*
- * security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <errno.h>
-#include <signal.h>
-#include <pthread.h>
-#include <limits.h>
-#include <fcntl.h>
-#include <sys/smack.h>
-
-#include "security-server-cookie.h"
-#include "security-server-common.h"
-#include "security-server-password.h"
-#include "security-server-comm.h"
-
-/* Set cookie as a global variable */
-cookie_list *c_list;
-pthread_mutex_t cookie_mutex;
-int thread_status[SECURITY_SERVER_NUM_THREADS];
-struct security_server_thread_param {
-       int client_sockfd;
-       int server_sockfd;
-       int thread_status;
-};
-
-/************************************************************************************************/
-/* Just for test. This code must be removed on release */
-#include "security-server-util.h"
-/************************************************************************************************/
-
-#if 0
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0xF)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-void print_cookie(cookie_list *list)
-{
-       int i;
-       printf("%s", "cookie:\n");
-       printhex(list->cookie, SECURITY_SERVER_COOKIE_LEN);
-       printf("path_len: %d\n", list->path_len);
-       printf("permission_len: %d\n", list->permission_len);
-       printf("PID: %d\n", list->pid);
-       printf("path: %s\n", list->path);
-       printf("%s", "permissions: ");
-       for(i=0;i<list->permission_len;i++)
-       {
-               printf("%d ", list->permissions[i]);
-       }
-       printf("%s", "\n");
-       printf("prev: %p\n", list->prev);
-       printf("next: %p\n", list->next);
-}
-#endif
-
-/* Object name is actually name of a Group ID *
- * This function opens /etc/group file and search group ID and
- * returns the string */
-int search_object_name(int gid, char *obj, int obj_size)
-{
-       FILE *fp = NULL;
-       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
-       int ret = 0, tmp_gid, bufsize;
-       fp = fopen("/etc/group", "r");
-       if(fp == NULL)
-       {
-               /* cannot open /etc/group */
-               SEC_SVR_DBG("%s", "Cannot open /etc/group");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-
-       linebuf = malloc(128);
-       bufsize = 128;
-       if(linebuf == NULL)
-       {
-               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-               SEC_SVR_DBG("%s", "cannot malloc()");
-               goto error;
-       }
-
-       bzero(linebuf, bufsize);
-       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
-       while(fgets(linebuf, bufsize, fp) != NULL)
-       {
-               while(linebuf[bufsize -2] != 0)
-               {
-                       linebuf[bufsize -1] = (char) fgetc(fp);
-                       tempstr = realloc(linebuf, bufsize + 128);
-                       if(tempstr == NULL)
-                       {
-                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-                               goto error;
-                       }
-                       linebuf = tempstr;
-                       bzero(linebuf + bufsize, 128);
-                       fgets(linebuf + bufsize, 128, fp);
-                       bufsize += 128;
-               }
-
-               token = strtok(linebuf, ":");   /* group name */
-               if(token == NULL)
-               {
-                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-               token2 = strtok(NULL, ":");     /* group password */
-               if(token2== NULL)
-               {
-                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-               token2 = strtok(NULL, ":");     /* gid */
-               if(token2 == NULL)
-               {
-                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-
-               errno = 0;
-               tmp_gid = strtoul(token2, 0, 10);
-               if (errno != 0)
-               {
-                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-
-               if(tmp_gid == gid)
-               {
-                       /* We found it */
-                       if(strlen(token) > obj_size)
-                       {
-                               ret = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
-                               SEC_SVR_DBG("buffer is too small. %d --> %d", obj_size, strlen(token));
-                               goto error;
-                       }
-                       strncpy(obj, token, strlen(token));
-                       obj[strlen(token)] = 0;
-                       ret = SECURITY_SERVER_SUCCESS;
-                       break;
-               }
-               bzero(linebuf, bufsize);
-       }
-
-error:
-       if(linebuf != NULL)
-               free(linebuf);
-       if(fp != NULL)
-               fclose(fp);
-       return ret;
-}
-
-/* Search GID from group name *
- * This function opens /etc/group and search group name by given gid */
-int search_gid(const char *obj)
-{
-       FILE *fp = NULL;
-       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
-       int ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT, tmp_gid, bufsize;
-
-       SEC_SVR_DBG("Searching for object %s", obj);
-
-       fp = fopen("/etc/group", "r");
-       if(fp == NULL)
-       {
-               /* cannot open /etc/group */
-               SEC_SVR_DBG("%s", "cannot open /etc/group");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-
-       linebuf = malloc(128);
-       bufsize = 128;
-       if(linebuf == NULL)
-       {
-               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-               SEC_SVR_DBG("%s", "Out Of Memory");
-               goto error;
-       }
-
-       bzero(linebuf, bufsize);
-       while(fgets(linebuf, bufsize, fp) != NULL)
-       {
-               while(linebuf[bufsize -2] != 0 )
-               {
-                       linebuf[bufsize -1] = (char) fgetc(fp);
-                       tempstr = realloc(linebuf, bufsize + 128);
-                       if(tempstr == NULL)
-                       {
-                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-                               goto error;
-                       }
-                       linebuf = tempstr;
-                       bzero(linebuf + bufsize, 128);
-                       fgets(linebuf + bufsize, 128, fp);
-                       bufsize += 128;
-               }
-
-               token = strtok(linebuf, ":");   /* group name */
-               token2 = strtok(NULL, ":");     /* group password */
-               token2 = strtok(NULL, ":");     /* gid */
-               if(token2 == NULL)
-               {
-                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-               errno = 0;
-               tmp_gid = strtoul(token2, 0, 10);
-               if ( errno != 0 )
-               {
-                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
-                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-                       goto error;
-               }
-
-               if(strcmp(obj, token) == 0)
-               {
-                       /* We found it */
-                       ret = tmp_gid;
-                       SEC_SVR_DBG("GID of %s is found: %d", obj, ret);
-                       break;
-               }
-               bzero(linebuf, bufsize);
-       }
-
-error:
-       if(linebuf != NULL)
-               free(linebuf);
-       if(fp != NULL)
-               fclose(fp);
-       return ret;
-}
-
-/* Signal handler for processes */
-static void security_server_sig_child(int signo, siginfo_t *info, void *data)
-{
-       int status;
-       pid_t child_pid;
-       pid_t child_pgid;
-
-       child_pgid = getpgid(info->si_pid);
-       SEC_SVR_DBG("Signal handler: dead_pid=%d, pgid=%d",info->si_pid,child_pgid);
-
-       while ((child_pid = waitpid(-1, &status, WNOHANG)) > 0) {
-               if(child_pid == child_pgid)
-                       killpg(child_pgid,SIGKILL);
-       }
-
-       return;
-}
-
-/* Execute a debugging tool by fork() and execve() */
-int execute_debug_tool(int argc, char *const *argv, int server_sockfd, int client_sockfd)
-{
-       int ret, i;
-       SEC_SVR_DBG("%s", "Executing tool");
-
-       ret = fork();
-       if(ret == 0)
-       {
-               close(client_sockfd);
-               close(server_sockfd);
-               setsid();
-
-               for(i=0;i<_NSIG;i++)
-                       signal(i, SIG_DFL);
-
-               ret = execv(argv[0], argv);
-               if(ret == -1)
-               {
-                       SEC_SVR_DBG("Error:Failed to execute [%d]", errno);
-                       exit(-1);
-               }
-       }
-       if(ret < 0)
-       {
-               SEC_SVR_DBG("Error: Failed to fork [%d]", errno);
-               return SECURITY_SERVER_ERROR_SERVER_ERROR;
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int process_cookie_request(int sockfd)
-{
-       int retval, client_pid, client_uid;
-       cookie_list *created_cookie = NULL;
-
-       /* Authenticate client */
-       retval = authenticate_client_application(sockfd, &client_pid, &client_uid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       /* If client application is root process, just respond default cookie */
-    /*
-       if( client_uid == 0)
-       {
-               SEC_SVR_DBG("%s", "Requested application is a root process");
-               created_cookie = c_list;
-               if(c_list == NULL)
-               {
-                       SEC_SVR_DBG("%s", "Cannot read default cookie");
-                       goto error;
-               }
-       }
-       else
-       {
-    */
-        //TODO: Remove above code if there will be no crashes without it
-        //All process should be treaded the same
-               /* Create a new cookie. or find existing one */
-               pthread_mutex_lock(&cookie_mutex);
-               created_cookie = create_cookie_item(client_pid, sockfd, c_list);
-               pthread_mutex_unlock(&cookie_mutex);
-               if(created_cookie == NULL)
-               {
-                       SEC_SVR_DBG("%s","Cannot create a cookie");
-                       goto error;
-               }
-
-    //let others know if this cookie belongs to root process
-    if(client_uid == 0)
-        created_cookie->is_roots_process = 1;
-    else
-        created_cookie->is_roots_process = 0;
-
-       //}
-       /* send cookie as response */
-       retval = send_cookie(sockfd, created_cookie->cookie);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-       }
-        SEC_SVR_DBG("Server: Cookie created for client PID %d LABEL >%s<",
-                    created_cookie->pid,
-                    (created_cookie->smack_label)?(created_cookie->smack_label):"NULL");
-
-       SEC_SVR_DBG("%s", "Server: Cookie has been sent to client");
-
-error:
-       return retval;
-}
-
-int process_check_privilege_request(int sockfd)
-{
-       /* Authenticate client */
-       int retval, client_pid, requested_privilege;
-       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
-       cookie_list *search_result = NULL;
-
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;;
-       }
-
-       retval = recv_check_privilege_request(sockfd,
-                               requested_cookie, &requested_privilege);
-       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;;
-       }
-
-       if(requested_privilege < 1)
-       {
-               SEC_SVR_DBG("Requiring bad privilege [%d]", requested_privilege);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Search cookie list */
-       pthread_mutex_lock(&cookie_mutex);
-       search_result = search_cookie(c_list, requested_cookie, requested_privilege);
-       pthread_mutex_unlock(&cookie_mutex);
-       if(search_result != NULL)
-       {
-               /* We found */
-               SEC_SVR_DBG("We found the cookie with %d privilege and pid:%d", requested_privilege, client_pid);
-               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       else
-       {
-               /* It's not exist */
-               SEC_SVR_DBG("Could not find the cookie with %d privilege", requested_privilege);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-error:
-       return retval;
-}
-
-int process_check_privilege_new_request(int sockfd)
-{
-       /* Authenticate client */
-       int retval, client_pid, requested_privilege;
-       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
-       cookie_list *search_result = NULL;
-        char object_label[MAX_OBJECT_LABEL_LEN+1];
-        char access_rights[MAX_MODE_STR_LEN+1];
-
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd, 
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;;
-       }
-
-        retval = recv_check_privilege_new_request(
-                     sockfd, requested_cookie, object_label, access_rights);
-       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               retval = send_generic_response(sockfd, 
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;;
-       }
-
-       /* Search cookie list */
-       pthread_mutex_lock(&cookie_mutex);
-       search_result = search_cookie_new(c_list, requested_cookie, object_label, access_rights);
-       pthread_mutex_unlock(&cookie_mutex);
-
-       if(search_result != NULL)
-    {
-               /* We found */
-               SEC_SVR_DBG("We found the cookie with %s rights and pid:%d", access_rights, client_pid);
-               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
-               retval = send_generic_response(sockfd, 
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
-                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       else
-       {
-               /* It's not exist */
-               SEC_SVR_DBG("Could not find the cookie with %s rights", access_rights);
-               retval = send_generic_response(sockfd, 
-                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
-                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-error:
-       return retval;
-
-
-}
-
-int process_object_name_request(int sockfd)
-{
-       int retval, client_pid, requested_privilege;
-       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
-
-       /* Authenticate client */
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive GID */
-       retval = read(sockfd, &requested_privilege, sizeof(requested_privilege));
-       if (retval < sizeof(requested_privilege))
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Search from /etc/group */
-       retval = search_object_name(requested_privilege,
-                       object_name,
-                       SECURITY_SERVER_MAX_OBJ_NAME);
-       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
-       {
-               /* It's not exist */
-               SEC_SVR_DBG("There is no such object for gid [%d]", requested_privilege);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error occurred */
-               SEC_SVR_DBG("Error on searching object name [%d]", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* We found */
-       SEC_SVR_DBG("We found object: %s", object_name);
-       retval = send_object_name(sockfd, object_name);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-       }
-
-error:
-       return retval;
-}
-
-int process_gid_request(int sockfd, int msg_len)
-{
-       int retval, client_pid;
-       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
-       /* Authenticate client as middleware daemon */
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client authentication failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       if(msg_len >= SECURITY_SERVER_MAX_OBJ_NAME)
-       {
-               /* Too big ojbect name */
-               SEC_SVR_DBG("%s", "Object name is too big");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive group name */
-       retval = read(sockfd, object_name, msg_len);
-       if (retval < msg_len )
-       {
-               SEC_SVR_DBG("%s", "Failed to read object name");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       object_name[msg_len] = 0;
-
-       /* Search /etc/group for the given group name */
-       retval = search_gid(object_name);
-       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
-       {
-               /* Not exist */
-               SEC_SVR_DBG("The object [%s] is not exist", object_name);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       if(retval < 0)
-       {
-               /* Error occurred */
-               SEC_SVR_DBG("Cannot send the response. %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-
-               goto error;
-       }
-       /* We found */
-       retval = send_gid(sockfd, retval);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("ERROR: Cannot gid response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-int process_pid_request(int sockfd)
-{
-       int retval, client_pid;
-       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
-       cookie_list *search_result = NULL;
-
-       /* Authenticate client */
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       retval = recv_pid_request(sockfd, requested_cookie);
-       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Search cookie list */
-       pthread_mutex_lock(&cookie_mutex);
-       search_result = search_cookie(c_list, requested_cookie, 0);
-       pthread_mutex_unlock(&cookie_mutex);
-       if(search_result != NULL)
-       {
-               /* We found */
-               SEC_SVR_DBG("We found the cookie and pid:%d", search_result->pid);
-               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
-               retval = send_pid(sockfd, search_result->pid);
-
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       else
-       {
-               /* It's not exist */
-               SEC_SVR_DBG("%s", "Could not find the cookie");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send pid response: %d", retval);
-               }
-       }
-error:
-       return retval;
-}
-
-int process_smack_request(int sockfd)
-{
-       int retval, client_pid;
-       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
-       cookie_list *search_result = NULL;
-    //handler for SMACK label
-    char * label = NULL;
-    //buffer for storing file path
-    const int BUFFSIZE = 30;
-    char path[BUFFSIZE];
-    int fd;
-
-       /* Authenticate client */
-       retval = authenticate_client_middleware(sockfd, &client_pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       retval = recv_smack_request(sockfd, requested_cookie);
-       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Search cookie list */
-       pthread_mutex_lock(&cookie_mutex);
-       search_result = search_cookie(c_list, requested_cookie, 0);
-       pthread_mutex_unlock(&cookie_mutex);
-       if(search_result != NULL)
-       {
-               /* We found */
-               SEC_SVR_DBG("We found the cookie and pid:%d", search_result->pid);
-               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
-
-        //clearing buffer
-        memset(path, 0x00, BUFFSIZE);
-
-        //preparing file path
-        snprintf(path, BUFFSIZE, "/proc/%d/attr/current", search_result->pid);
-        SEC_SVR_DBG("Path to file: %s\n", path);
-
-        //allocation place for label
-        label = calloc(SMACK_LABEL_LEN, 1);
-        if(NULL == label)
-        {
-            SEC_SVR_DBG("Client ERROR: Memory allocation error");
-            goto error;
-        }
-
-        //clearing buffer for label
-        memset(label, 0x00, SMACK_LABEL_LEN);
-
-        //opening file /proc/<pid>/attr/curent with SMACK label
-        fd = open(path, O_RDONLY);
-        if(fd < 0)
-        {
-            SEC_SVR_DBG("Client ERROR: Unable to open file in /proc");
-            goto error;
-        }
-
-        //reading label from file, it is NOT NULL TERMINATED
-        retval = read(fd, label, SMACK_LABEL_LEN);
-        close(fd);
-        if(retval < 0)
-        {
-            SEC_SVR_DBG("Client ERROR: Unable to read from file");
-            goto error;
-        }
-
-        SEC_SVR_DBG("Readed label is: %s\n", label);
-
-               retval = send_smack(sockfd, label);
-
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       else
-       {
-               /* It's not exist */
-               SEC_SVR_DBG("%s", "Could not find the cookie");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send SMACK label response: %d", retval);
-               }
-       }
-error:
-    if(NULL != label)
-        free(label);
-
-       return retval;
-}
-
-int process_tool_request(int client_sockfd, int server_sockfd)
-{
-       int retval, argcnum;
-       char **recved_argv = NULL;
-
-       /* Authenticate client */
-       retval = authenticate_developer_shell(client_sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive Total number of argv */
-       argcnum = 0;
-       retval = read(client_sockfd, &argcnum, sizeof(int));
-       if((retval < sizeof(int)) || argcnum > (UINT_MAX/sizeof(char *))-2 || argcnum < 0)
-       {
-               SEC_SVR_DBG("Error: argc recieve failed: %d", retval);
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       argcnum += 2;
-       recved_argv = (char **)malloc(sizeof(char *) * argcnum);
-       if(recved_argv == NULL)
-       {
-               SEC_SVR_DBG("Error: malloc() failed: %d", retval);
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       memset(recved_argv, 0, sizeof(char *) * argcnum);
-
-       retval = recv_launch_tool_request(client_sockfd, argcnum -1, recved_argv);
-       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED || retval == SECURITY_SERVER_ERROR_OUT_OF_MEMORY)
-       {
-               SEC_SVR_DBG("%s", "Receiving request failed");
-               recved_argv = NULL;
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       if(argcnum < 2)
-       {
-               SEC_SVR_DBG("Error: Too small number of argv [%d]", argcnum);
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       /* Execute the command */
-       retval = execute_debug_tool(argcnum, recved_argv, server_sockfd, client_sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Error: Cannot execute debug tool [%d]", retval);
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       else
-       {
-               SEC_SVR_DBG("%s", "Tool has been executed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SUCCESS);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-error:
-       if(recved_argv != NULL)
-       {
-               /* Free */
-               free_argv(recved_argv, argcnum);
-               recved_argv = NULL;
-               argcnum =0;;
-       }
-       return retval;
-}
-
-void *security_server_thread(void *param)
-{
-       int client_sockfd = -1, client_uid, client_pid;
-       int server_sockfd, retval, argcnum;
-       basic_header basic_hdr;
-       struct security_server_thread_param *my_param;
-
-       my_param = (struct security_server_thread_param *) param;
-       client_sockfd = my_param->client_sockfd;
-       server_sockfd = my_param->server_sockfd;
-
-       /* Receive request header */
-       retval = recv_hdr(client_sockfd, &basic_hdr);
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT || retval == SECURITY_SERVER_ERROR_RECV_FAILED
-               || retval == SECURITY_SERVER_ERROR_SOCKET)
-       {
-               SEC_SVR_DBG("Receiving header error [%d]",retval);
-               close(client_sockfd);
-               client_sockfd = -1;
-               goto error;;
-       }
-
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Response */
-               SEC_SVR_DBG("Receiving header error [%d]",retval);
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-                       goto error;
-               }
-               safe_server_sock_close(client_sockfd);
-               client_sockfd = -1;
-               goto error;
-       }
-
-       /* Act different for request message ID */
-       switch(basic_hdr.msg_id)
-       {
-               case SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST:
-                       SEC_SVR_DBG("%s", "Cookie request received");
-                       process_cookie_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST:
-                       SEC_SVR_DBG("%s", "Privilege check received");
-                       process_check_privilege_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST:
-                       SEC_SVR_DBG("%s", "Privilege check (new mode) received");
-                       process_check_privilege_new_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST:
-                       SEC_SVR_DBG("%s", "Get object name request received");
-                       process_object_name_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_GID_REQUEST:
-                       SEC_SVR_DBG("%s", "Get GID received");
-                       process_gid_request(client_sockfd, (int)basic_hdr.msg_len);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_PID_REQUEST:
-                       SEC_SVR_DBG("%s", "pid request received");
-                       process_pid_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST:
-                       SEC_SVR_DBG("%s", "SMACK label request received");
-                       process_smack_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST:
-                       SEC_SVR_DBG("%s", "launch tool request received");
-                       process_tool_request(client_sockfd, server_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST:
-                       SEC_SVR_DBG("%s", "Server: validate password request received");
-                       process_valid_pwd_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST:
-                       SEC_SVR_DBG("%s", "Server: set password request received");
-                       process_set_pwd_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST:
-                       SEC_SVR_DBG("%s", "Server: reset password request received");
-                       process_reset_pwd_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST:
-                       SEC_SVR_DBG("%s", "Server: check password request received");
-                       process_chk_pwd_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST:
-                       SEC_SVR_DBG("%s", "Server: set password histroy request received");
-                       process_set_pwd_history_request(client_sockfd);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST:
-                   SEC_SVR_DBG("%s", "Server: set password max challenge request received");
-                   process_set_pwd_max_challenge_request(client_sockfd);
-                   break;
-
-        case SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST:
-            SEC_SVR_DBG("%s", "Server: set password validity request received");
-            process_set_pwd_validity_request(client_sockfd);
-            break;
-
-/************************************************************************************************/
-/* Just for test. This code must be removed on release */
-               case SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST:
-                       SEC_SVR_DBG("%s", "all cookie info request received -- NEED TO BE DELETED ON RELEASE");
-                       retval = authenticate_client_application(client_sockfd, &client_pid, &client_uid);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("%s", "Client Authentication Failed");
-                               retval = send_generic_response(client_sockfd,
-                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-                               if(retval != SECURITY_SERVER_SUCCESS)
-                               {
-                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-                               }
-                               break;
-                       }
-                       retval = util_process_all_cookie(client_sockfd, c_list);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("ERROR: Cannot send all cookie info: %d", retval);
-                       }
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST:
-                       SEC_SVR_DBG("%s", "cookie info from pid request received -- NEED TO BE DELETED ON RELEASE");
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("%s", "Client Authentication Failed");
-                               retval = send_generic_response(client_sockfd,
-                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-                               if(retval != SECURITY_SERVER_SUCCESS)
-                               {
-                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-                               }
-                               break;
-                       }
-                       util_process_cookie_from_pid(client_sockfd, c_list);
-                       break;
-
-               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST:
-                       SEC_SVR_DBG("%s", "cookie info from cookie request received -- NEED TO BE DELETED ON RELEASE");
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("%s", "Client Authentication Failed");
-                               retval = send_generic_response(client_sockfd,
-                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-                               if(retval != SECURITY_SERVER_SUCCESS)
-                               {
-                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-                               }
-                               break;
-                       }
-                       util_process_cookie_from_cookie(client_sockfd, c_list);
-                       break;
-/************************************************************************************************/
-
-
-               default:
-                       SEC_SVR_DBG("Unknown msg ID :%d", basic_hdr.msg_id);
-                       /* Unknown message ID */
-                       retval = send_generic_response(client_sockfd,
-                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-                       }
-                       break;
-       }
-
-       if(client_sockfd > 0)
-       {
-               safe_server_sock_close(client_sockfd);
-               client_sockfd = -1;
-       }
-
-error:
-       if(client_sockfd > 0)
-               close(client_sockfd);
-       thread_status[my_param->thread_status] = 0;
-       pthread_detach(pthread_self());
-       pthread_exit(NULL);
-}
-
-void *security_server_main_thread(void *data)
-{
-       int server_sockfd = 0, retval, client_sockfd = -1, args[2], rc;
-       struct sigaction act, dummy;
-       pthread_t threads[SECURITY_SERVER_NUM_THREADS];
-       struct security_server_thread_param param[SECURITY_SERVER_NUM_THREADS];
-
-       SEC_SVR_DBG("%s", "Starting Security Server main thread");
-
-       /* security server must be executed by root */
-       if(getuid() != 0)
-       {
-               fprintf(stderr, "%s\n", "You are not root. exiting...");
-               goto error;
-       }
-
-       for(retval = 0 ; retval < SECURITY_SERVER_NUM_THREADS; retval++)
-               thread_status[retval] = 0;
-       initiate_try();
-
-       /* Create and bind a Unix domain socket */
-       retval = create_new_socket(&server_sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "cannot create socket. exiting...");
-               goto error;
-       }
-
-       if(listen(server_sockfd, 5) < 0)
-       {
-               SEC_SVR_DBG("%s", "listen() failed. exiting...");
-               goto error;
-       }
-
-       /* Create a default cookie --> Cookie for root process */
-       c_list = create_default_cookie();
-       if(c_list == NULL)
-       {
-               SEC_SVR_DBG("%s", "cannot make a default cookie. exiting...");
-               goto error;
-       }
-
-       /* Init signal handler */
-       act.sa_handler = NULL;
-       act.sa_sigaction = security_server_sig_child;
-       sigemptyset(&act.sa_mask);
-       act.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
-
-       if (sigaction(SIGCHLD, &act, &dummy) < 0)
-       {
-               SEC_SVR_DBG("%s", "cannot change session");
-       }
-
-       pthread_mutex_init(&cookie_mutex, NULL);
-
-       while(1)
-       {
-               /* Accept a new client */
-               if(client_sockfd < 0)
-                       client_sockfd = accept_client(server_sockfd);
-
-               if(client_sockfd == SECURITY_SERVER_ERROR_TIMEOUT)
-                       continue;
-               if(client_sockfd < 0)
-                       goto error;
-               SEC_SVR_DBG("Server: new connection has been accepted: %d", client_sockfd);
-               retval = 0;
-               while(1)
-               {
-                       if(thread_status[retval] == 0)
-                       {
-                               thread_status[retval] = 1;
-                               param[retval].client_sockfd = client_sockfd;
-                               param[retval].server_sockfd = server_sockfd;
-                               param[retval].thread_status= retval;
-                               SEC_SVR_DBG("Server: Creating a new thread: %d", retval);
-                               rc =pthread_create(&threads[retval], NULL, security_server_thread, (void *)&param[retval]);
-                               if (rc)
-                               {
-                                       SEC_SVR_DBG("Error: Server: Cannot create thread:%d", rc);
-                                       goto error;
-                               }
-                               break;
-                       }
-                       retval++;
-                       if(retval >= SECURITY_SERVER_NUM_THREADS)
-                               retval = 0;
-               }
-               client_sockfd = -1;
-       }
-error:
-       if(server_sockfd > 0)
-               close(server_sockfd);
-
-       pthread_detach(pthread_self());
-       pthread_exit(NULL);
-}
-
-int main(int argc, char* argv[])
-{
-       int res;
-       pthread_t main_thread;
-
-       res = pthread_create(&main_thread, NULL, security_server_main_thread, NULL);
-       if (res == 0)
-       {
-               while (1)
-                       sleep(60);
-       }
-       else
-       {
-               SEC_SVR_DBG("Error: Server: Cannot create main security server thread: %d", res);
-       }
-       pthread_exit(NULL);
-       return 0;
-}
-
diff --git a/src/security-srv/server/security-server-password.c b/src/security-srv/server/security-server-password.c
deleted file mode 100644 (file)
index 367b5d6..0000000
+++ /dev/null
@@ -1,1579 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <dirent.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <openssl/sha.h>
-
-#include "security-server-password.h"
-
-struct timeval prev_try;
-
-void initiate_try()
-{
-       gettimeofday(&prev_try, NULL);
-}
-
-int validate_pwd_file(char *filename)
-{
-       int i;
-
-       if((strncmp(filename + (strlen(filename) -4), ".pwd" , 4)) != 0)
-       {
-               SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
-               return SECURITY_SERVER_ERROR_NO_PASSWORD;
-       }
-
-       for(i=0;i<(strlen(filename) -4);i++)
-       {
-               if(filename[i] > '9' || filename[i] < '0')
-               {
-                       SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
-                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
-               }
-       }
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int dir_filter(const struct dirent *entry)
-{
-       if ((strcmp(entry->d_name, ".") == 0) ||
-               (strcmp(entry->d_name, "..") == 0) ||
-               (strcmp(entry->d_name, "attempts") ==0) ||
-               (strcmp(entry->d_name, "history") ==0) )
-               return (0);
-       else
-               return (1);
-}
-
-int get_pwd_path(char *path)
-{
-       int retval;
-       struct dirent **mydirent;
-       int num;
-       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
-       if(num < 0)
-       {
-               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       if(num == 0)
-       {
-               SEC_SVR_DBG("%s", "Server: There is no password file");
-               return SECURITY_SERVER_ERROR_NO_PASSWORD;
-       }
-
-       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num-1]->d_name);
-       retval = validate_pwd_file(mydirent[num-1]->d_name);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Removing invalid password file: %s", path);
-               unlink(path);
-               get_pwd_path(path);
-       }
-       SEC_SVR_DBG("Password file path: %s", path);
-       while (num--)
-               free(mydirent[num]);
-       free(mydirent);
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int load_password(unsigned char *cur_pwd, unsigned int *max_attempt, unsigned int *expire_time)
-{
-       int retval, fd;
-       char pwd_path[255];
-
-       /* Create directory */
-       retval = mkdir(SECURITY_SERVER_DATA_DIRECTORY_PATH, 0700);
-       if(retval != 0)
-       {
-               if(errno != EEXIST)
-               {
-                       SEC_SVR_DBG("Cannot create directory. errno: %d", errno);
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-       }
-
-       /* Check password files */
-       while(1)
-       {
-               /* Get password file path */
-               retval = get_pwd_path(pwd_path);
-               if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
-               {
-                       SEC_SVR_DBG("%s", "Current password doesn't exist");
-                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
-               }
-
-               /* Load password file */
-               fd = open(pwd_path, O_RDONLY | O_NONBLOCK );
-               if(fd < 0)
-               {
-                       if(errno == ENOENT)
-                       {
-                               SEC_SVR_DBG("%s", "Server: Current password doesn't exist");
-                               return SECURITY_SERVER_ERROR_NO_PASSWORD;
-                       }
-                       SEC_SVR_DBG("Server: Current password cannot be opened. errno: %d", errno);
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-
-               /* Read and store into memory */
-               retval = read(fd, cur_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
-               if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
-               {
-                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 0");
-                       close(fd);
-                       fd = 0;
-                       unlink(pwd_path);
-                       continue;
-               }
-
-               retval = read(fd, max_attempt, sizeof(unsigned int));
-               if(retval < sizeof(unsigned int))
-               {
-                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 1");
-                       close(fd);
-                       fd = 0;
-                       unlink(pwd_path);
-                       continue;
-               }
-
-               retval = read(fd, expire_time, sizeof(unsigned int));
-               if(retval < sizeof(unsigned int))
-               {
-                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 2");
-                       close(fd);
-                       fd = 0;
-                       unlink(pwd_path);
-                       continue;
-               }
-               close(fd);
-
-               /* Check expiration time. */
-               if(*expire_time == 0)  /* No valid period */
-                       *expire_time = 0xffffffff;
-               else if(*expire_time <= time(NULL)) /* expired */
-                       *expire_time =0;
-               else            /* valid yet */
-                       *expire_time -= time(NULL);
-               break;
-       }
-       SEC_SVR_DBG("%s", "Server: Current password file successfully loaded");
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int get_current_attempt(int increase)
-{
-       int retval, fd, attempt;
-       char path[255];
-
-       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
-               SECURITY_SERVER_ATTEMPT_FILE_NAME);
-
-       /* Open current attempt file as read mode */
-       fd = open(path, O_RDONLY | O_NONBLOCK );
-       if(fd < 0)
-       {
-               if(errno == ENOENT)
-               {
-                       SEC_SVR_DBG("%s", "Server: attempt doesn't exist. Creating one:");
-                       /* Create one if it doesn't exist */
-                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
-                       if(fd < 0)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
-                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       }
-                       retval = fchmod(fd, 0600);
-                       if(retval != 0)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
-                               close(fd);
-                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       }
-                       attempt = increase;
-                       retval = write(fd, &attempt, sizeof(int));
-                       close(fd);
-                       if(retval < sizeof(int))
-                       {
-                               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
-                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       }
-                       return attempt;
-               }
-               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = read(fd, &attempt, sizeof(int));
-       close(fd);
-       if(retval < sizeof(int))
-       {
-               SEC_SVR_DBG("%s", "Server ERROR: Cannot read attempt");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-
-       if(increase > 0)
-       {
-               /* Open the file again with write mode */
-               fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
-               if(fd < 0)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-               retval = fchmod(fd, 0600);
-               if(retval != 0)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
-                       close(fd);
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-               attempt += increase;
-               retval = write(fd, &attempt, sizeof(int));
-               close(fd);
-               if(retval < sizeof(int))
-               {
-                       SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-       }
-       return attempt;
-}
-
-int reset_attempt(void)
-{
-       int fd, retval;
-       char path[255];
-       unsigned int attempt = 0;
-
-       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
-               SECURITY_SERVER_ATTEMPT_FILE_NAME);
-
-       /* Open the file again with write mode */
-       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
-       if(fd < 0)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = fchmod(fd, 0600);
-       if(retval != 0)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = write(fd, &attempt, sizeof(int));
-       close(fd);
-       if(retval < sizeof(int))
-       {
-               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       SEC_SVR_DBG("%s", "Server: Attempt reset");
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Compare current password Stored password is hashed by SHA-256 Algorithm */
-int check_password(const unsigned char *cur_pwd, const unsigned char *requested_pwd,
-                       const unsigned int max_attempts, const unsigned int expire_time,
-                       int *current_attempt)
-{
-       unsigned int current_time = time(NULL);
-
-       if(max_attempts != 0)
-       {
-               *current_attempt = get_current_attempt(1);
-
-               if(*current_attempt > max_attempts)
-               {
-                       SEC_SVR_DBG("Server: Max attempt exceeded: %d, %d", *current_attempt, max_attempts);
-                       return SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
-               }
-               if(*current_attempt < 0)
-               {
-                       SEC_SVR_DBG("Server: Attempt file operation failed. Ignoring... : %d", *current_attempt);
-               }
-       }
-
-       /* Compare */
-       if(memcmp(cur_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) != 0)
-       {
-           SEC_SVR_DBG("%s", "Password mismatched");
-           return SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
-       }
-
-    if(expire_time == 0)
-    {
-        SEC_SVR_DBG("Server: Password has been expired: %d, %d", current_time, expire_time);
-        return SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
-    }
-
-    SEC_SVR_DBG("%s", "Password matched");
-    return SECURITY_SERVER_SUCCESS;
-}
-
-int set_history(int num)
-{
-       int fd, retval;
-       char path[255];
-
-       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
-               SECURITY_SERVER_HISTORY_FILE_NAME);
-
-       /* Open the file again with write mode */
-       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
-       if(fd < 0)
-       {
-               if (errno == ENOENT)
-               {
-                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
-                       if(fd < 0)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot create history file. errno: %d", errno);
-                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       }
-               }
-               else
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot open history file. errno: %d", errno);
-                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
-               }
-       }
-       retval = fchmod(fd, 0600);
-       if(retval != 0)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot chmod history file. errno: %d", errno);
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = write(fd, &num, sizeof(int));
-       close(fd);
-       if(retval < sizeof(int))
-       {
-               SEC_SVR_DBG("%s", "Server ERROR: Cannot write history");
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       SEC_SVR_DBG("%s", "Server: history set finished");
-       return SECURITY_SERVER_SUCCESS;
-}
-
-
-int get_history_num(void)
-{
-       /* Placeholder for password history check count getting function */
-       int fd, retval, history;
-       char path[255];
-
-       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
-               SECURITY_SERVER_HISTORY_FILE_NAME);
-
-       /* Load password file */
-       fd = open(path, O_RDONLY | O_NONBLOCK );
-       if(fd < 0)
-       {
-               if(errno == ENOENT)
-               {
-                       SEC_SVR_DBG("%s", "Server: history file doesn't exist");
-                       retval = set_history(0);
-                       return retval;
-               }
-               SEC_SVR_DBG("Server ERROR: history file cannot be opened. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = read(fd, &history, sizeof(history));
-       close(fd);
-       if(retval < sizeof(history))
-       {
-               SEC_SVR_DBG("%s", "History file corrupted. Creating new one");
-               unlink(path);
-               retval = set_history(0);
-               return retval;
-       }
-       SEC_SVR_DBG("History file read: %d", history);
-       return history;
-}
-
-
-
-int check_history(const unsigned char *requested_pwd)
-{
-       unsigned char history_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-       char path[255];
-       unsigned int max_history;
-       int num, history_count, fd, file_count, retval;
-       int retval2 = SECURITY_SERVER_SUCCESS;
-       struct dirent **mydirent;
-
-       history_count = get_history_num();
-       if(history_count <= 0)
-               return SECURITY_SERVER_SUCCESS;
-
-       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
-       if(num < 0)
-       {
-               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-
-       if(num == 0)
-       {
-               SEC_SVR_DBG("%s", "Server: There is no password file");
-               return SECURITY_SERVER_ERROR_NO_PASSWORD;
-       }
-
-       file_count = 2;
-       while((num--))
-       {
-               snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num]->d_name);
-               SEC_SVR_DBG("Password file path: %s", path);
-               if(history_count > 0)
-               {
-                       /* Load password file */
-                       fd = open(path, O_RDONLY | O_NONBLOCK );
-                       if(fd < 0)
-                       {
-                               if(errno == ENOENT)
-                               {
-                                       SEC_SVR_DBG("%s", "Current password doesn't exist");
-                                       return SECURITY_SERVER_SUCCESS;
-                               }
-                               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
-                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-                       }
-                       /* Read and store into memory */
-                       retval = read(fd, history_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
-                       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
-                       {
-                               SEC_SVR_DBG("%s", "Current password corrupted. resetting to previous one. 0");
-                               close(fd);
-                               fd = 0;
-                               unlink(path);
-                               continue;
-                       }
-                       close(fd);
-                       /* Compare */
-                       if(memcmp(history_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) == 0)
-                       {
-                               SEC_SVR_DBG("%s", "Server: Password has been reused");
-                               retval2 =  SECURITY_SERVER_ERROR_PASSWORD_REUSED;
-                       }
-                       history_count--;
-
-               }
-
-               /* Remove too old or invalid password history */
-               retval = validate_pwd_file(mydirent[num]->d_name);
-               if(retval != SECURITY_SERVER_SUCCESS || file_count > (SECURITY_SERVER_MAX_PASSWORD_HISTORY))
-               {
-                       SEC_SVR_DBG("Removing too old password. %s", path);
-                       unlink(path);
-               }
-               file_count++;
-               free(mydirent[num]);
-       }
-       free(mydirent);
-       if(retval2 == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
-               retval = retval2;
-       return retval;
-}
-
-/* Password file format */
-/*  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                                                               |
- * |                       Hashed PWD (32 bytes)                   |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                       Max attempts (4 bytes)                  |
- * |---------------------------------------------------------------|
- * |              Expiration time in seconds (4 bytes)             |
- * |---------------------------------------------------------------|
- */
-int set_password(const unsigned char *requested_new_pwd, const unsigned int attempts,
-                       const unsigned int expire_time)
-{
-       int retval, fd;
-       char pwd_path[255];
-
-       /* New file created */
-       retval = time(NULL);
-       snprintf(pwd_path, 255, "%s/%d.pwd", SECURITY_SERVER_DATA_DIRECTORY_PATH, retval);
-
-       /* Save new password as current password */
-       fd = open(pwd_path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
-       if(fd < 0)
-       {
-               SEC_SVR_DBG("Cannot open current password file. errno: %d", errno);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = fchmod(fd, 0600);
-       if(retval != 0)
-       {
-               SEC_SVR_DBG("Cannot chmod current password file. errno: %d", errno);
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = write(fd, requested_new_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
-       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
-       {
-               SEC_SVR_DBG("%s", "Cannot write password");
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = write(fd, &attempts, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("%s", "Cannot write password");
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       retval = write(fd, &expire_time, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("%s", "Cannot write password");
-               close(fd);
-               return SECURITY_SERVER_ERROR_FILE_OPERATION;
-       }
-       fsync(fd);
-       close(fd);
-       SEC_SVR_DBG("%s", "Password file created");
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int check_retry(const struct timeval cur_try)
-{
-       int retval, interval_sec, interval_usec;
-       interval_sec = cur_try.tv_sec - prev_try.tv_sec;
-       interval_usec = cur_try.tv_usec - prev_try.tv_usec;
-       prev_try = cur_try;
-       if(interval_sec > SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND)
-               return SECURITY_SERVER_SUCCESS;
-
-       if(interval_sec == SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND
-                       && interval_usec >= 0)
-               return SECURITY_SERVER_SUCCESS;
-
-       SEC_SVR_DBG("%s", "retry timer hit");
-       return SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
-}
-
-int process_valid_pwd_request(int sockfd)
-{
-       struct timeval cur_try;
-       int retval, current_attempts, password_set;
-       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-       unsigned int max_attempt, expire_time;
-
-/*
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-*/
-
-       /* Check retry timer */
-       gettimeofday(&cur_try, NULL);
-       retval = check_retry(cur_try);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
-       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
-       {
-               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       current_attempts = get_current_attempt(0);
-       if(current_attempts < 0)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot get attempts: %d", current_attempts);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-
-       /* There is no password */
-       if(password_set == SECURITY_SERVER_ERROR_NO_PASSWORD)
-       {
-               retval = send_pwd_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_NO_PASSWORD,
-                               0, 0, 0);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
-               }
-               goto error;
-       }
-       if(password_set == SECURITY_SERVER_SUCCESS)
-       {
-               retval = send_pwd_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST,
-                               current_attempts, max_attempt, expire_time);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
-               }
-               goto error;
-       }
-       SEC_SVR_DBG("Server ERROR: Unknown error: %d", retval);
-       retval = send_generic_response(sockfd,
-                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-int process_set_pwd_request(int sockfd)
-{
-       struct timeval cur_try;
-       int retval, password_set, current_attempt;
-       unsigned int max_attempt, expire_time, valid_days, received_attempts;
-       char  new_pwd_len = 0, cur_pwd_len = 0;
-       char requested_cur_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
-       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
-       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
-       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
-
-       SHA256_CTX context;
-
-       /* Authenticate client that peer is setting app goes here*/
-       /* Check SMACK 'rw' rule for the set password */
-       retval = SECURITY_SERVER_SUCCESS;
-/*
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-*/
-
-       /* Check retry timer */
-       gettimeofday(&cur_try, NULL);
-       retval = check_retry(cur_try);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
-       /* If we cannot load password file */
-       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
-       {
-               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive size of pwds */
-       retval = read(sockfd, &cur_pwd_len, sizeof(char));
-       if(retval < sizeof(char) || cur_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
-       {
-               SEC_SVR_DBG("Server Error: current password length recieve failed: %d, %d", retval, cur_pwd_len);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       retval = read(sockfd, &new_pwd_len, sizeof(char));
-       if(retval < sizeof(char)  || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN || new_pwd_len < 0)
-       {
-               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive current password */
-       if(cur_pwd_len > 0)
-       {
-               /* Check wheter current password is exist */
-               if(password_set == SECURITY_SERVER_SUCCESS)
-               retval = read(sockfd, requested_cur_pwd, cur_pwd_len);
-               if(retval < cur_pwd_len)
-               {
-                       SEC_SVR_DBG("Server Error: current password recieve failed: %d", retval);
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               requested_cur_pwd[cur_pwd_len] = 0;
-       }
-       else /* Check first password set attempt but password is already set */
-       {
-               if(password_set == SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server Error: password is already set: %d", retval);
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-       }
-
-       /* Receive new password */
-       retval = read(sockfd, requested_new_pwd, new_pwd_len);
-       if(retval < new_pwd_len)
-       {
-               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       requested_new_pwd[new_pwd_len] = 0;
-
-       /* Receive max attempt */
-       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive valid period  */
-       retval = read(sockfd, &valid_days, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Hash requested password */
-       SHA256_Init(&context);
-       SHA256_Update(&context, (unsigned char*)requested_cur_pwd, strlen(requested_cur_pwd));
-       SHA256_Final(hashed_challenge, &context);
-
-       SHA256_Init(&context);
-       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
-       SHA256_Final(hashed_new_pw, &context);
-
-       /* check current password */
-       if(password_set  == SECURITY_SERVER_SUCCESS)
-       {
-               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
-               {
-                       SEC_SVR_DBG("%s", "Server: Wrong password");
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
-               {
-                       SEC_SVR_DBG("%s", "Server: Too many challange");
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
-               {
-                       SEC_SVR_DBG("%s", "Server: Password expired");
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Error: Password check failed: %d", retval);
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               retval = check_history(hashed_new_pw);
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
-               {
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-       }
-       else if(cur_pwd_len != 0)
-       {
-               /* Client ask to set with current password, but there is no password now */
-               SEC_SVR_DBG("%s", "Server: There is no current password. But try to set with current password");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Calculate expire time in seconds */
-       if(valid_days == 0)
-               expire_time = 0;
-       else
-               expire_time = time(NULL) + (valid_days * 86400);
-
-       /* set new password */
-       retval = set_password(hashed_new_pw, received_attempts, expire_time);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               password_set = SECURITY_SERVER_ERROR_SERVER_ERROR;
-               goto error;
-       }
-       password_set = SECURITY_SERVER_SUCCESS;
-       retval = reset_attempt();
-
-       /* All done. send response */
-       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
-       retval = send_generic_response(sockfd,
-                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-int process_reset_pwd_request(int sockfd)
-{
-       int retval, password_set;
-       char new_pwd_len;
-       unsigned int valid_days, received_attempts, expire_time;
-       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN +1];
-       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
-       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-       struct timeval cur_try;
-
-       SHA256_CTX context;
-
-       /* Authenticate client that peer is setting app goes here*/
-/*
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-*/
-
-       /* Check retry timer */
-       gettimeofday(&cur_try, NULL);
-       retval = check_retry(cur_try);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       password_set = load_password(cur_pwd, &valid_days, &expire_time);
-       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
-       {
-               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive size of pwd */
-       retval = read(sockfd, &new_pwd_len, sizeof(char));
-       if(retval < sizeof(char) || new_pwd_len < 0 || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
-       {
-               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive new password */
-       retval = read(sockfd, requested_new_pwd, new_pwd_len);
-       if(retval < new_pwd_len)
-       {
-               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       requested_new_pwd[new_pwd_len] = 0;
-
-       /* Receive max attempt */
-       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive valid period  */
-       retval = read(sockfd, &valid_days, sizeof(unsigned int));
-       if(retval < sizeof(unsigned int))
-       {
-               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Calculate expire time in seconds */
-       if(valid_days == 0)
-               expire_time = 0;
-       else
-               expire_time = time(NULL) + (valid_days * 86400);
-
-       /* Hash requested password */
-       SHA256_Init(&context);
-       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
-       SHA256_Final(hashed_new_pw, &context);
-       /* set new password */
-       retval = set_password(hashed_new_pw, received_attempts, expire_time);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       retval = reset_attempt();
-
-       /* All done. send response */
-       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
-       retval = send_generic_response(sockfd,
-                       SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-int process_chk_pwd_request(int sockfd)
-{
-       int retval, password_set, current_attempt;
-       unsigned int max_attempt, expire_time;
-       char requested_challenge[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
-       char challenge_len;
-       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
-       struct timeval cur_try;
-
-       SHA256_CTX context;
-
-       /* Authenticate client that peer is proper app goes here*/
-       /* Check SMACK rule for the 'r' for password */
-       retval = SECURITY_SERVER_SUCCESS;
-/*
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-*/
-       /* Check retry timer */
-       gettimeofday(&cur_try, NULL);
-       retval = check_retry(cur_try);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* If we cannot load password file */
-       password_set = load_password(cur_pwd, &max_attempt, &expire_time);;
-       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
-       {
-               SEC_SVR_DBG("%s", "ServerERROR: Responding error because we cannot provide password service");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive size of challenge */
-       retval = read(sockfd, &challenge_len, sizeof(char));
-       if(retval < sizeof(char) || challenge_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
-       {
-               SEC_SVR_DBG("Server ERROR: challenge length recieve failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-       /* Receive challenge */
-       if(challenge_len > 0)
-       {
-               retval = read(sockfd, requested_challenge, challenge_len);
-               if(retval < challenge_len)
-               {
-                       SEC_SVR_DBG("Server ERROR: current password recieve failed: %d", retval);
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               requested_challenge[challenge_len] = 0;
-       }
-       else
-       {
-               SEC_SVR_DBG("Error: Challenge length too short: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Hash requested password */
-       SHA256_Init(&context);
-       SHA256_Update(&context, (unsigned char*)requested_challenge, challenge_len);
-       SHA256_Final(hashed_challenge, &context);
-
-       /* check current password */
-       if(password_set  == SECURITY_SERVER_SUCCESS)
-       {
-               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
-               {
-                       SEC_SVR_DBG("%s", "Server: Wrong password");
-                       retval = send_pwd_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH,
-                                       current_attempt, max_attempt, expire_time);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
-               {
-                       SEC_SVR_DBG("%s", "Server: Too many trial");
-                       retval = send_pwd_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED,
-                                       current_attempt, max_attempt, expire_time);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
-               {
-                       SEC_SVR_DBG("%s", "Server: Password expired");
-                       retval = send_pwd_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED,
-                                       current_attempt, max_attempt, 0);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Password check failed: %d", retval);
-                       retval = send_generic_response(sockfd,
-                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-                       if(retval != SECURITY_SERVER_SUCCESS)
-                       {
-                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-                       }
-                       goto error;
-               }
-
-               /* Password matched */
-               SEC_SVR_DBG("%s", "Server: Password matched");
-               retval = send_pwd_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SUCCESS,
-                               current_attempt, max_attempt, expire_time);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               retval = reset_attempt();
-               goto error;
-       }
-
-       /* There is no password */
-
-       SEC_SVR_DBG("%s", "Server: There is no password to be checked");
-       retval = send_generic_response(sockfd,
-                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-int process_set_pwd_history_request(int sockfd)
-{
-       int retval;
-       char history_num;
-       struct timeval cur_try;
-
-       /* Authenticate client that peer is setting app goes here*/
-/*
-       f(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Client Authentication Failed");
-               retval = send_generic_response(client_sockfd,
-                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-*/
-
-       /* Check retry timer */
-       gettimeofday(&cur_try, NULL);
-       retval = check_retry(cur_try);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       /* Receive size of pwds */
-       retval = read(sockfd, &history_num, sizeof(char));
-       if(retval < sizeof(char) || history_num > SECURITY_SERVER_MAX_PASSWORD_HISTORY || history_num < 0 )
-       {
-               SEC_SVR_DBG("Server Error: History number recieve failed: %d, %d", retval, history_num);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-               goto error;
-       }
-
-       retval = set_history((int)history_num);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server Error: History number set failed: %d", retval);
-               retval = send_generic_response(sockfd,
-                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
-                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-               if(retval != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-               }
-       }
-       SEC_SVR_DBG("Server History has been set to %d", history_num);
-       retval = send_generic_response(sockfd,
-                       SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-       }
-error:
-       return retval;
-}
-
-
-int process_set_pwd_max_challenge_request(int sockfd)
-{
-    unsigned int max_challenge, current_challenge, current_validity;
-    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-    int retval;
-
-    // TODO here we should probably check if the peer has rights to change
-    // this value (max challenge) for current password
-
-    retval = read(sockfd, &max_challenge, sizeof(unsigned int));
-    if(retval < sizeof(unsigned int))
-    {
-        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    SEC_SVR_DBG("Server max challenge request: %d", max_challenge);
-
-    // Getting currently set password
-    retval = load_password(cur_pwd, &current_challenge, &current_validity);
-    /* If we cannot load password file */
-    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
-    {
-        SEC_SVR_DBG("%s", "Server: can't read current password");
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-    else if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("%s", "Server: can't read current password");
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    // Set 'new' password file with old password and new max challenge
-    retval = set_password(cur_pwd, max_challenge, time(NULL) + current_validity);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_SUCCESS);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-    }
-    retval = reset_attempt();
-error:
-    return retval;
-}
-
-int process_set_pwd_validity_request(int sockfd)
-{
-    unsigned int current_challenge, current_validity, validity;
-    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
-    int retval;
-
-    // TODO here we should probably check if the peer has rights to change
-    // this value (validity) for current password
-
-    retval = read(sockfd, &validity, sizeof(unsigned int));
-    if(retval < sizeof(unsigned int))
-    {
-        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    SEC_SVR_DBG("Server validity request: %d", validity);
-
-    // Calculating validity in seconds
-    if(validity == 0)
-        validity = 0;
-    else
-        validity = time(NULL) + (validity * 86400);
-
-    // Getting currently set password
-    retval = load_password(cur_pwd, &current_challenge, &current_validity);
-    /* If we cannot load password file */
-    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
-    {
-        SEC_SVR_DBG("%s", "Server: can't read current password");
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-    else if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("%s", "Server: can't read current password");
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    // Set 'new' password file with old password and new validity
-    retval = set_password(cur_pwd, current_challenge, validity);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
-        retval = send_generic_response(sockfd,
-                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
-                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-        if(retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_SUCCESS);
-    if(retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
-    }
-    retval = reset_attempt();
-error:
-    return retval;
-}
diff --git a/src/security-srv/util/security-server-util-common.c b/src/security-srv/util/security-server-util-common.c
deleted file mode 100644 (file)
index e28786a..0000000
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-
-#include <poll.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <errno.h>
-#include <unistd.h>
-
-#include "security-server-common.h"
-#include "security-server-cookie.h"
-#include "security-server-comm.h"
-#include "security-server-util.h"
-#include "security-server.h"
-
-
-/* Get all cookie info response *
- * packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x52 |       Message Length          |
- * |---------------------------------------------------------------|
- * |  return code  |             tot # of cooks (32bit)            |
- * |---------------------------------------------------------------|
- * |   cont'd...   |            1st cmdline_len (32bit)            |
- * |---------------------------------------------------------------|
- * |   cont'd...   |           1st permission_len (32bit)          |
- * ----------------------------------------------------------------|
- * |   cont'd...   |                                               |
- * |----------------                                               |
- * |                         1st cookie                            |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                         1st PID (32bit)                       |
- * |---------------------------------------------------------------|
- * |                     1st cmdline (string)                      |
- * |---------------------------------------------------------------|
- * |                           1st perm_1                          |
- * |---------------------------------------------------------------|
- * |                           1st perm_2                          |
- * |---------------------------------------------------------------|
- * |                              ...                              |
- * |---------------------------------------------------------------|
- * |                      2nd cmdline_len  (32bit)                 |
- * |---------------------------------------------------------------|
- * |                     2nd permission_len (32bit)                |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                        2nd cookie                             |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                         2nd PID (32 bit)                      |
- * |---------------------------------------------------------------|
- * |                     2nd cmdline (string)                      |
- * |---------------------------------------------------------------|
- * |                           2st perm_1                          |
- * |---------------------------------------------------------------|
- * |                           2st perm_2                          |
- * |---------------------------------------------------------------|
- * |                              ...                              |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                             ...                               |
- * |                                                               |
- * |                                                               |
- */
- unsigned char * get_all_cookie_info(cookie_list *list, int *size)
-{
-       cookie_list *current = list;
-       int ptr, total_num, total_size, tempnum, i;
-       unsigned char *buf = NULL, *tempptr = NULL;
-       response_header hdr;
-
-       total_size = sizeof(hdr) + sizeof(int);
-
-       buf = malloc(total_size); /* header size */
-       ptr = sizeof(hdr) + sizeof(int);
-       total_num = 0;  /* Total # of cookies initial value */
-
-       while(current != NULL)
-       {
-               current = garbage_collection(current);
-               if(current == NULL)
-                       break;
-
-               total_num++;
-               total_size += sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + current->path_len + (current->permission_len * sizeof(int));
-               tempptr = realloc(buf, total_size);
-               if(tempptr == NULL)
-               {
-                       SEC_SVR_DBG("%s", "Out of memory");
-                       return NULL;
-               }
-               buf = tempptr;
-
-               tempnum = current->path_len;
-               memcpy(buf+ptr, &tempnum, sizeof(int));
-               ptr += sizeof(int);
-               tempnum = current->permission_len;
-               memcpy(buf+ptr, &tempnum, sizeof(int));
-               ptr += sizeof(int);
-               memcpy(buf+ptr, current->cookie, SECURITY_SERVER_COOKIE_LEN);
-               ptr += SECURITY_SERVER_COOKIE_LEN;
-               tempnum = current->pid;
-               memcpy(buf+ptr, &tempnum, sizeof(int));
-               ptr += sizeof(int);
-               memcpy(buf+ptr, current->path, current->path_len);
-               ptr += current->path_len;
-
-               for(i=0;i<current->permission_len;i++)
-               {
-                       tempnum = current->permissions[i];
-                       memcpy(buf+ptr, &tempnum, sizeof(int));
-                       ptr += sizeof(int);
-               }
-               current = current->next;
-       }
-
-       if(total_size > 65530)
-       {
-               SEC_SVR_DBG("Packet too big. message length overflow: %d", total_size);
-               free(buf);
-               return  NULL;
-       }
-
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE;
-       hdr.basic_hdr.msg_len =(unsigned short)( total_size - sizeof(hdr));
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-       memcpy(buf, &hdr, sizeof(hdr));
-       tempnum = total_num;
-       memcpy(buf + sizeof(hdr), &tempnum, sizeof(int));
-       *size = total_size;
-       return buf;
-}
-
-int send_all_cookie_info(const unsigned char *buf, int size, int sockfd)
-{
-       int ret;
-       /* Check poll */
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to client */
-       ret = write(sockfd, buf, size);
-
-       if(ret < size)
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Get one cookie info response *
- * packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x54 |       Message Length          |
- * |---------------------------------------------------------------|
- * |  return code  |              cmdline_len (32bit)t)            |
- * |---------------------------------------------------------------|
- * |   cont'd...   |              permission_len (32bit)           |
- * ----------------------------------------------------------------|
- * |   cont'd...   |                                               |
- * |----------------                                               |
- * |                             cookie                            |
- * |                                                               |
- * |---------------------------------------------------------------|
- * |                           PID (32bit)                         |
- * |---------------------------------------------------------------|
- * |                         cmdline (string)                      |
- * |---------------------------------------------------------------|
- * |                             perm_1                            |
- * |---------------------------------------------------------------|
- * |                             perm_2                            |
- * |---------------------------------------------------------------|
- * |                              ...                              |
- * |---------------------------------------------------------------|
-*/
-int send_one_cookie_info(const cookie_list *list, int sockfd)
-{
-       unsigned char *buf = NULL;
-       response_header hdr;
-       int total_size, ptr = 0, tempnum, ret, i;
-
-       total_size = sizeof(hdr) + sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
-       buf = malloc(total_size);
-       if(buf == NULL)
-       {
-               SEC_SVR_DBG("%s", "Out of memory");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE;
-       hdr.basic_hdr.msg_len =sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
-       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-       memcpy(buf, &hdr, sizeof(hdr));
-       ptr += sizeof(hdr);
-
-       tempnum = list->path_len;
-       memcpy(buf+ptr, &tempnum, sizeof(int));
-       ptr += sizeof(int);
-       tempnum = list->permission_len;
-       memcpy(buf+ptr, &tempnum, sizeof(int));
-       ptr += sizeof(int);
-       memcpy(buf+ptr, list->cookie, SECURITY_SERVER_COOKIE_LEN);
-       ptr += SECURITY_SERVER_COOKIE_LEN;
-       tempnum = list->pid;
-       memcpy(buf+ptr, &tempnum, sizeof(int));
-       ptr += sizeof(int);
-       memcpy(buf+ptr, list->path, list->path_len);
-       ptr += list->path_len;
-
-       for(i=0;i<list->permission_len;i++)
-       {
-               tempnum = list->permissions[i];
-               memcpy(buf+ptr, &tempnum, sizeof(int));
-               ptr += sizeof(int);
-       }
-
-       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(ret == SECURITY_SERVER_ERROR_POLL)
-       {
-               SEC_SVR_DBG("%s", "poll() error");
-               free(buf);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               SEC_SVR_DBG("%s", "poll() timeout");
-               free(buf);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to client */
-       ret = write(sockfd, buf, total_size);
-       free(buf);
-       if(ret < total_size)
-           return SECURITY_SERVER_ERROR_SEND_FAILED;
-       return SECURITY_SERVER_SUCCESS;
-}
-
-int util_process_all_cookie(int sockfd, cookie_list* list)
-{
-       unsigned char *buf = NULL;
-       int ret;
-       buf = get_all_cookie_info(list, &ret);
-       if(buf == NULL)
-       {
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       ret = send_all_cookie_info(buf, ret, sockfd);
-
-       if(buf != NULL)
-               free(buf);
-       return ret;
-}
-int util_process_cookie_from_pid(int sockfd, cookie_list* list)
-{
-       int pid, ret;
-       cookie_list *result = NULL;
-
-       ret = read(sockfd, &pid, sizeof(int));
-       if(ret < sizeof(int))
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       if(pid == 0)
-       {
-               SEC_SVR_DBG("%s", "ERROR: Default cookie is not allowed to be retrieved");
-               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-               if(ret != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
-               }
-       }
-       result = search_cookie_from_pid(list, pid);
-       if(result == NULL)
-       {
-               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
-               if(ret != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
-               }
-       }
-       else
-       {
-               ret = send_one_cookie_info(result, sockfd);
-               if(ret != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
-               }
-       }
-       
-       return ret;
-}
-
-int util_process_cookie_from_cookie(int sockfd, cookie_list* list)
-{
-       unsigned char cookie[SECURITY_SERVER_COOKIE_LEN];
-       int ret;
-       cookie_list *result = NULL;
-
-       ret = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(ret < SECURITY_SERVER_COOKIE_LEN)
-       {
-               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       result = search_cookie(list, cookie, 0);
-       if(result == NULL)
-       {
-               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
-                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
-               if(ret != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
-               }
-       }
-       else
-       {
-               ret = send_one_cookie_info(result, sockfd);
-               if(ret != SECURITY_SERVER_SUCCESS)
-               {
-                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
-               }
-       }
-       
-       return ret;
-}
diff --git a/src/security-srv/util/security-server-util.c b/src/security-srv/util/security-server-util.c
deleted file mode 100644 (file)
index 9e6e516..0000000
+++ /dev/null
@@ -1,773 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- *
- */
-
-#include <poll.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <errno.h>
-#include <unistd.h>
-
-#include "security-server.h"
-#include "security-server-common.h"
-#include "security-server-util.h"
-#include "security-server-comm.h"
-
-#define TOTAL_PATH_MAX 256
-
-#define mszBase64Table  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
-#define BASE64_PAD      '='
-
-
-
- void printusage(char *cmdline)
-{
-       printf("%s\n", "Usage: ");
-       printf("%s [Options]\n", cmdline);
-       printf("%s\n", "[Options]");
-       printf("%s\n", "-a:\tList all active cookies ");
-       printf("%s\n", "-f [filename]:\tList a specific cookie information from file");
-       printf("%s\n", "\tThe file must contain binary form of cookie");
-       printf("%s\n", "-p [pid]:\tList a specific cookie information for a process by PID");
-       printf("%s\n", "-s [base64 encoded cookie]:\tList a specific cookie information for a process by given base64 encoded cookie value");
-       printf("%s\n", "Example:");
-       printf("%s -a\n", cmdline);
-       printf("%s -f /tmp/mycookie.bin\n", cmdline);
-       printf("%s -p 2115\n", cmdline);
-       printf("%s -s asC34fddaxd6NDVDA43GFD345TfCADF==\n", cmdline);
-}
-
-void printstr(const unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               printf("%c", data[i]);
-       }
-       printf("\n");
-}
-
-void printperm(const unsigned char *data, int num)
-{
-       int i, ptr, tempnum;
-       for(i=0, ptr=0;i<num;i++)
-       {
-               memcpy(&tempnum, data+ptr, sizeof(int));
-               printf("%d, ", tempnum);
-               ptr+= sizeof(int);
-               if(i % 6 == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-/* Send all cookie information request packet to security server *
- * 
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x51 |       Message Length = 0      |
- * |---------------------------------------------------------------|
- */
-int send_all_cookie_info_request(int sockfd)
-{
-
-       basic_header hdr;
-       int retval;
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST;
-       hdr.msg_len = 0;
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               printf("Error: %s\n", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               printf("Error: %s\n", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sockfd, &hdr, sizeof(hdr));
-       if(retval < sizeof(hdr))
-       {
-               /* Write error */
-               printf("Error on write(): %d\n", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS; 
-}
-
-int recv_all_cookie_info(int sockfd)
-{
-       int retval, total_cookie, ptr = 0, i, cmdline_len, perm_len, recved_pid;
-       response_header hdr;
-       unsigned char *buf = NULL;
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               printf("Error: %s\n", "poll() error");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               printf("Error: %s\n", "poll() timeout");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       /* Receive response */
-       retval = read(sockfd, &hdr, sizeof(response_header));
-       if(retval < sizeof(hdr) )
-       {
-               /* Error on socket */
-               printf("Error: Receive failed %d\n", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
-       {
-               printf("Error: response error: %d\n", hdr.return_code);
-               return return_code_to_error_code(hdr.return_code);
-       }
-
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE)
-       {
-               printf("Error: response error: different msg type %d\n", hdr.basic_hdr.msg_id );
-               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-       }
-
-       buf = malloc(hdr.basic_hdr.msg_len);
-       if(buf == NULL)
-       {
-               printf("Error: Out of memory\n");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
-       if(retval < hdr.basic_hdr.msg_len)
-       {
-               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
-               printhex(buf, retval);
-               if(buf != NULL)
-                       free(buf);
-               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-       }
-
-       memcpy(&total_cookie, buf, sizeof(int));
-       if(total_cookie == 0)
-       {
-               printf("There is no cookie available\n");
-               if(buf != NULL)
-                       free(buf);
-               return SECURITY_SERVER_SUCCESS;
-       }
-       ptr = sizeof(int);
-       printf("--------------------------------\n");
-       for(i=0;i<total_cookie;i++)
-       {
-               printf("%dth cookie:\n", i+1);
-               memcpy(&cmdline_len, buf+ptr, sizeof(int));
-               ptr += sizeof(int);
-               memcpy(&perm_len, buf+ptr, sizeof(int));
-               ptr+= sizeof(int);
-
-               printf("%s\n", "Cookie:");
-               printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
-               ptr += SECURITY_SERVER_COOKIE_LEN;
-               memcpy(&recved_pid, buf+ptr, sizeof(int));
-               ptr+= sizeof(int);
-               if(recved_pid == 0)
-               {
-                       printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
-                       printf("%s\n", "cmdline: N/A");
-                       printf("%s\n", "Permissions (gids): N/A");
-               }
-               else
-               {
-                       printf("PID: %d\n", recved_pid);
-
-                       printf("%s\n", "cmdline:");
-                       printstr(buf + ptr, cmdline_len);
-                       ptr += cmdline_len;
-
-                       printf("%s\n", "Permissions (gids):");
-                       printperm(buf + ptr, perm_len);
-                       ptr += (perm_len * sizeof(int));
-               }
-               printf("--------------------------------\n");
-       }
-       if(buf != NULL)
-               free(buf);
-       return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send cookie information request from cookie packet to security server *
- * 
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x55 |       Message Length = 20     |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                         cookie                                |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_cookie_info_request_from_cookie(int sockfd, const unsigned char *cookie)
-{
-
-       basic_header hdr;
-       int retval;
-       int size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN;
-       unsigned char buf[size];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST;
-       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               printf("Error: %s\n", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               printf("Error: %s\n", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sockfd, buf, size);
-       if(retval < size)
-       {
-               /* Write error */
-               printf("Error on write(): %d\n", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS; 
-}
-
-/* Send cookie information request from pid packet to security server *
- * 
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x53 |       Message Length = 20     |
- * |---------------------------------------------------------------|
- * |                            pid                                |
- * |---------------------------------------------------------------|
- */
-int send_cookie_info_request_from_pid(int sockfd, int pid)
-{
-       basic_header hdr;
-       int retval;
-       int size = sizeof(hdr) + sizeof(int);
-       unsigned char buf[size];
-
-       /* Assemble header */
-       hdr.version = SECURITY_SERVER_MSG_VERSION;
-       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST;
-       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf+sizeof(hdr), &pid, sizeof(int));
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               printf("Error: %s\n", "poll() error");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               printf("Error: %s\n", "poll() timeout");
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-
-       /* Send to server */
-       retval = write(sockfd, buf, size);
-       if(retval < size)
-       {
-               /* Write error */
-               printf("Error on write(): %d\n", retval);
-               return SECURITY_SERVER_ERROR_SEND_FAILED;
-       }
-       return SECURITY_SERVER_SUCCESS; 
-}
-
-int recv_cookie_info_response(sockfd)
-{
-       unsigned char *buf = NULL;
-       int retval, cmdline_len, perm_len, recved_pid, ptr = 0;
-       response_header hdr;
-
-       /* Check poll */
-       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-       if(retval == SECURITY_SERVER_ERROR_POLL)
-       {
-               printf("Error: %s\n", "poll() error");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
-       {
-               printf("Error: %s\n", "poll() timeout");
-               return SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       /* Receive response */
-       retval = read(sockfd, &hdr, sizeof(response_header));
-       if(retval < sizeof(hdr) )
-       {
-               /* Error on socket */
-               printf("Error: Receive failed %d\n", retval);
-               return  SECURITY_SERVER_ERROR_RECV_FAILED;
-       }
-
-       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
-       {
-               printf("Error: response error: %d\n", hdr.return_code);
-               return return_code_to_error_code(hdr.return_code);
-       }
-
-       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE)
-       {
-               printf("Error: response error: different msg type %d\n" ,hdr.basic_hdr.msg_id);
-               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-       }
-
-       buf = malloc(hdr.basic_hdr.msg_len);
-       if(buf == NULL)
-       {
-               printf("Error: Out of memory\n");
-               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-       }
-
-       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
-       if(retval < hdr.basic_hdr.msg_len)
-       {
-               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
-               printhex(buf, retval);
-               if(buf != NULL)
-                       free(buf);
-               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-       }
-
-       memcpy(&cmdline_len, buf+ptr, sizeof(int));
-       ptr += sizeof(int);
-       memcpy(&perm_len, buf+ptr, sizeof(int));
-       ptr+= sizeof(int);
-
-       printf("%s\n", "Cookie:");
-       printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
-       ptr += SECURITY_SERVER_COOKIE_LEN;
-       memcpy(&recved_pid, buf+ptr, sizeof(int));
-       ptr+= sizeof(int);
-       if(recved_pid == 0)
-       {
-               printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
-               printf("%s\n", "cmdline: N/A");
-               printf("%s\n", "Permissions (gids): N/A");
-       }
-       else
-       {
-               printf("PID: %d\n", recved_pid);
-
-               printf("%s\n", "cmdline:");
-               printstr(buf + ptr, cmdline_len);
-               ptr += cmdline_len;
-
-               printf("%s\n", "Permissions (gids):");
-               printperm(buf + ptr, perm_len);
-       }
-
-       free(buf);
-
-       return SECURITY_SERVER_SUCCESS;
-}
-
-void util_send_all_cookie_info_request(void)
-{
-       int sockfd = -1, retval;
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               printf("Error: %s\n", "connection failed");
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_all_cookie_info_request(sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Error: send request failed: %d", retval);
-               goto error;
-       }
-       retval = recv_all_cookie_info(sockfd);
-       if(retval <0)
-       {
-               printf("Error: Error receiving cookie list: %d\n", retval);
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-       {
-               close(sockfd);
-       }
-       return;
-}
-
-void util_read_cookie_from_bin_file(unsigned char *cookie, const char *path)
-{
-       char total_path[TOTAL_PATH_MAX] = {0, };
-       FILE *fp = NULL;
-       int ret;
-
-       if(path[0] == '/' || (path[0] == '.' && path[1] == '/'))
-       {
-               /* Using absolute path */
-               strncpy(total_path, path, TOTAL_PATH_MAX);
-       }
-       else
-       {
-               if (getcwd(total_path, TOTAL_PATH_MAX) == NULL)
-               {
-                       printf("Cannot open cookie file\n");
-                       exit(1);
-               }
-               snprintf(total_path, TOTAL_PATH_MAX, "%s/%s", total_path, path);
-       }
-
-       fp = fopen(total_path, "rb");
-       if(fp == NULL)
-       {
-               printf("Cannot open cookie file\n");
-               exit(1);
-       }
-
-       ret = fread(cookie, 1, SECURITY_SERVER_COOKIE_LEN, fp);
-       if(ret < SECURITY_SERVER_COOKIE_LEN)
-       {
-               printf("Cannot read cookie file: %d\n", ret);
-               fclose(fp);
-               exit(1);
-       }
-
-       fclose(fp);
-       return;
-}
-
-void util_send_cookie_info_request_from_cookie(unsigned char *cookie)
-{
-       int sockfd = -1, retval;
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               printf("Error: %s\n", "connection failed");
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_cookie_info_request_from_cookie(sockfd, cookie);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Error: send request failed: %d", retval);
-               goto error;
-       }
-       retval = recv_cookie_info_response(sockfd);
-       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
-       {
-               printf("There is no such cookie available\n");
-               goto error;
-       }
-       if(retval <0)
-       {
-               printf("Error: Error receiving cookie info: %d\n", retval);
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-       {
-               close(sockfd);
-       }
-       return;
-}
-
-unsigned char* util_base64_decode(unsigned char* input, long inputLength, long* outputLength)
-{
-       unsigned char* pCurIn = input;
-       unsigned char* pCurOut;
-       long iOutCharNum = 0;
-       long lInputLength = inputLength;
-       char buf[4];
-       unsigned char* inCode;
-       unsigned char* output;
-       (*outputLength) = 0;
-       if((input == NULL) || (inputLength <= 0))
-       return NULL;
-
-        /* calculate length of output data */
-       for(; lInputLength > 0; lInputLength--)
-       {
-               if ((*pCurIn) == BASE64_PAD)
-               {
-                       (*outputLength) += ((iOutCharNum + 1) >> 1);
-                       if ((iOutCharNum == 2) &&
-                       ((lInputLength == 1) ||
-                       (*(pCurIn + 1) != BASE64_PAD)))
-                       {
-                               (*outputLength)++;
-                       }
-                       iOutCharNum = 0;
-                       break;
-               }
-               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
-               if (!inCode)
-                       continue;
-               iOutCharNum++;
-               if (iOutCharNum == 4)
-               {
-                       (*outputLength) += 3;
-                       iOutCharNum=0;
-               }
-       }
-       (*outputLength) += ((iOutCharNum + 1)/2);
-
-       /* allocate memory for output data*/
-       output = malloc( *outputLength + 1 );
-       if(NULL == output)
-       {
-               return NULL;
-       }
-       memset( output, 0, (*outputLength + 1) );
-       pCurOut = output;
-       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
-
-       /* decode data*/
-       pCurIn = input;
-
-       for(; inputLength>0; inputLength--)
-       {
-               if ((*pCurIn) == BASE64_PAD)
-               {
-                       /*end-padding processing*/
-                       if (iOutCharNum == 0)
-                       {
-                               return output;
-                       }
-                       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
-                       if ((iOutCharNum == 3)||((iOutCharNum == 2) && ((lInputLength == 0) ||
-                       ((*(pCurIn + 1)) != BASE64_PAD))))
-                       {
-                               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
-                       }
-                       return output;
-               }
-               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
-               if (!inCode)
-               {
-                       continue;
-               }
-               buf[iOutCharNum++] = (char)((unsigned long)inCode - (unsigned long)mszBase64Table);
-               if (iOutCharNum == 4)
-               {
-                       *(pCurOut++) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
-                       *(pCurOut++) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
-                       *(pCurOut++) = ((buf[2] & 0x03) << 6) + (buf[3] & 0x3F);
-                       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
-               }
-       }
-       if (iOutCharNum == 0)
-       {
-               return output;
-       }
-       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
-       if (iOutCharNum == 3)
-       {
-               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
-       }
-       return output;
-}
-
-void util_read_cookie_from_base64_string(unsigned char *cookie, const char *encoded_cookie)
-{
-       unsigned char *decoded_cookie = NULL;
-       int encoded_len, decoded_len;
-       encoded_len = strlen(encoded_cookie);
-
-       decoded_cookie = util_base64_decode((unsigned char *)encoded_cookie, encoded_len, (long *)&decoded_len);
-       if(decoded_len != SECURITY_SERVER_COOKIE_LEN)
-       {
-               printf("Base64 decode failed: %d\n", decoded_len);
-               exit(1);
-       }
-
-       if(decoded_cookie == NULL)
-       {
-               printf("%s", "BASE64 decode failed:\n");
-               exit(1);
-       }
-
-       memcpy(cookie, decoded_cookie, SECURITY_SERVER_COOKIE_LEN);
-       if(decoded_cookie != NULL)
-               free(decoded_cookie);
-
-       return;
-}
-
-void util_send_cookie_info_request_from_pid(const char *str_pid)
-{
-       int retval, sockfd, pid;
-
-       if(str_pid == NULL)
-       {
-               printf("Wrong PID\n");
-               return;
-       }
-
-       errno = 0;
-       pid = strtoul(str_pid, 0, 10);
-       if (errno != 0)
-       {
-               SEC_SVR_DBG("cannot change string to integer [%s]", str_pid);
-               return;
-       }
-
-       retval = connect_to_server(&sockfd);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               printf("Error: %s\n", "connection failed");
-               goto error;
-       }
-
-       /* make request packet */
-       retval = send_cookie_info_request_from_pid(sockfd, pid);
-       if(retval != SECURITY_SERVER_SUCCESS)
-       {
-               /* Error on socket */
-               SEC_SVR_DBG("Error: send request failed: %d", retval);
-               goto error;
-       }
-       retval = recv_cookie_info_response(sockfd);
-       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
-       {
-               printf("There is no such cookie available\n");
-               goto error;
-       }
-       if(retval <0)
-       {
-               printf("Error: Error receiving cookie info: %d\n", retval);
-               goto error;
-       }
-
-error:
-       if(sockfd > 0)
-       {
-               close(sockfd);
-       }
-       return;
-}
-
-int main(int argc, char *argv[])
-{
-       int ret;
-       unsigned char cookie[20];
-       ret = getuid();
-       if(ret != 0)
-       {
-               printf("You must be root to test. Current UID: %d\nExiting...\n", ret);
-               exit(1);
-       }
-       if(argc < 2 || argc > 4)
-       {
-               printf("Wrong usage: %d\n", argc);
-               printusage(argv[0]);
-               exit(1);
-       }
-       if(strcmp(argv[1], "-a") == 0)
-       {
-               if(argc != 2)
-               {
-                       printf("Wrong usage: %d\n", argc);
-                       printusage(argv[0]);
-                       exit(1);
-               }
-                       
-               util_send_all_cookie_info_request();
-               exit(0);
-       }
-
-       if(argc < 3)
-       {
-               printf("Wrong usage: %d\n", argc);
-               printusage(argv[0]);
-               exit(1);
-       }
-
-       if(strcmp(argv[1], "-f") == 0)
-       {
-               util_read_cookie_from_bin_file(cookie, argv[2]);
-               util_send_cookie_info_request_from_cookie(cookie);
-               exit(0);
-       }
-
-       if(strcmp(argv[1], "-p") == 0)
-       {
-               util_send_cookie_info_request_from_pid(argv[2]);
-               exit(0);
-       }
-
-       if(strcmp(argv[1], "-s") == 0)
-       {
-               util_read_cookie_from_base64_string(cookie, argv[2]);
-               util_send_cookie_info_request_from_cookie(cookie);
-               exit(0);
-       }
-
-       printf("%s", "Wrong usage\n");
-       printusage(argv[0]);
-       exit(1);
-}
diff --git a/src/server/security-server-cookie.c b/src/server/security-server-cookie.c
new file mode 100644 (file)
index 0000000..a084a11
--- /dev/null
@@ -0,0 +1,606 @@
+/*
+ *  security-server
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/smack.h>
+
+#include "security-server-cookie.h"
+
+/* Delete useless cookie item *
+ * then connect prev and next */
+int free_cookie_item(cookie_list *cookie)
+{
+       if(cookie->path != NULL)
+               free(cookie->path);
+       if(cookie->permissions != NULL)
+               free(cookie->permissions);
+        if(cookie->smack_label != NULL)
+                free(cookie->smack_label);
+       if(cookie->prev != NULL)
+               cookie->prev->next = cookie->next;
+       if(cookie->next != NULL)
+               cookie->next->prev = cookie->prev;
+       free(cookie);
+       cookie = NULL;
+       return 0;
+}
+
+/* Cut the link of the current cookie item and connect previous link and next line *
+ * That is remove a cookie item *
+ * Returns next cookie item  if exist, NULL for no more cookie item */
+cookie_list *delete_cookie_item(cookie_list *cookie)
+{
+       cookie_list *retval = NULL;
+       if(cookie == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot delete null cookie");
+               return retval;
+       }
+
+       /* Reconnect cookie item */
+       if(cookie->next != NULL)
+       {
+               cookie->prev->next = cookie->next;
+               cookie->next->prev = cookie->prev;
+               retval = cookie->next;
+       }
+       else
+       {
+               cookie->prev->next = NULL;
+       }
+       
+       free_cookie_item(cookie);
+       return retval;
+}
+
+cookie_list * garbage_collection(cookie_list *cookie)
+{
+       char path[17];
+       cookie_list *retval = NULL;
+       struct stat statbuf;
+       int ret;
+
+       while(cookie != NULL)
+       {
+               /* Skip default cookie */
+               if(cookie->pid ==0)
+                       return cookie;
+
+               /* Try to find the PID directory from proc fs */
+               snprintf(path, sizeof(path), "/proc/%d", cookie->pid);
+               path[16] = 0;
+               ret = stat(path, &statbuf);
+               if(ret != 0)
+               {
+                       /* If it's not exist, delete the cookie */
+                       if(errno == ENOENT)
+                       {
+                               SEC_SVR_DBG("Garbage found. PID:%d, deleting...", cookie->pid);
+                               cookie = delete_cookie_item(cookie);
+                               continue;
+                       }
+                       else
+                       {
+                               /* Some error occurred */
+                               SEC_SVR_DBG("Error occurred on stat: errno = %d", errno);
+                               return cookie;
+                       }
+               }
+               else
+               {
+                       /* This is not a garbage. returning */
+                       return cookie;
+               }
+       }
+       return retval;
+}
+
+/* Search existing cookie from the cookie list for the client process *
+ * At the same time, it collects garbage cookie which PID is no longer exist and delete them */
+cookie_list *search_existing_cookie(int pid, const cookie_list *c_list)
+{
+       cookie_list *current =(cookie_list *)c_list, *cookie = NULL;
+       char *cmdline = NULL, *debug_cmdline = NULL;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               /* PID must be same */
+               if(current->pid == pid)
+               {
+                       /* Found cookie for the pid. Check the cookie is reused by dirrent executable */
+                       /* Check the path of the process */
+                       cmdline = (char*)read_cmdline_from_proc(pid);
+                       if(cmdline == NULL)
+                       {
+                               SEC_SVR_DBG("%s", "cannot read cmdline");
+                               return NULL;
+                       }
+                       /* Check the path is different */
+                       if(strncmp(cmdline, current->path, current->path_len) != 0 || strlen(cmdline) != current->path_len)
+                       {
+                               SEC_SVR_DBG("pid [%d] has been reused by %s. deleting the old cookie.", pid, cmdline);
+                               debug_cmdline = malloc(current->path_len + 1);
+                               if(debug_cmdline == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "out of memory error");
+                                       free(cmdline);
+                                       return NULL;
+                               }
+                               strncpy(debug_cmdline, current->path, current->path_len);
+                               debug_cmdline[current->path_len] = 0;
+                               SEC_SVR_DBG("[%s] --> [%s]", cmdline, debug_cmdline);
+                               if(debug_cmdline != NULL)
+                               {
+                                       free(debug_cmdline);
+                                       debug_cmdline = NULL;
+                               }
+                               /* Okay. delete current cookie */
+                               current = delete_cookie_item(current);
+                               if(cmdline != NULL)
+                               {
+                                       free(cmdline);
+                                       cmdline = NULL;
+                               }
+                               continue;
+                       }
+                       else
+                       {
+                               SEC_SVR_DBG("%s", "cookie found");
+                               cookie = current;
+                       }
+
+                       if(cmdline != NULL)
+                       {
+                               free(cmdline);
+                               cmdline = NULL;
+                       }
+               }
+               current = current->next;
+       }
+       return cookie;
+}
+
+/* Search existing cookie from the cookie list for matching pid *
+ * Default cookie (meaning PID 0) is not allowed in here */
+cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               if(current->pid == pid)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+                       retval = current;
+                       goto finish;
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+/* Search existing cookie from the cookie list for matching cookie and privilege */
+/* If privilege is 0, just search cookie exists or not */
+cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+       int i;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+        //searching for cookie
+               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+
+            //check if this cookie belongs to root process
+            if(current->is_roots_process == 1)
+            {
+                SEC_SVR_DBG("%s", "Root process cookie, special privileges");
+                //we can skip privilege checking
+                retval = current;
+                goto finish;
+            }
+
+                       for(i=0 ; i < current->permission_len ; i++)
+                       {
+                               if(privilege == current->permissions[i])
+                               {
+                                       SEC_SVR_DBG("Found privilege %d", privilege);
+                                       retval = current;
+                                       goto finish;
+                               }
+                       }
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+
+cookie_list *search_cookie_new(const cookie_list *c_list,
+                               const unsigned char *cookie,
+                               const char *object,
+                               const char *access_rights)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+        int ret;
+       int i;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+
+                                ret = smack_have_access(current->smack_label, object, access_rights);
+          SEC_SVR_DBG("smack_have_access, subject >%s< object >%s< access >%s< ===> %d",
+                    current->smack_label, object, access_rights, ret);
+                                if (ret == 1)
+                                {
+                                        retval = current;
+                                        goto finish;
+                                }
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+
+/* Generage a random stream value of size to cookie *
+ * by reading /dev/uranddom file */
+int generate_random_cookie(unsigned char *cookie, int size)
+{
+       int fd, ret;
+
+    if (cookie == NULL) {
+        SEC_SVR_DBG("%s", "Null pointer passed to function");
+        return SECURITY_SERVER_ERROR_UNKNOWN;
+    }
+       fd = open("/dev/urandom", O_RDONLY);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("%s", "Cannot open /dev/urandom");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       ret = read(fd, cookie, size);
+       if(ret < size)
+       {
+               SEC_SVR_DBG("Cannot read /dev/urandom: %d", ret);
+               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               goto error;
+       }
+       ret = SECURITY_SERVER_SUCCESS;
+error:
+       if(fd >= 0)
+               close(fd);
+       return ret;
+}
+
+/* Create a cookie item from PID */
+cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list)
+{
+       int ret, tempint;
+       cookie_list *added = NULL, *current = NULL;
+       char path[24], *cmdline = NULL;
+       char *buf = NULL, inputed, *tempptr = NULL;
+       char delim[] = ": ", *token = NULL;
+       int *permissions = NULL, perm_num = 1, cnt, i, *tempperm = NULL;
+        char *smack_label = NULL;
+       FILE *fp = NULL;
+
+       current = search_existing_cookie(pid, c_list);
+       if(current != NULL)
+       {
+               /* There is a cookie for this process already */
+               added = current;
+               SEC_SVR_DBG("%s", "Existing cookie found");
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = (char *)read_cmdline_from_proc(pid);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("Error on reading /proc/%d/cmdline", pid);
+               goto error;
+       }
+
+       /*
+        * modified by security part
+        *  - get gid from /etc/group
+        */
+       /* Read group info of the PID from proc fs - /proc/[PID]/status */
+       snprintf(path, sizeof(path), "/proc/%d/status", pid);
+       fp = fopen(path, "r");
+
+       /* Find the line which starts with 'Groups:' */
+       i = 0;
+       
+       while(1)
+       {
+               buf = (char*)malloc(sizeof(char) * 128);
+               if(buf == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Error on malloc()");
+                       goto error;
+               }
+               memset(buf, 0x00, 128);
+               cnt = 128;
+
+               /* get one line from /proc/[PID]/status */
+               while(1)
+               {
+                       tempint = fgetc(fp);
+                       inputed = (char)tempint;
+                       if(tempint == EOF)
+                               goto out_of_while;
+                       else if(inputed == '\n')
+                       {
+                               buf[i] = '\0';
+                               break;
+                       }
+                       else if((i == cnt) && (inputed != '\n'))
+                       {
+                               tempptr = (char*)realloc(buf, sizeof(char) * (i + 128));
+                               if(tempptr == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "Error on realloc()");
+                                       goto error;
+                               }
+                               buf = tempptr;
+                               buf[i++] = inputed;
+                               cnt = i + 128;
+                       }
+                       else
+                               buf[i++] = inputed;
+               }
+               i = 0;
+
+               /* find 'Groups:' */
+               if(strncmp(buf, "Groups:", 7) == 0)
+               {
+                       /* get gid from the line and insert to 'permissions' array */
+                       token = strtok(buf, delim); // first string is "Groups"
+                       while((token = strtok(NULL, delim)))
+                       {
+                               tempperm = realloc(permissions, sizeof(int) * perm_num);
+                               if(tempperm == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "Error on realloc()");
+                                       goto error;
+                               }
+                               permissions = tempperm;
+                               errno = 0;
+                               permissions[perm_num - 1] = strtoul(token, 0, 10);
+                               if (errno != 0)
+                               {
+                                       SEC_SVR_DBG("cannot change string to integer [%s]", token);
+                                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                                       goto error;
+                               }
+                               perm_num++;
+                       }
+                       perm_num--;
+
+                       /* goto out of while loop */
+                       break;
+               }
+               if(buf != NULL)
+               {
+                       free(buf);
+                       buf = NULL;
+               }
+       }
+out_of_while:
+               
+       /* Each group ID is stored in each line of the file */
+//     while(fgets(permline, sizeof(permline), fp) != NULL)
+//     {
+//             permissions = realloc(permissions, sizeof(int) * perm_num);
+//             if(permissions == NULL)
+//             {
+//                     SEC_SVR_DBG("%s", "Error on realloc()");
+//                     goto error;
+//             }
+//             permissions[perm_num -1] = strtoul(permline, 0, 10);
+//             perm_num++;
+//     }
+//     perm_num--;
+       /*
+        * modifying end
+        */
+
+       /* Go to last cookie from the list */
+       current = c_list;
+       while(current->next != NULL)
+       {
+               current = current->next;
+       }
+
+       /* Create a new one and assign values */
+       added = malloc(sizeof(cookie_list));
+       if(added == NULL)
+               goto error;
+
+       ret = generate_random_cookie(added->cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error on making random cookie: %d", ret);
+               free(added);
+               added = NULL;
+               goto error;
+       }
+
+        /* Check SMACK label */
+        ret = smack_new_label_from_socket(sockfd, &smack_label);
+        if (ret != 0)
+       {
+               SEC_SVR_DBG("Error checking peer label: %d", ret);
+               free(added);
+               added = NULL;
+               goto error;
+       }
+
+       added->path_len = strlen(cmdline);
+       added->path = calloc(1, strlen(cmdline));
+       memcpy(added->path, cmdline, strlen(cmdline));
+
+       added->permission_len = perm_num;
+       added->pid = pid;
+       added->permissions = permissions;
+       added->smack_label = smack_label;
+       added->prev = current;
+       current->next = added;
+       added->next = NULL;
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+       if(fp != NULL)
+               fclose(fp);
+       if(buf != NULL)
+               free(buf);
+
+       if(added == NULL && permissions != NULL)
+               free(permissions);
+
+       return added;
+}
+
+/* Check stored default cookie, if it's not exist make a new one and store it */
+int check_stored_cookie(unsigned char *cookie, int size)
+{
+       int fd, ret;
+
+       /* First, check the default cookie is stored */
+       fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_RDONLY);
+       if(fd < 0)
+       {
+               if(errno != ENOENT)
+               {
+                       SEC_SVR_DBG("Cannot open default cookie. errno=%d", errno);
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       unlink(SECURITY_SERVER_DEFAULT_COOKIE_PATH);
+               }
+
+               ret = generate_random_cookie(cookie, size);
+
+               /* Save cookie to disk */
+               fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_WRONLY | O_CREAT, 0600);
+               if (fd < 0)
+               {
+                       SEC_SVR_DBG("Cannot open default cookie errno=%d", errno);
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       goto error;
+               }
+               ret = write(fd, cookie, size);
+               if(ret < size)
+               {
+                       SEC_SVR_DBG("%s", "Cannot save default cookie");
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       goto error;
+               }
+
+               close(fd);
+               return SECURITY_SERVER_SUCCESS;
+       }
+
+       ret = read (fd, cookie, size);
+       if(ret < size)
+       {
+               SEC_SVR_DBG("Cannot read default cookie errno=%d", errno);
+               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               goto error;
+       }
+       ret = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(fd >= 0)
+               close(fd);
+       return ret;
+}
+/* Create a cookie item from PID */
+
+/* Create a default cookie when security server is executed *
+ * Default cookie is for root processes that needs cookie */
+cookie_list *create_default_cookie(void)
+{
+       cookie_list *first = NULL;
+       int ret;
+
+       first = malloc(sizeof(cookie_list));
+
+       ret = check_stored_cookie(first->cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error on making random cookie: %d", ret);
+               free(first);
+               return NULL;
+       }
+
+       first->path_len = 0;
+       first->permission_len = 0;
+       first->pid = 0;
+       first->path = NULL;
+       first->permissions = NULL;
+        first->smack_label = NULL;
+       first->prev = NULL;
+       first->next = NULL;
+       return first;
+}
diff --git a/src/server/security-server-main.c b/src/server/security-server-main.c
new file mode 100644 (file)
index 0000000..94fe1f5
--- /dev/null
@@ -0,0 +1,1326 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <errno.h>
+#include <signal.h>
+#include <pthread.h>
+#include <limits.h>
+#include <fcntl.h>
+#include <sys/smack.h>
+
+#include "security-server-cookie.h"
+#include "security-server-common.h"
+#include "security-server-password.h"
+#include "security-server-comm.h"
+
+/* Set cookie as a global variable */
+cookie_list *c_list;
+pthread_mutex_t cookie_mutex;
+int thread_status[SECURITY_SERVER_NUM_THREADS];
+struct security_server_thread_param {
+       int client_sockfd;
+       int server_sockfd;
+       int thread_status;
+};
+
+/************************************************************************************************/
+/* Just for test. This code must be removed on release */
+#include "security-server-util.h"
+/************************************************************************************************/
+
+#if 0
+void printhex(unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+void print_cookie(cookie_list *list)
+{
+       int i;
+       printf("%s", "cookie:\n");
+       printhex(list->cookie, SECURITY_SERVER_COOKIE_LEN);
+       printf("path_len: %d\n", list->path_len);
+       printf("permission_len: %d\n", list->permission_len);
+       printf("PID: %d\n", list->pid);
+       printf("path: %s\n", list->path);
+       printf("%s", "permissions: ");
+       for(i=0;i<list->permission_len;i++)
+       {
+               printf("%d ", list->permissions[i]);
+       }
+       printf("%s", "\n");
+       printf("prev: %p\n", list->prev);
+       printf("next: %p\n", list->next);
+}
+#endif
+
+/* Object name is actually name of a Group ID *
+ * This function opens /etc/group file and search group ID and
+ * returns the string */
+int search_object_name(int gid, char *obj, int obj_size)
+{
+       FILE *fp = NULL;
+       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
+       int ret = 0, tmp_gid, bufsize;
+       fp = fopen("/etc/group", "r");
+       if(fp == NULL)
+       {
+               /* cannot open /etc/group */
+               SEC_SVR_DBG("%s", "Cannot open /etc/group");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       linebuf = malloc(128);
+       bufsize = 128;
+       if(linebuf == NULL)
+       {
+               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               SEC_SVR_DBG("%s", "cannot malloc()");
+               goto error;
+       }
+
+       bzero(linebuf, bufsize);
+       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
+       while(fgets(linebuf, bufsize, fp) != NULL)
+       {
+               while(linebuf[bufsize -2] != 0)
+               {
+                       linebuf[bufsize -1] = (char) fgetc(fp);
+                       tempstr = realloc(linebuf, bufsize + 128);
+                       if(tempstr == NULL)
+                       {
+                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+                               goto error;
+                       }
+                       linebuf = tempstr;
+                       bzero(linebuf + bufsize, 128);
+                       fgets(linebuf + bufsize, 128, fp);
+                       bufsize += 128;
+               }
+
+               token = strtok(linebuf, ":");   /* group name */
+               if(token == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               token2 = strtok(NULL, ":");     /* group password */
+               if(token2== NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               token2 = strtok(NULL, ":");     /* gid */
+               if(token2 == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               errno = 0;
+               tmp_gid = strtoul(token2, 0, 10);
+               if (errno != 0)
+               {
+                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               if(tmp_gid == gid)
+               {
+                       /* We found it */
+                       if(strlen(token) > obj_size)
+                       {
+                               ret = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+                               SEC_SVR_DBG("buffer is too small. %d --> %d", obj_size, strlen(token));
+                               goto error;
+                       }
+                       strncpy(obj, token, strlen(token));
+                       obj[strlen(token)] = 0;
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               }
+               bzero(linebuf, bufsize);
+       }
+
+error:
+       if(linebuf != NULL)
+               free(linebuf);
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Search GID from group name *
+ * This function opens /etc/group and search group name by given gid */
+int search_gid(const char *obj)
+{
+       FILE *fp = NULL;
+       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
+       int ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT, tmp_gid, bufsize;
+
+       SEC_SVR_DBG("Searching for object %s", obj);
+
+       fp = fopen("/etc/group", "r");
+       if(fp == NULL)
+       {
+               /* cannot open /etc/group */
+               SEC_SVR_DBG("%s", "cannot open /etc/group");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       linebuf = malloc(128);
+       bufsize = 128;
+       if(linebuf == NULL)
+       {
+               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               SEC_SVR_DBG("%s", "Out Of Memory");
+               goto error;
+       }
+
+       bzero(linebuf, bufsize);
+       while(fgets(linebuf, bufsize, fp) != NULL)
+       {
+               while(linebuf[bufsize -2] != 0 )
+               {
+                       linebuf[bufsize -1] = (char) fgetc(fp);
+                       tempstr = realloc(linebuf, bufsize + 128);
+                       if(tempstr == NULL)
+                       {
+                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+                               goto error;
+                       }
+                       linebuf = tempstr;
+                       bzero(linebuf + bufsize, 128);
+                       fgets(linebuf + bufsize, 128, fp);
+                       bufsize += 128;
+               }
+
+               token = strtok(linebuf, ":");   /* group name */
+               token2 = strtok(NULL, ":");     /* group password */
+               token2 = strtok(NULL, ":");     /* gid */
+               if(token2 == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               errno = 0;
+               tmp_gid = strtoul(token2, 0, 10);
+               if ( errno != 0 )
+               {
+                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               if(strcmp(obj, token) == 0)
+               {
+                       /* We found it */
+                       ret = tmp_gid;
+                       SEC_SVR_DBG("GID of %s is found: %d", obj, ret);
+                       break;
+               }
+               bzero(linebuf, bufsize);
+       }
+
+error:
+       if(linebuf != NULL)
+               free(linebuf);
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Signal handler for processes */
+static void security_server_sig_child(int signo, siginfo_t *info, void *data)
+{
+       int status;
+       pid_t child_pid;
+       pid_t child_pgid;
+
+       child_pgid = getpgid(info->si_pid);
+       SEC_SVR_DBG("Signal handler: dead_pid=%d, pgid=%d",info->si_pid,child_pgid);
+
+       while ((child_pid = waitpid(-1, &status, WNOHANG)) > 0) {
+               if(child_pid == child_pgid)
+                       killpg(child_pgid,SIGKILL);
+       }
+
+       return;
+}
+
+/* Execute a debugging tool by fork() and execve() */
+int execute_debug_tool(int argc, char *const *argv, int server_sockfd, int client_sockfd)
+{
+       int ret, i;
+       SEC_SVR_DBG("%s", "Executing tool");
+
+       ret = fork();
+       if(ret == 0)
+       {
+               close(client_sockfd);
+               close(server_sockfd);
+               setsid();
+
+               for(i=0;i<_NSIG;i++)
+                       signal(i, SIG_DFL);
+
+               ret = execv(argv[0], argv);
+               if(ret == -1)
+               {
+                       SEC_SVR_DBG("Error:Failed to execute [%d]", errno);
+                       exit(-1);
+               }
+       }
+       if(ret < 0)
+       {
+               SEC_SVR_DBG("Error: Failed to fork [%d]", errno);
+               return SECURITY_SERVER_ERROR_SERVER_ERROR;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int process_cookie_request(int sockfd)
+{
+       int retval, client_pid, client_uid;
+       cookie_list *created_cookie = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_client_application(sockfd, &client_pid, &client_uid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* If client application is root process, just respond default cookie */
+    /*
+       if( client_uid == 0)
+       {
+               SEC_SVR_DBG("%s", "Requested application is a root process");
+               created_cookie = c_list;
+               if(c_list == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Cannot read default cookie");
+                       goto error;
+               }
+       }
+       else
+       {
+    */
+        //TODO: Remove above code if there will be no crashes without it
+        //All process should be treaded the same
+               /* Create a new cookie. or find existing one */
+               pthread_mutex_lock(&cookie_mutex);
+               created_cookie = create_cookie_item(client_pid, sockfd, c_list);
+               pthread_mutex_unlock(&cookie_mutex);
+               if(created_cookie == NULL)
+               {
+                       SEC_SVR_DBG("%s","Cannot create a cookie");
+                       goto error;
+               }
+
+    //let others know if this cookie belongs to root process
+    if(client_uid == 0)
+        created_cookie->is_roots_process = 1;
+    else
+        created_cookie->is_roots_process = 0;
+
+       //}
+       /* send cookie as response */
+       retval = send_cookie(sockfd, created_cookie->cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+       }
+        SEC_SVR_DBG("Server: Cookie created for client PID %d LABEL >%s<",
+                    created_cookie->pid,
+                    (created_cookie->smack_label)?(created_cookie->smack_label):"NULL");
+
+       SEC_SVR_DBG("%s", "Server: Cookie has been sent to client");
+
+error:
+       return retval;
+}
+
+int process_check_privilege_request(int sockfd)
+{
+       /* Authenticate client */
+       int retval, client_pid, requested_privilege;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       retval = recv_check_privilege_request(sockfd,
+                               requested_cookie, &requested_privilege);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       if(requested_privilege < 1)
+       {
+               SEC_SVR_DBG("Requiring bad privilege [%d]", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie(c_list, requested_cookie, requested_privilege);
+       pthread_mutex_unlock(&cookie_mutex);
+       if(search_result != NULL)
+       {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie with %d privilege and pid:%d", requested_privilege, client_pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("Could not find the cookie with %d privilege", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       return retval;
+}
+
+int process_check_privilege_new_request(int sockfd)
+{
+       /* Authenticate client */
+       int retval, client_pid, requested_privilege;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+        char object_label[MAX_OBJECT_LABEL_LEN+1];
+        char access_rights[MAX_MODE_STR_LEN+1];
+
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+        retval = recv_check_privilege_new_request(
+                     sockfd, requested_cookie, object_label, access_rights);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie_new(c_list, requested_cookie, object_label, access_rights);
+       pthread_mutex_unlock(&cookie_mutex);
+
+       if(search_result != NULL)
+    {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie with %s rights and pid:%d", access_rights, client_pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("Could not find the cookie with %s rights", access_rights);
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       return retval;
+
+
+}
+
+int process_object_name_request(int sockfd)
+{
+       int retval, client_pid, requested_privilege;
+       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
+
+       /* Authenticate client */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive GID */
+       retval = read(sockfd, &requested_privilege, sizeof(requested_privilege));
+       if (retval < sizeof(requested_privilege))
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search from /etc/group */
+       retval = search_object_name(requested_privilege,
+                       object_name,
+                       SECURITY_SERVER_MAX_OBJ_NAME);
+       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("There is no such object for gid [%d]", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error occurred */
+               SEC_SVR_DBG("Error on searching object name [%d]", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* We found */
+       SEC_SVR_DBG("We found object: %s", object_name);
+       retval = send_object_name(sockfd, object_name);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+       }
+
+error:
+       return retval;
+}
+
+int process_gid_request(int sockfd, int msg_len)
+{
+       int retval, client_pid;
+       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
+       /* Authenticate client as middleware daemon */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client authentication failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       if(msg_len >= SECURITY_SERVER_MAX_OBJ_NAME)
+       {
+               /* Too big ojbect name */
+               SEC_SVR_DBG("%s", "Object name is too big");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive group name */
+       retval = read(sockfd, object_name, msg_len);
+       if (retval < msg_len )
+       {
+               SEC_SVR_DBG("%s", "Failed to read object name");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       object_name[msg_len] = 0;
+
+       /* Search /etc/group for the given group name */
+       retval = search_gid(object_name);
+       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
+       {
+               /* Not exist */
+               SEC_SVR_DBG("The object [%s] is not exist", object_name);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       if(retval < 0)
+       {
+               /* Error occurred */
+               SEC_SVR_DBG("Cannot send the response. %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+
+               goto error;
+       }
+       /* We found */
+       retval = send_gid(sockfd, retval);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot gid response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_pid_request(int sockfd)
+{
+       int retval, client_pid;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       retval = recv_pid_request(sockfd, requested_cookie);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie(c_list, requested_cookie, 0);
+       pthread_mutex_unlock(&cookie_mutex);
+       if(search_result != NULL)
+       {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie and pid:%d", search_result->pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_pid(sockfd, search_result->pid);
+
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("%s", "Could not find the cookie");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send pid response: %d", retval);
+               }
+       }
+error:
+       return retval;
+}
+
+int process_smack_request(int sockfd)
+{
+       int retval, client_pid;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+    //handler for SMACK label
+    char * label = NULL;
+    //buffer for storing file path
+    const int BUFFSIZE = 30;
+    char path[BUFFSIZE];
+    int fd;
+
+       /* Authenticate client */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       retval = recv_smack_request(sockfd, requested_cookie);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie(c_list, requested_cookie, 0);
+       pthread_mutex_unlock(&cookie_mutex);
+       if(search_result != NULL)
+       {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie and pid:%d", search_result->pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+
+        //clearing buffer
+        memset(path, 0x00, BUFFSIZE);
+
+        //preparing file path
+        snprintf(path, BUFFSIZE, "/proc/%d/attr/current", search_result->pid);
+        SEC_SVR_DBG("Path to file: %s\n", path);
+
+        //allocation place for label
+        label = calloc(SMACK_LABEL_LEN, 1);
+        if(NULL == label)
+        {
+            SEC_SVR_DBG("Client ERROR: Memory allocation error");
+            goto error;
+        }
+
+        //clearing buffer for label
+        memset(label, 0x00, SMACK_LABEL_LEN);
+
+        //opening file /proc/<pid>/attr/curent with SMACK label
+        fd = open(path, O_RDONLY);
+        if(fd < 0)
+        {
+            SEC_SVR_DBG("Client ERROR: Unable to open file in /proc");
+            goto error;
+        }
+
+        //reading label from file, it is NOT NULL TERMINATED
+        retval = read(fd, label, SMACK_LABEL_LEN);
+        close(fd);
+        if(retval < 0)
+        {
+            SEC_SVR_DBG("Client ERROR: Unable to read from file");
+            goto error;
+        }
+
+        SEC_SVR_DBG("Readed label is: %s\n", label);
+
+               retval = send_smack(sockfd, label);
+
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("%s", "Could not find the cookie");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SMACK_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send SMACK label response: %d", retval);
+               }
+       }
+error:
+    if(NULL != label)
+        free(label);
+
+       return retval;
+}
+
+int process_tool_request(int client_sockfd, int server_sockfd)
+{
+       int retval, argcnum;
+       char **recved_argv = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_developer_shell(client_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive Total number of argv */
+       argcnum = 0;
+       retval = read(client_sockfd, &argcnum, sizeof(int));
+       if((retval < sizeof(int)) || argcnum > (UINT_MAX/sizeof(char *))-2 || argcnum < 0)
+       {
+               SEC_SVR_DBG("Error: argc recieve failed: %d", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       argcnum += 2;
+       recved_argv = (char **)malloc(sizeof(char *) * argcnum);
+       if(recved_argv == NULL)
+       {
+               SEC_SVR_DBG("Error: malloc() failed: %d", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       memset(recved_argv, 0, sizeof(char *) * argcnum);
+
+       retval = recv_launch_tool_request(client_sockfd, argcnum -1, recved_argv);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED || retval == SECURITY_SERVER_ERROR_OUT_OF_MEMORY)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               recved_argv = NULL;
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       if(argcnum < 2)
+       {
+               SEC_SVR_DBG("Error: Too small number of argv [%d]", argcnum);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* Execute the command */
+       retval = execute_debug_tool(argcnum, recved_argv, server_sockfd, client_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error: Cannot execute debug tool [%d]", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               SEC_SVR_DBG("%s", "Tool has been executed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SUCCESS);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       if(recved_argv != NULL)
+       {
+               /* Free */
+               free_argv(recved_argv, argcnum);
+               recved_argv = NULL;
+               argcnum =0;;
+       }
+       return retval;
+}
+
+void *security_server_thread(void *param)
+{
+       int client_sockfd = -1, client_uid, client_pid;
+       int server_sockfd, retval, argcnum;
+       basic_header basic_hdr;
+       struct security_server_thread_param *my_param;
+
+       my_param = (struct security_server_thread_param *) param;
+       client_sockfd = my_param->client_sockfd;
+       server_sockfd = my_param->server_sockfd;
+
+       /* Receive request header */
+       retval = recv_hdr(client_sockfd, &basic_hdr);
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT || retval == SECURITY_SERVER_ERROR_RECV_FAILED
+               || retval == SECURITY_SERVER_ERROR_SOCKET)
+       {
+               SEC_SVR_DBG("Receiving header error [%d]",retval);
+               close(client_sockfd);
+               client_sockfd = -1;
+               goto error;;
+       }
+
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Response */
+               SEC_SVR_DBG("Receiving header error [%d]",retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                       goto error;
+               }
+               safe_server_sock_close(client_sockfd);
+               client_sockfd = -1;
+               goto error;
+       }
+
+       /* Act different for request message ID */
+       switch(basic_hdr.msg_id)
+       {
+               case SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST:
+                       SEC_SVR_DBG("%s", "Cookie request received");
+                       process_cookie_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST:
+                       SEC_SVR_DBG("%s", "Privilege check received");
+                       process_check_privilege_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST:
+                       SEC_SVR_DBG("%s", "Privilege check (new mode) received");
+                       process_check_privilege_new_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST:
+                       SEC_SVR_DBG("%s", "Get object name request received");
+                       process_object_name_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GID_REQUEST:
+                       SEC_SVR_DBG("%s", "Get GID received");
+                       process_gid_request(client_sockfd, (int)basic_hdr.msg_len);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_PID_REQUEST:
+                       SEC_SVR_DBG("%s", "pid request received");
+                       process_pid_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SMACK_REQUEST:
+                       SEC_SVR_DBG("%s", "SMACK label request received");
+                       process_smack_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST:
+                       SEC_SVR_DBG("%s", "launch tool request received");
+                       process_tool_request(client_sockfd, server_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: validate password request received");
+                       process_valid_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: set password request received");
+                       process_set_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: reset password request received");
+                       process_reset_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: check password request received");
+                       process_chk_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: set password histroy request received");
+                       process_set_pwd_history_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST:
+                   SEC_SVR_DBG("%s", "Server: set password max challenge request received");
+                   process_set_pwd_max_challenge_request(client_sockfd);
+                   break;
+
+        case SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST:
+            SEC_SVR_DBG("%s", "Server: set password validity request received");
+            process_set_pwd_validity_request(client_sockfd);
+            break;
+
+/************************************************************************************************/
+/* Just for test. This code must be removed on release */
+               case SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST:
+                       SEC_SVR_DBG("%s", "all cookie info request received -- NEED TO BE DELETED ON RELEASE");
+                       retval = authenticate_client_application(client_sockfd, &client_pid, &client_uid);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       retval = util_process_all_cookie(client_sockfd, c_list);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("ERROR: Cannot send all cookie info: %d", retval);
+                       }
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST:
+                       SEC_SVR_DBG("%s", "cookie info from pid request received -- NEED TO BE DELETED ON RELEASE");
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       util_process_cookie_from_pid(client_sockfd, c_list);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST:
+                       SEC_SVR_DBG("%s", "cookie info from cookie request received -- NEED TO BE DELETED ON RELEASE");
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       util_process_cookie_from_cookie(client_sockfd, c_list);
+                       break;
+/************************************************************************************************/
+
+
+               default:
+                       SEC_SVR_DBG("Unknown msg ID :%d", basic_hdr.msg_id);
+                       /* Unknown message ID */
+                       retval = send_generic_response(client_sockfd,
+                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                       }
+                       break;
+       }
+
+       if(client_sockfd > 0)
+       {
+               safe_server_sock_close(client_sockfd);
+               client_sockfd = -1;
+       }
+
+error:
+       if(client_sockfd > 0)
+               close(client_sockfd);
+       thread_status[my_param->thread_status] = 0;
+       pthread_detach(pthread_self());
+       pthread_exit(NULL);
+}
+
+void *security_server_main_thread(void *data)
+{
+       int server_sockfd = 0, retval, client_sockfd = -1, args[2], rc;
+       struct sigaction act, dummy;
+       pthread_t threads[SECURITY_SERVER_NUM_THREADS];
+       struct security_server_thread_param param[SECURITY_SERVER_NUM_THREADS];
+
+       SEC_SVR_DBG("%s", "Starting Security Server main thread");
+
+       /* security server must be executed by root */
+       if(getuid() != 0)
+       {
+               fprintf(stderr, "%s\n", "You are not root. exiting...");
+               goto error;
+       }
+
+       for(retval = 0 ; retval < SECURITY_SERVER_NUM_THREADS; retval++)
+               thread_status[retval] = 0;
+       initiate_try();
+
+       /* Create and bind a Unix domain socket */
+       retval = create_new_socket(&server_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "cannot create socket. exiting...");
+               goto error;
+       }
+
+       if(listen(server_sockfd, 5) < 0)
+       {
+               SEC_SVR_DBG("%s", "listen() failed. exiting...");
+               goto error;
+       }
+
+       /* Create a default cookie --> Cookie for root process */
+       c_list = create_default_cookie();
+       if(c_list == NULL)
+       {
+               SEC_SVR_DBG("%s", "cannot make a default cookie. exiting...");
+               goto error;
+       }
+
+       /* Init signal handler */
+       act.sa_handler = NULL;
+       act.sa_sigaction = security_server_sig_child;
+       sigemptyset(&act.sa_mask);
+       act.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+
+       if (sigaction(SIGCHLD, &act, &dummy) < 0)
+       {
+               SEC_SVR_DBG("%s", "cannot change session");
+       }
+
+       pthread_mutex_init(&cookie_mutex, NULL);
+
+       while(1)
+       {
+               /* Accept a new client */
+               if(client_sockfd < 0)
+                       client_sockfd = accept_client(server_sockfd);
+
+               if(client_sockfd == SECURITY_SERVER_ERROR_TIMEOUT)
+                       continue;
+               if(client_sockfd < 0)
+                       goto error;
+               SEC_SVR_DBG("Server: new connection has been accepted: %d", client_sockfd);
+               retval = 0;
+               while(1)
+               {
+                       if(thread_status[retval] == 0)
+                       {
+                               thread_status[retval] = 1;
+                               param[retval].client_sockfd = client_sockfd;
+                               param[retval].server_sockfd = server_sockfd;
+                               param[retval].thread_status= retval;
+                               SEC_SVR_DBG("Server: Creating a new thread: %d", retval);
+                               rc =pthread_create(&threads[retval], NULL, security_server_thread, (void *)&param[retval]);
+                               if (rc)
+                               {
+                                       SEC_SVR_DBG("Error: Server: Cannot create thread:%d", rc);
+                                       goto error;
+                               }
+                               break;
+                       }
+                       retval++;
+                       if(retval >= SECURITY_SERVER_NUM_THREADS)
+                               retval = 0;
+               }
+               client_sockfd = -1;
+       }
+error:
+       if(server_sockfd > 0)
+               close(server_sockfd);
+
+       pthread_detach(pthread_self());
+       pthread_exit(NULL);
+}
+
+int main(int argc, char* argv[])
+{
+       int res;
+       pthread_t main_thread;
+
+       res = pthread_create(&main_thread, NULL, security_server_main_thread, NULL);
+       if (res == 0)
+       {
+               while (1)
+                       sleep(60);
+       }
+       else
+       {
+               SEC_SVR_DBG("Error: Server: Cannot create main security server thread: %d", res);
+       }
+       pthread_exit(NULL);
+       return 0;
+}
+
diff --git a/src/server/security-server-password.c b/src/server/security-server-password.c
new file mode 100644 (file)
index 0000000..367b5d6
--- /dev/null
@@ -0,0 +1,1579 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dirent.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <openssl/sha.h>
+
+#include "security-server-password.h"
+
+struct timeval prev_try;
+
+void initiate_try()
+{
+       gettimeofday(&prev_try, NULL);
+}
+
+int validate_pwd_file(char *filename)
+{
+       int i;
+
+       if((strncmp(filename + (strlen(filename) -4), ".pwd" , 4)) != 0)
+       {
+               SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       for(i=0;i<(strlen(filename) -4);i++)
+       {
+               if(filename[i] > '9' || filename[i] < '0')
+               {
+                       SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
+                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
+               }
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int dir_filter(const struct dirent *entry)
+{
+       if ((strcmp(entry->d_name, ".") == 0) ||
+               (strcmp(entry->d_name, "..") == 0) ||
+               (strcmp(entry->d_name, "attempts") ==0) ||
+               (strcmp(entry->d_name, "history") ==0) )
+               return (0);
+       else
+               return (1);
+}
+
+int get_pwd_path(char *path)
+{
+       int retval;
+       struct dirent **mydirent;
+       int num;
+       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
+       if(num < 0)
+       {
+               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       if(num == 0)
+       {
+               SEC_SVR_DBG("%s", "Server: There is no password file");
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num-1]->d_name);
+       retval = validate_pwd_file(mydirent[num-1]->d_name);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Removing invalid password file: %s", path);
+               unlink(path);
+               get_pwd_path(path);
+       }
+       SEC_SVR_DBG("Password file path: %s", path);
+       while (num--)
+               free(mydirent[num]);
+       free(mydirent);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int load_password(unsigned char *cur_pwd, unsigned int *max_attempt, unsigned int *expire_time)
+{
+       int retval, fd;
+       char pwd_path[255];
+
+       /* Create directory */
+       retval = mkdir(SECURITY_SERVER_DATA_DIRECTORY_PATH, 0700);
+       if(retval != 0)
+       {
+               if(errno != EEXIST)
+               {
+                       SEC_SVR_DBG("Cannot create directory. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+
+       /* Check password files */
+       while(1)
+       {
+               /* Get password file path */
+               retval = get_pwd_path(pwd_path);
+               if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+               {
+                       SEC_SVR_DBG("%s", "Current password doesn't exist");
+                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
+               }
+
+               /* Load password file */
+               fd = open(pwd_path, O_RDONLY | O_NONBLOCK );
+               if(fd < 0)
+               {
+                       if(errno == ENOENT)
+                       {
+                               SEC_SVR_DBG("%s", "Server: Current password doesn't exist");
+                               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+                       }
+                       SEC_SVR_DBG("Server: Current password cannot be opened. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+
+               /* Read and store into memory */
+               retval = read(fd, cur_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+               if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 0");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+
+               retval = read(fd, max_attempt, sizeof(unsigned int));
+               if(retval < sizeof(unsigned int))
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 1");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+
+               retval = read(fd, expire_time, sizeof(unsigned int));
+               if(retval < sizeof(unsigned int))
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 2");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+               close(fd);
+
+               /* Check expiration time. */
+               if(*expire_time == 0)  /* No valid period */
+                       *expire_time = 0xffffffff;
+               else if(*expire_time <= time(NULL)) /* expired */
+                       *expire_time =0;
+               else            /* valid yet */
+                       *expire_time -= time(NULL);
+               break;
+       }
+       SEC_SVR_DBG("%s", "Server: Current password file successfully loaded");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int get_current_attempt(int increase)
+{
+       int retval, fd, attempt;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_ATTEMPT_FILE_NAME);
+
+       /* Open current attempt file as read mode */
+       fd = open(path, O_RDONLY | O_NONBLOCK );
+       if(fd < 0)
+       {
+               if(errno == ENOENT)
+               {
+                       SEC_SVR_DBG("%s", "Server: attempt doesn't exist. Creating one:");
+                       /* Create one if it doesn't exist */
+                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+                       if(fd < 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       retval = fchmod(fd, 0600);
+                       if(retval != 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+                               close(fd);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       attempt = increase;
+                       retval = write(fd, &attempt, sizeof(int));
+                       close(fd);
+                       if(retval < sizeof(int))
+                       {
+                               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       return attempt;
+               }
+               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = read(fd, &attempt, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot read attempt");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       if(increase > 0)
+       {
+               /* Open the file again with write mode */
+               fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+               if(fd < 0)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+               retval = fchmod(fd, 0600);
+               if(retval != 0)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+                       close(fd);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+               attempt += increase;
+               retval = write(fd, &attempt, sizeof(int));
+               close(fd);
+               if(retval < sizeof(int))
+               {
+                       SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+       return attempt;
+}
+
+int reset_attempt(void)
+{
+       int fd, retval;
+       char path[255];
+       unsigned int attempt = 0;
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_ATTEMPT_FILE_NAME);
+
+       /* Open the file again with write mode */
+       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &attempt, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       SEC_SVR_DBG("%s", "Server: Attempt reset");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Compare current password Stored password is hashed by SHA-256 Algorithm */
+int check_password(const unsigned char *cur_pwd, const unsigned char *requested_pwd,
+                       const unsigned int max_attempts, const unsigned int expire_time,
+                       int *current_attempt)
+{
+       unsigned int current_time = time(NULL);
+
+       if(max_attempts != 0)
+       {
+               *current_attempt = get_current_attempt(1);
+
+               if(*current_attempt > max_attempts)
+               {
+                       SEC_SVR_DBG("Server: Max attempt exceeded: %d, %d", *current_attempt, max_attempts);
+                       return SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+               }
+               if(*current_attempt < 0)
+               {
+                       SEC_SVR_DBG("Server: Attempt file operation failed. Ignoring... : %d", *current_attempt);
+               }
+       }
+
+       /* Compare */
+       if(memcmp(cur_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) != 0)
+       {
+           SEC_SVR_DBG("%s", "Password mismatched");
+           return SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
+       }
+
+    if(expire_time == 0)
+    {
+        SEC_SVR_DBG("Server: Password has been expired: %d, %d", current_time, expire_time);
+        return SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
+    }
+
+    SEC_SVR_DBG("%s", "Password matched");
+    return SECURITY_SERVER_SUCCESS;
+}
+
+int set_history(int num)
+{
+       int fd, retval;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_HISTORY_FILE_NAME);
+
+       /* Open the file again with write mode */
+       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+       if(fd < 0)
+       {
+               if (errno == ENOENT)
+               {
+                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+                       if(fd < 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot create history file. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+               }
+               else
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot open history file. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot chmod history file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &num, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot write history");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       SEC_SVR_DBG("%s", "Server: history set finished");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+
+int get_history_num(void)
+{
+       /* Placeholder for password history check count getting function */
+       int fd, retval, history;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_HISTORY_FILE_NAME);
+
+       /* Load password file */
+       fd = open(path, O_RDONLY | O_NONBLOCK );
+       if(fd < 0)
+       {
+               if(errno == ENOENT)
+               {
+                       SEC_SVR_DBG("%s", "Server: history file doesn't exist");
+                       retval = set_history(0);
+                       return retval;
+               }
+               SEC_SVR_DBG("Server ERROR: history file cannot be opened. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = read(fd, &history, sizeof(history));
+       close(fd);
+       if(retval < sizeof(history))
+       {
+               SEC_SVR_DBG("%s", "History file corrupted. Creating new one");
+               unlink(path);
+               retval = set_history(0);
+               return retval;
+       }
+       SEC_SVR_DBG("History file read: %d", history);
+       return history;
+}
+
+
+
+int check_history(const unsigned char *requested_pwd)
+{
+       unsigned char history_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       char path[255];
+       unsigned int max_history;
+       int num, history_count, fd, file_count, retval;
+       int retval2 = SECURITY_SERVER_SUCCESS;
+       struct dirent **mydirent;
+
+       history_count = get_history_num();
+       if(history_count <= 0)
+               return SECURITY_SERVER_SUCCESS;
+
+       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
+       if(num < 0)
+       {
+               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       if(num == 0)
+       {
+               SEC_SVR_DBG("%s", "Server: There is no password file");
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       file_count = 2;
+       while((num--))
+       {
+               snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num]->d_name);
+               SEC_SVR_DBG("Password file path: %s", path);
+               if(history_count > 0)
+               {
+                       /* Load password file */
+                       fd = open(path, O_RDONLY | O_NONBLOCK );
+                       if(fd < 0)
+                       {
+                               if(errno == ENOENT)
+                               {
+                                       SEC_SVR_DBG("%s", "Current password doesn't exist");
+                                       return SECURITY_SERVER_SUCCESS;
+                               }
+                               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       /* Read and store into memory */
+                       retval = read(fd, history_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+                       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+                       {
+                               SEC_SVR_DBG("%s", "Current password corrupted. resetting to previous one. 0");
+                               close(fd);
+                               fd = 0;
+                               unlink(path);
+                               continue;
+                       }
+                       close(fd);
+                       /* Compare */
+                       if(memcmp(history_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) == 0)
+                       {
+                               SEC_SVR_DBG("%s", "Server: Password has been reused");
+                               retval2 =  SECURITY_SERVER_ERROR_PASSWORD_REUSED;
+                       }
+                       history_count--;
+
+               }
+
+               /* Remove too old or invalid password history */
+               retval = validate_pwd_file(mydirent[num]->d_name);
+               if(retval != SECURITY_SERVER_SUCCESS || file_count > (SECURITY_SERVER_MAX_PASSWORD_HISTORY))
+               {
+                       SEC_SVR_DBG("Removing too old password. %s", path);
+                       unlink(path);
+               }
+               file_count++;
+               free(mydirent[num]);
+       }
+       free(mydirent);
+       if(retval2 == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
+               retval = retval2;
+       return retval;
+}
+
+/* Password file format */
+/*  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                       Hashed PWD (32 bytes)                   |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                       Max attempts (4 bytes)                  |
+ * |---------------------------------------------------------------|
+ * |              Expiration time in seconds (4 bytes)             |
+ * |---------------------------------------------------------------|
+ */
+int set_password(const unsigned char *requested_new_pwd, const unsigned int attempts,
+                       const unsigned int expire_time)
+{
+       int retval, fd;
+       char pwd_path[255];
+
+       /* New file created */
+       retval = time(NULL);
+       snprintf(pwd_path, 255, "%s/%d.pwd", SECURITY_SERVER_DATA_DIRECTORY_PATH, retval);
+
+       /* Save new password as current password */
+       fd = open(pwd_path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("Cannot open current password file. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Cannot chmod current password file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, requested_new_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &expire_time, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       fsync(fd);
+       close(fd);
+       SEC_SVR_DBG("%s", "Password file created");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int check_retry(const struct timeval cur_try)
+{
+       int retval, interval_sec, interval_usec;
+       interval_sec = cur_try.tv_sec - prev_try.tv_sec;
+       interval_usec = cur_try.tv_usec - prev_try.tv_usec;
+       prev_try = cur_try;
+       if(interval_sec > SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND)
+               return SECURITY_SERVER_SUCCESS;
+
+       if(interval_sec == SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND
+                       && interval_usec >= 0)
+               return SECURITY_SERVER_SUCCESS;
+
+       SEC_SVR_DBG("%s", "retry timer hit");
+       return SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
+}
+
+int process_valid_pwd_request(int sockfd)
+{
+       struct timeval cur_try;
+       int retval, current_attempts, password_set;
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned int max_attempt, expire_time;
+
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       current_attempts = get_current_attempt(0);
+       if(current_attempts < 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot get attempts: %d", current_attempts);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+
+       /* There is no password */
+       if(password_set == SECURITY_SERVER_ERROR_NO_PASSWORD)
+       {
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_PASSWORD,
+                               0, 0, 0);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
+               }
+               goto error;
+       }
+       if(password_set == SECURITY_SERVER_SUCCESS)
+       {
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST,
+                               current_attempts, max_attempt, expire_time);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
+               }
+               goto error;
+       }
+       SEC_SVR_DBG("Server ERROR: Unknown error: %d", retval);
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_set_pwd_request(int sockfd)
+{
+       struct timeval cur_try;
+       int retval, password_set, current_attempt;
+       unsigned int max_attempt, expire_time, valid_days, received_attempts;
+       char  new_pwd_len = 0, cur_pwd_len = 0;
+       char requested_cur_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is setting app goes here*/
+       /* Check SMACK 'rw' rule for the set password */
+       retval = SECURITY_SERVER_SUCCESS;
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
+       /* If we cannot load password file */
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwds */
+       retval = read(sockfd, &cur_pwd_len, sizeof(char));
+       if(retval < sizeof(char) || cur_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server Error: current password length recieve failed: %d, %d", retval, cur_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       retval = read(sockfd, &new_pwd_len, sizeof(char));
+       if(retval < sizeof(char)  || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN || new_pwd_len < 0)
+       {
+               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive current password */
+       if(cur_pwd_len > 0)
+       {
+               /* Check wheter current password is exist */
+               if(password_set == SECURITY_SERVER_SUCCESS)
+               retval = read(sockfd, requested_cur_pwd, cur_pwd_len);
+               if(retval < cur_pwd_len)
+               {
+                       SEC_SVR_DBG("Server Error: current password recieve failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               requested_cur_pwd[cur_pwd_len] = 0;
+       }
+       else /* Check first password set attempt but password is already set */
+       {
+               if(password_set == SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server Error: password is already set: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+       }
+
+       /* Receive new password */
+       retval = read(sockfd, requested_new_pwd, new_pwd_len);
+       if(retval < new_pwd_len)
+       {
+               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       requested_new_pwd[new_pwd_len] = 0;
+
+       /* Receive max attempt */
+       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive valid period  */
+       retval = read(sockfd, &valid_days, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_cur_pwd, strlen(requested_cur_pwd));
+       SHA256_Final(hashed_challenge, &context);
+
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
+       SHA256_Final(hashed_new_pw, &context);
+
+       /* check current password */
+       if(password_set  == SECURITY_SERVER_SUCCESS)
+       {
+               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
+               {
+                       SEC_SVR_DBG("%s", "Server: Wrong password");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Too many challange");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Password expired");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Error: Password check failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               retval = check_history(hashed_new_pw);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
+               {
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+       }
+       else if(cur_pwd_len != 0)
+       {
+               /* Client ask to set with current password, but there is no password now */
+               SEC_SVR_DBG("%s", "Server: There is no current password. But try to set with current password");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Calculate expire time in seconds */
+       if(valid_days == 0)
+               expire_time = 0;
+       else
+               expire_time = time(NULL) + (valid_days * 86400);
+
+       /* set new password */
+       retval = set_password(hashed_new_pw, received_attempts, expire_time);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               password_set = SECURITY_SERVER_ERROR_SERVER_ERROR;
+               goto error;
+       }
+       password_set = SECURITY_SERVER_SUCCESS;
+       retval = reset_attempt();
+
+       /* All done. send response */
+       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_reset_pwd_request(int sockfd)
+{
+       int retval, password_set;
+       char new_pwd_len;
+       unsigned int valid_days, received_attempts, expire_time;
+       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN +1];
+       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       struct timeval cur_try;
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is setting app goes here*/
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       password_set = load_password(cur_pwd, &valid_days, &expire_time);
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwd */
+       retval = read(sockfd, &new_pwd_len, sizeof(char));
+       if(retval < sizeof(char) || new_pwd_len < 0 || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive new password */
+       retval = read(sockfd, requested_new_pwd, new_pwd_len);
+       if(retval < new_pwd_len)
+       {
+               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       requested_new_pwd[new_pwd_len] = 0;
+
+       /* Receive max attempt */
+       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive valid period  */
+       retval = read(sockfd, &valid_days, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Calculate expire time in seconds */
+       if(valid_days == 0)
+               expire_time = 0;
+       else
+               expire_time = time(NULL) + (valid_days * 86400);
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
+       SHA256_Final(hashed_new_pw, &context);
+       /* set new password */
+       retval = set_password(hashed_new_pw, received_attempts, expire_time);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       retval = reset_attempt();
+
+       /* All done. send response */
+       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_chk_pwd_request(int sockfd)
+{
+       int retval, password_set, current_attempt;
+       unsigned int max_attempt, expire_time;
+       char requested_challenge[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       char challenge_len;
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
+       struct timeval cur_try;
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is proper app goes here*/
+       /* Check SMACK rule for the 'r' for password */
+       retval = SECURITY_SERVER_SUCCESS;
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* If we cannot load password file */
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);;
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "ServerERROR: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of challenge */
+       retval = read(sockfd, &challenge_len, sizeof(char));
+       if(retval < sizeof(char) || challenge_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server ERROR: challenge length recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* Receive challenge */
+       if(challenge_len > 0)
+       {
+               retval = read(sockfd, requested_challenge, challenge_len);
+               if(retval < challenge_len)
+               {
+                       SEC_SVR_DBG("Server ERROR: current password recieve failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               requested_challenge[challenge_len] = 0;
+       }
+       else
+       {
+               SEC_SVR_DBG("Error: Challenge length too short: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_challenge, challenge_len);
+       SHA256_Final(hashed_challenge, &context);
+
+       /* check current password */
+       if(password_set  == SECURITY_SERVER_SUCCESS)
+       {
+               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
+               {
+                       SEC_SVR_DBG("%s", "Server: Wrong password");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH,
+                                       current_attempt, max_attempt, expire_time);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Too many trial");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED,
+                                       current_attempt, max_attempt, expire_time);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Password expired");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED,
+                                       current_attempt, max_attempt, 0);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Password check failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+
+               /* Password matched */
+               SEC_SVR_DBG("%s", "Server: Password matched");
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SUCCESS,
+                               current_attempt, max_attempt, expire_time);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               retval = reset_attempt();
+               goto error;
+       }
+
+       /* There is no password */
+
+       SEC_SVR_DBG("%s", "Server: There is no password to be checked");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_set_pwd_history_request(int sockfd)
+{
+       int retval;
+       char history_num;
+       struct timeval cur_try;
+
+       /* Authenticate client that peer is setting app goes here*/
+/*
+       f(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwds */
+       retval = read(sockfd, &history_num, sizeof(char));
+       if(retval < sizeof(char) || history_num > SECURITY_SERVER_MAX_PASSWORD_HISTORY || history_num < 0 )
+       {
+               SEC_SVR_DBG("Server Error: History number recieve failed: %d, %d", retval, history_num);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       retval = set_history((int)history_num);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: History number set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       SEC_SVR_DBG("Server History has been set to %d", history_num);
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+
+int process_set_pwd_max_challenge_request(int sockfd)
+{
+    unsigned int max_challenge, current_challenge, current_validity;
+    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+    int retval;
+
+    // TODO here we should probably check if the peer has rights to change
+    // this value (max challenge) for current password
+
+    retval = read(sockfd, &max_challenge, sizeof(unsigned int));
+    if(retval < sizeof(unsigned int))
+    {
+        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    SEC_SVR_DBG("Server max challenge request: %d", max_challenge);
+
+    // Getting currently set password
+    retval = load_password(cur_pwd, &current_challenge, &current_validity);
+    /* If we cannot load password file */
+    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+    else if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    // Set 'new' password file with old password and new max challenge
+    retval = set_password(cur_pwd, max_challenge, time(NULL) + current_validity);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    retval = send_generic_response(sockfd,
+            SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+            SECURITY_SERVER_RETURN_CODE_SUCCESS);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+    }
+    retval = reset_attempt();
+error:
+    return retval;
+}
+
+int process_set_pwd_validity_request(int sockfd)
+{
+    unsigned int current_challenge, current_validity, validity;
+    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+    int retval;
+
+    // TODO here we should probably check if the peer has rights to change
+    // this value (validity) for current password
+
+    retval = read(sockfd, &validity, sizeof(unsigned int));
+    if(retval < sizeof(unsigned int))
+    {
+        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    SEC_SVR_DBG("Server validity request: %d", validity);
+
+    // Calculating validity in seconds
+    if(validity == 0)
+        validity = 0;
+    else
+        validity = time(NULL) + (validity * 86400);
+
+    // Getting currently set password
+    retval = load_password(cur_pwd, &current_challenge, &current_validity);
+    /* If we cannot load password file */
+    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+    else if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    // Set 'new' password file with old password and new validity
+    retval = set_password(cur_pwd, current_challenge, validity);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    retval = send_generic_response(sockfd,
+            SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+            SECURITY_SERVER_RETURN_CODE_SUCCESS);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+    }
+    retval = reset_attempt();
+error:
+    return retval;
+}
diff --git a/src/services/ace/ace_server_api.h b/src/services/ace/ace_server_api.h
deleted file mode 100644 (file)
index e327e31..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_server_api.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       This file contains definitions of ACE server interface name & methods.
- */
-
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
-
-#include<string>
-
-
-namespace WrtSecurity{
-namespace AceServerApi{
-
-    // DBus interface names
-    inline const std::string INTERFACE_NAME()
-    {
-        return "org.tizen.AceCheckAccessInterface";
-    }
-
-    // IN string subject
-    // IN string resource
-    // IN vector<string> function param names
-    // IN vector<string> function param values
-    // OUT int allow, deny, popup type
-    inline const std::string CHECK_ACCESS_METHOD()
-    {
-        return "check_access";
-    }
-
-    // IN string subject
-    // IN string resource
-    // OUT int allow, deny, popup type
-    inline const std::string CHECK_ACCESS_INSTALL_METHOD()
-    {
-        return "check_access_install";
-    }
-
-    // Policy update trigger
-    inline const std::string UPDATE_POLICY_METHOD()
-    {
-        return "update_policy";
-    }
-};
-};
-
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
diff --git a/src/services/ace/ace_service.cpp b/src/services/ace/ace_service.cpp
deleted file mode 100644 (file)
index 15227f4..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This is implementation file of AceService service
- */
-
-#include <dpl/log/log.h>
-#include <security_controller.h>
-
-#include "security_daemon.h"
-
-namespace AceService
-{
-
-class AceService : public SecurityDaemon::DaemonService
-{
-  private:
-    virtual void initialize()
-    {
-        LogDebug("AceService initializing");
-
-        SecurityControllerSingleton::Instance().Touch();
-        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
-
-        CONTROLLER_POST_SYNC_EVENT(
-            SecurityController,
-            SecurityControllerEvents::InitializeSyncEvent());
-    }
-
-    virtual void start()
-    {
-        LogDebug("Starting AceService");
-    }
-
-    virtual void stop()
-    {
-        LogDebug("Stopping AceService");
-    }
-
-    virtual void deinitialize()
-    {
-        LogDebug("AceService deinitializing");
-        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
-        //this is direct call inside
-        CONTROLLER_POST_SYNC_EVENT(
-            SecurityController,
-            SecurityControllerEvents::TerminateSyncEvent());
-    }
-
-};
-
-DAEMON_REGISTER_SERVICE_MODULE(AceService)
-
-}//namespace AceService
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.cpp b/src/services/ace/dbus/ace_server_dbus_interface.cpp
deleted file mode 100644 (file)
index e77b9f9..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service_dbus_interface.cpp
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       Implementation of ACE server API.
- */
-#include <dpl/foreach.h>
-#include <vector>
-#include <string>
-#include "ace_server_dbus_interface.h"
-#include <dpl/dbus/dbus_server_deserialization.h>
-#include <dpl/dbus/dbus_server_serialization.h>
-
-#include <ace/Request.h>
-#include <ace/PolicyResult.h>
-#include <security_controller.h>
-#include <attribute_facade.h>
-
-
-namespace RPC {
-
-void AceServerDBusInterface::onMethodCall(const gchar* methodName,
-                          GVariant* parameters,
-                          GDBusMethodInvocation* invocation)
-{
-    using namespace WrtSecurity;
-
-    if (0 == g_strcmp0(methodName, AceServerApi::ECHO_METHOD().c_str()))
-    {
-        std::string str;
-        DPL::DBus::ServerDeserialization::deserialize(parameters, &str);
-        g_dbus_method_invocation_return_value(invocation,
-                DPL::DBus::ServerSerialization::serialize(str));
-    } else if (0 == g_strcmp0(methodName,
-                              AceServerApi::CHECK_ACCESS_METHOD().c_str()))
-    {
-        int widgetHandle;
-        std::string subject, resource, sessionId;
-        std::vector<std::string> paramNames, paramValues;
-        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
-                                                      &widgetHandle,
-                                                      &subject,
-                                                      &resource,
-                                                      &paramNames,
-                                                      &paramValues,
-                                                      &sessionId)) {
-            g_dbus_method_invocation_return_dbus_error(
-                          invocation,
-                          "org.tizen.AceCheckAccessInterface.UnknownError",
-                          "Error in deserializing input parameters");
-            return;
-        }
-        if (paramNames.size() != paramValues.size()) {
-            g_dbus_method_invocation_return_dbus_error(
-                      invocation,
-                      "org.tizen.AceCheckAccessInterface.UnknownError",
-                      "Varying sizes of parameter names and parameter values");
-            return;
-        }
-        LogDebug("We got subject: " << subject);
-        LogDebug("We got resource: " << resource);
-
-        FunctionParamImpl params;
-        for (size_t i = 0; i < paramNames.size(); ++i) {
-            params.addAttribute(paramNames[i], paramValues[i]);
-        }
-
-        Request request(widgetHandle,
-                        WidgetExecutionPhase_Invoke,
-                        &params);
-        request.addDeviceCapability(resource);
-
-        PolicyResult result(PolicyEffect::DENY);
-        CONTROLLER_POST_SYNC_EVENT(
-            SecurityController,
-            SecurityControllerEvents::CheckRuntimeCallSyncEvent(
-                &result,
-                &request,
-                sessionId));
-
-        int response = PolicyResult::serialize(result);
-        g_dbus_method_invocation_return_value(invocation,
-                DPL::DBus::ServerSerialization::serialize(response));
-    } else if (0 == g_strcmp0(methodName,
-            AceServerApi::CHECK_ACCESS_INSTALL_METHOD().c_str()))
-    {
-        int widgetHandle;
-        std::string resource;
-        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
-                                            &widgetHandle,
-                                            &resource)) {
-            g_dbus_method_invocation_return_dbus_error(
-                    invocation,
-                    "org.tizen.AceCheckAccessInterface.UnknownError",
-                    "Error in deserializing input parameters");
-            return;
-        }
-        LogDebug("We got handle: " << widgetHandle);
-        LogDebug("We got resource: " << resource);
-
-        Request request(widgetHandle,
-              WidgetExecutionPhase_WidgetInstall);
-        request.addDeviceCapability(resource);
-
-        PolicyResult result(PolicyEffect::DENY);
-        CONTROLLER_POST_SYNC_EVENT(
-        SecurityController,
-        SecurityControllerEvents::CheckFunctionCallSyncEvent(
-             &result,
-             &request));
-
-        int response = PolicyResult::serialize(result);
-        g_dbus_method_invocation_return_value(invocation,
-                DPL::DBus::ServerSerialization::serialize(response));
-    } else if (0 == g_strcmp0(methodName,
-            AceServerApi::UPDATE_POLICY_METHOD().c_str()))
-    {
-        LogDebug("Policy update DBus message received");
-        CONTROLLER_POST_SYNC_EVENT(
-                    SecurityController,
-                    SecurityControllerEvents::UpdatePolicySyncEvent());
-        g_dbus_method_invocation_return_value(invocation, NULL);
-    } else {
-        // invalid method name
-        g_dbus_method_invocation_return_value(invocation, NULL);
-    }
-}
-
-} // namespace RPC
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.h b/src/services/ace/dbus/ace_server_dbus_interface.h
deleted file mode 100644 (file)
index d5957cb..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service_dbus_interface.h
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       Class that handles ACE server API.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
-
-#include <dpl/dbus/dbus_interface_dispatcher.h>
-#include "api/ace_server_dbus_api.h"
-
-namespace RPC {
-
-class AceServerDBusInterface : public DPL::DBus::InterfaceDispatcher {
-  public:
-    AceServerDBusInterface():
-        DPL::DBus::InterfaceDispatcher(WrtSecurity::AceServerApi::INTERFACE_NAME())
-    {
-        using namespace WrtSecurity;
-
-        setXmlSignature("<node>"
-            "  <interface name='" + AceServerApi::INTERFACE_NAME() + "'>"
-            "    <method name='" + AceServerApi::ECHO_METHOD() + "'>"
-            "      <arg type='s' name='input' direction='in'/>"
-            "      <arg type='s' name='output' direction='out'/>"
-            "    </method>"
-            "    <method name='" + AceServerApi::CHECK_ACCESS_METHOD() + "'>"
-            "      <arg type='i' name='handle' direction='in'/>"
-            "      <arg type='s' name='subject' direction='in'/>"
-            "      <arg type='s' name='resource' direction='in'/>"
-            "      <arg type='as' name='parameter names' direction='in'/>"
-            "      <arg type='as' name='parameter values' direction='in'/>"
-            "      <arg type='s' name='session' direction='in'/>"
-            "      <arg type='i' name='output' direction='out'/>"
-            "    </method>"
-            "    <method name='" + AceServerApi::CHECK_ACCESS_INSTALL_METHOD() + "'>"
-            "      <arg type='i' name='handle' direction='in'/>"
-            "      <arg type='s' name='resource' direction='in'/>"
-            "      <arg type='i' name='output' direction='out'/>"
-            "    </method>"
-            "    <method name='" + AceServerApi::UPDATE_POLICY_METHOD() + "'>"
-            "    </method>"
-            "  </interface>"
-            "</node>");
-    }
-
-    virtual ~AceServerDBusInterface()
-    {}
-
-    virtual void onMethodCall(const gchar* methodName,
-                              GVariant* parameters,
-                              GDBusMethodInvocation* invocation);
-};
-
-} // namespace RPC
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ace/dbus/api/ace_server_dbus_api.h b/src/services/ace/dbus/api/ace_server_dbus_api.h
deleted file mode 100644 (file)
index 9db4f05..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_server_api.h
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       This file contains definitions ACE server interface & methods specifically needed by DBUS.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
-
-#include "ace_server_api.h"
-#include<string>
-
-namespace WrtSecurity{
-namespace AceServerApi{
-
-    // RPC test function
-    // IN std::string
-    // OUT std::string
-    inline const std::string ECHO_METHOD()
-    {
-        return "echo";
-    }
-};
-};
-
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
diff --git a/src/services/ace/logic/acf_consts.h b/src/services/ace/logic/acf_consts.h
deleted file mode 100644 (file)
index 93ecfae..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * This file contain consts for Signing Template and Policy Manager
- * This values will be used to specified and identified algorithms in xml policy documents.
- * Its consistent with BONDI 1.0 released requirements
- *
- * NOTE: This values should be verified when ACF will be updated to the latest version of BONDI requirements
- * This values comes from widget digital signature 1.0 - required version of this doc is very important
- *
- **/
-
-#ifndef ACF_CONSTS_TYPES_H
-#define ACF_CONSTS_TYPES_H
-
-//Digest Algorithms
-extern const char* DIGEST_ALG_SHA256;
-
-//Canonicalization Algorithms
-extern const char* CANONICAL_ALG_C14N;
-
-//Signature Algorithms
-extern const char* SIGNATURE_ALG_RSA_with_SHA256;
-extern const char* SIGNATURE_ALG_DSA_with_SHA1;
-extern const char* SIGNATURE_ALG_ECDSA_with_SHA256;
-
-#endif
-
diff --git a/src/services/ace/logic/attribute_facade.cpp b/src/services/ace/logic/attribute_facade.cpp
deleted file mode 100644 (file)
index 2a988a7..0000000
+++ /dev/null
@@ -1,716 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- *
- * This file contains classes that implement WRT_INTERFACE.h interfaces,
- * so that ACE could access  WRT specific and other information during
- * the decision making.
- *
- * @file    attribute_.cpp
- * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @author  Ming Jin(ming79.jin@samsung.com)
- * @version 1.0
- * @brief   Implementation file for attributes obtaining.
- */
-
-#include <dpl/exception.h>
-#include <sstream>
-#include <algorithm>
-#include <list>
-#include <string>
-#include <sstream>
-#include <stdexcept>
-#include <map>
-#include <cstdlib>
-#include <ace-dao-ro/AceDAOReadOnly.h>
-#include <ace/WRT_INTERFACE.h>
-#include <map>
-#include <dpl/log/log.h>
-#include <dpl/foreach.h>
-#include <attribute_facade.h>
-#include <ace/Request.h>
-#include <simple_roaming_agent.h>
-
-namespace // anonymous
-{
-typedef std::list<std::string> AttributeHandlerResponse;
-
-typedef AttributeHandlerResponse (*AttributeHandler)(
-    const WidgetExecutionPhase &phase,
-    const WidgetHandle &widgetHandle);
-typedef AttributeHandlerResponse (*ResourceAttributeHandler)(
-    const WidgetExecutionPhase &phase,
-    const WidgetHandle &widgetHandle,
-    const Request &request);
-
-AttributeHandlerResponse AttributeClassHandler(const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle & /*widgetHandle*/)
-{
-    AttributeHandlerResponse response;
-    response.push_back("widget");
-    return response;
-}
-
-AttributeHandlerResponse AttributeInstallUriHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    std::string value = AceDB::AceDAOReadOnly::getShareHref(widgetHandle);
-    if(!value.empty())
-        response.push_back(value);
-    return response;
-}
-
-AttributeHandlerResponse AttributeVersionHandler(const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-
-    std::string value = AceDB::AceDAOReadOnly::getVersion(widgetHandle);
-
-    if (!value.empty()) {
-        response.push_back(value);
-    }
-
-    return response;
-}
-
-AttributeHandlerResponse AttributeDistributorKeyCnHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
-        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
-    return response;
-}
-
-AttributeHandlerResponse AttributeDistributorKeyFingerprintHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
-        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
-    return response;
-}
-
-AttributeHandlerResponse AttributeDistributorKeyRootCnHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
-        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
-    return response;
-}
-
-AttributeHandlerResponse AttributeDistributorKeyRootFingerprintHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
-        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
-    return response;
-}
-
-AttributeHandlerResponse AttributeAuthorKeyCnHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
-        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
-    return response;
-}
-
-AttributeHandlerResponse AttributeAuthorKeyFingerprintHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
-        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
-    return response;
-}
-
-AttributeHandlerResponse AttributeAuthorKeyRootCnHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
-        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
-    return response;
-}
-
-AttributeHandlerResponse AttributeAuthorKeyRootFingerprintHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
-        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
-    return response;
-}
-
-AttributeHandlerResponse AttributeNetworkAccessUriHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle & /*widgetHandle*/)
-{
-    AttributeHandlerResponse response;
-    return response;
-}
-
-AttributeHandlerResponse AttributeIdHandler(const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-
-    std::string wGUID = AceDB::AceDAOReadOnly::getGUID(widgetHandle);
-
-    if (!wGUID.empty()) {
-        response.push_back(wGUID);
-    }
-    return response;
-}
-
-AttributeHandlerResponse AttributeAuthorNameHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle &widgetHandle)
-{
-    AttributeHandlerResponse response;
-
-    std::string value = AceDB::AceDAOReadOnly::getAuthorName(widgetHandle);
-
-    if (!value.empty()) {
-        response.push_back(value);
-    }
-
-    return response;
-}
-
-AttributeHandlerResponse AttributeRoamingHandler(
-        const WidgetExecutionPhase &phase,
-        const WidgetHandle & /*widgetHandle*/)
-{
-    AttributeHandlerResponse response;
-
-    if (WidgetExecutionPhase_WidgetInstall == phase) {
-        // TODO undetermind value
-        response.push_back(std::string(""));
-    } else if (SimpleRoamingAgentSingleton::Instance().IsRoamingOn()) {
-        response.push_back(std::string("true"));
-    } else {
-        response.push_back(std::string("false"));
-    }
-
-    return response;
-}
-
-AttributeHandlerResponse AttributeBearerTypeHandler(
-        const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle & /*widgetHandle*/)
-{
-    AttributeHandlerResponse response;
-
-    std::string bearerName = "undefined-bearer-name";
-
-    if (bearerName.empty()) {
-        LogWarning("Bearer-type is NOT SET or empty");
-    } else {
-        response.push_back(bearerName);
-    }
-
-    return response;
-}
-
-struct AttributeHandlerContext
-{
-    std::string name;
-    WidgetExecutionPhase allowedPhaseMask;
-    AttributeHandler handler;
-};
-
-// Private masks
-const WidgetExecutionPhase WidgetExecutionPhase_All =
-    static_cast<WidgetExecutionPhase>(
-        WidgetExecutionPhase_WidgetInstall |
-        WidgetExecutionPhase_WidgetInstantiate |
-        WidgetExecutionPhase_WebkitBind |
-        WidgetExecutionPhase_Invoke);
-const WidgetExecutionPhase WidgetExecutionPhase_NoWidgetInstall =
-    static_cast<WidgetExecutionPhase>(
-        WidgetExecutionPhase_WidgetInstantiate |
-        WidgetExecutionPhase_WebkitBind |
-        WidgetExecutionPhase_Invoke);
-
-#define ALL_PHASE(name, handler) \
-    { # name, WidgetExecutionPhase_All, handler },
-
-#define NO_INSTALL(name, handler) \
-    { # name, WidgetExecutionPhase_NoWidgetInstall, handler },
-
-AttributeHandlerContext HANDLED_ATTRIBUTES_LIST[] = {
-    ALL_PHASE(Class, &AttributeClassHandler)
-    ALL_PHASE(install-uri, &AttributeInstallUriHandler)
-    ALL_PHASE(version, &AttributeVersionHandler)
-    ALL_PHASE(distributor-key-cn, &AttributeDistributorKeyCnHandler)
-    ALL_PHASE(distributor-key-fingerprint,
-              &AttributeDistributorKeyFingerprintHandler)
-    ALL_PHASE(distributor-key-root-cn,
-              &AttributeDistributorKeyRootCnHandler)
-    ALL_PHASE(distributor-key-root-fingerprint,
-              &AttributeDistributorKeyRootFingerprintHandler)
-    ALL_PHASE(author-key-cn, &AttributeAuthorKeyCnHandler)
-    ALL_PHASE(author-key-fingerprint, &AttributeAuthorKeyFingerprintHandler)
-    ALL_PHASE(author-key-root-cn, &AttributeAuthorKeyRootCnHandler)
-    ALL_PHASE(author-key-root-fingerprint,
-              &AttributeAuthorKeyRootFingerprintHandler)
-    ALL_PHASE(network-access-uri, &AttributeNetworkAccessUriHandler)
-    ALL_PHASE(id, &AttributeIdHandler)
-//    ALL_PHASE(name, &AttributeNameHandler)
-//    ALL_PHASE(widget-attr:name, &AttributeWidgetAttrNameHandler)
-    ALL_PHASE(author-name, &AttributeAuthorNameHandler)
-    /* Enviroment  attributes*/
-    NO_INSTALL(roaming, &AttributeRoamingHandler)
-    NO_INSTALL(bearer-type, &AttributeBearerTypeHandler)
-};
-
-#undef ALL_PHASE
-#undef NO_INSTALL
-
-const size_t HANDLED_ATTRIBUTES_LIST_COUNT =
-    sizeof(HANDLED_ATTRIBUTES_LIST) / sizeof(HANDLED_ATTRIBUTES_LIST[0]);
-
-template<class T>
-class lambdaCollectionPusher
-{
-  public:
-    std::list<T>& m_collection;
-    lambdaCollectionPusher(std::list<T>& collection) : m_collection(collection)
-    {
-    }
-    void operator()(const T& element) const
-    {
-        m_collection.push_back(element);
-    }
-};
-
-AttributeHandlerResponse AttributeDeviceCapHandler(const WidgetExecutionPhase & /*phase*/,
-        const WidgetHandle & /*widgetHandle*/,
-        const Request &request)
-{
-    AttributeHandlerResponse response;
-
-    Request::DeviceCapabilitySet capSet = request.getDeviceCapabilitySet();
-    LogDebug("device caps set contains");
-    FOREACH(dc, capSet)
-    {
-        LogDebug("-> " << *dc);
-    }
-
-    std::for_each(
-        capSet.begin(),
-        capSet.end(),
-        lambdaCollectionPusher<std::string>(response));
-
-    return response;
-}
-
-//class lambdaFeatureEquality :
-//    public std::binary_function<FeatureHandle, int, bool>
-//{
-//  public:
-//    bool operator()(const FeatureHandle& wFeature,
-//            const int& resurceId) const
-//    {
-//        return wFeature == resurceId;
-//    }
-//};
-//
-//class lambdaPushFeatureName :
-//    public std::binary_function<WidgetFeature, AttributeHandlerResponse, void>
-//{
-//    void operator()(const WidgetFeature& wFeature,
-//            AttributeHandlerResponse& response) const
-//    {
-//        response.push_back(DPL::ToUTF8String(wFeature.name));
-//    }
-//};
-
-AttributeHandlerResponse AttributeApiFeatureHandler(
-        const WidgetExecutionPhase & /* phase */,
-        const WidgetHandle & /* widgetHandle */,
-        const Request & /* request */)
-{
-    LogDebug("WAC 2.0 does not support api-feature and resource-id in policy.");
-    AttributeHandlerResponse response;
-    return response;
-}
-
-AttributeHandlerResponse AttributeFeatureInstallUriHandler(
-        const WidgetExecutionPhase & /* phase */,
-        const WidgetHandle & /* widgetHandle */,
-        const Request & /* request */)
-{
-    LogDebug("WAC 2.0 does not support feature-install-uri is policy!");
-    AttributeHandlerResponse response;
-    return response;
-}
-
-AttributeHandlerResponse AttributeFeatureFeatureKeyCnHandler(
-        const WidgetExecutionPhase & /* phase */,
-        const WidgetHandle & /* widgetHandle */,
-        const Request & /* request */)
-{
-    LogDebug("WAC 2.0 does not support feature-key-cn is policy!");
-    AttributeHandlerResponse response;
-    return response;
-}
-
-AttributeHandlerResponse AttributeFeatureKeyRootCnHandler(
-        const WidgetExecutionPhase & /* phase */,
-        const WidgetHandle & /* widgetHandle */,
-        const Request & /* request */)
-{
-    LogDebug("WAC 2.0 does not support feature-key-root-cn is policy!");
-    AttributeHandlerResponse response;
-    return response;
-}
-
-AttributeHandlerResponse AttributeFeatureKeyRootFingerprintHandler(
-        const WidgetExecutionPhase & /* phase */,
-        const WidgetHandle & /* widgetHandle */,
-        const Request & /* request */)
-{
-    LogDebug("WAC 2.0 does not support"
-        " feature-key-root-fingerprint is policy!");
-    AttributeHandlerResponse response;
-    return response;
-}
-
-struct ResourceAttributeHandlerContext
-{
-    std::string name;
-    WidgetExecutionPhase allowedPhaseMask;
-    ResourceAttributeHandler handler;
-};
-
-#define ALL_PHASE(name, handler) \
-    { # name, WidgetExecutionPhase_All, handler },
-
-ResourceAttributeHandlerContext HANDLED_RESOURCE_ATTRIBUTES_LIST[] = {
-    ALL_PHASE(device-cap, &AttributeDeviceCapHandler)
-    ALL_PHASE(api-feature, &AttributeApiFeatureHandler)
-    // For compatiblity with older policies we tread resource-id
-    // identically as api-feature
-    ALL_PHASE(resource-id, &AttributeApiFeatureHandler)
-
-    ALL_PHASE(feature-install-uri, &AttributeFeatureInstallUriHandler)
-    ALL_PHASE(feature-key-cn, &AttributeFeatureFeatureKeyCnHandler)
-    ALL_PHASE(feature-key-root-cn, &AttributeFeatureKeyRootCnHandler)
-    ALL_PHASE(feature-key-root-fingerprint,
-              &AttributeFeatureKeyRootFingerprintHandler)
-};
-
-#undef ALL_PHASE
-
-const size_t HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT =
-    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST) /
-    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST[0]);
-} // namespace anonymous
-
-/*
- * class WebRuntimeImpl
- */
-int WebRuntimeImpl::getAttributesValuesLoop(const Request &request,
-        std::list<ATTRIBUTE>* attributes,
-        WidgetExecutionPhase executionPhase)
-{
-    UNHANDLED_EXCEPTION_HANDLER_BEGIN
-    {
-        WidgetHandle widgetHandle = request.getWidgetHandle();
-
-        FOREACH(itr, *attributes)
-        {
-            // Get attribute name
-            std::string attribute = *itr->first;
-
-            // Search for attribute handler
-            bool attributeFound = false;
-
-            for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
-                if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
-                    // Check if execution phase is valid
-                    if ((executionPhase &
-                         HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
-                        // Attribute found, but execution state
-                        // forbids to execute handler
-                        LogWarning(
-                            "Request for attribute: '" <<
-                            attribute << "' which is supported " <<
-                            "but forbidden at widget execution phase: "
-                            <<
-                            executionPhase);
-                    } else {
-                        // Execution phase allows handler
-                        AttributeHandlerResponse attributeResponse =
-                            (*HANDLED_ATTRIBUTES_LIST[i].handler)(
-                                executionPhase,
-                                widgetHandle);
-                        std::copy(attributeResponse.begin(),
-                                  attributeResponse.end(),
-                                  std::back_inserter(*itr->second));
-                    }
-
-                    attributeFound = true;
-                    break;
-                }
-            }
-
-            if (!attributeFound) {
-                LogWarning("Request for attribute: '" <<
-                           attribute << "' which is not supported");
-            }
-        }
-
-        return 0;
-    }
-    UNHANDLED_EXCEPTION_HANDLER_END
-}
-
-int WebRuntimeImpl::getAttributesValues(const Request &request,
-        std::list<ATTRIBUTE>* attributes)
-{
-    UNHANDLED_EXCEPTION_HANDLER_BEGIN
-    {
-        // Get current execution state
-        WidgetExecutionPhase executionPhase =
-            request.getExecutionPhase();
-
-        return getAttributesValuesLoop(request, attributes, executionPhase);
-    }
-    UNHANDLED_EXCEPTION_HANDLER_END
-}
-
-std::string WebRuntimeImpl::getSessionId(const Request & /* request */)
-{
-    std::string result;
-    LogError("Not implemented!");
-    return result;
-}
-
-WebRuntimeImpl::WebRuntimeImpl()
-{
-}
-
-/*
- * class ResourceInformationImpl
- */
-
-int ResourceInformationImpl::getAttributesValuesLoop(const Request &request,
-        std::list<ATTRIBUTE>* attributes,
-        WidgetExecutionPhase executionPhase)
-{
-    // Currently, we assume widgets have internal representation of integer IDs
-    WidgetHandle widgetHandle = request.getWidgetHandle();
-    //TODO add resource id string analyzys
-    FOREACH(itr, *attributes)
-    {
-        // Get attribute name
-        std::string attribute = *itr->first;
-        LogDebug("getting attribute value for: " << attribute);
-        FOREACH(aaa, *itr->second)
-        {
-            LogDebug("its value is: " << *aaa);
-        }
-
-        // Search for attribute handler
-        bool attributeFound = false;
-
-        for (size_t i = 0; i < HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT; ++i) {
-            if (HANDLED_RESOURCE_ATTRIBUTES_LIST[i].name == attribute) {
-                // Check if execution phase is valid
-                if ((executionPhase &
-                     HANDLED_RESOURCE_ATTRIBUTES_LIST[i].allowedPhaseMask) ==
-                    0) {
-                    // Attribute found, but execution state
-                    // forbids to execute handler
-                    LogDebug(
-                        "Request for attribute: '" <<
-                        attribute <<
-                        "' which is supported but forbidden " <<
-                        "at widget execution phase: " << executionPhase);
-                    itr->second = NULL;
-                } else {
-                    // Execution phase allows handler
-                    AttributeHandlerResponse attributeResponse =
-                        (*HANDLED_RESOURCE_ATTRIBUTES_LIST[i].handler)(
-                            executionPhase,
-                            widgetHandle,
-                            request);
-                    std::copy(attributeResponse.begin(),
-                              attributeResponse.end(),
-                              std::back_inserter(*itr->second));
-
-                    std::ostringstream attributeResponseFull;
-
-                    for (AttributeHandlerResponse::const_iterator
-                         it = attributeResponse.begin();
-                         it != attributeResponse.end(); ++it) {
-                        attributeResponseFull <<
-                        (it == attributeResponse.begin() ? "" : ", ") <<
-                        *it;
-                    }
-
-                    LogDebug("Attribute(" << attribute << ") = " <<
-                             attributeResponseFull.str());
-                }
-
-                attributeFound = true;
-                break;
-            }
-        }
-
-        if (!attributeFound) {
-            LogWarning("Request for attribute: '" << attribute <<
-                       "' which is not supported");
-        }
-    }
-    return 0;
-}
-
-int ResourceInformationImpl::getAttributesValues(const Request &request,
-        std::list<ATTRIBUTE>* attributes)
-{
-    UNHANDLED_EXCEPTION_HANDLER_BEGIN
-    {
-        // Get current execution state
-        WidgetExecutionPhase executionPhase =
-            request.getExecutionPhase();
-        return getAttributesValuesLoop(request, attributes, executionPhase);
-    }
-    UNHANDLED_EXCEPTION_HANDLER_END
-}
-
-ResourceInformationImpl::ResourceInformationImpl()
-{
-}
-
-/*
- * class OperationSystemImpl
- */
-
-int OperationSystemImpl::getAttributesValues(const Request &request,
-        std::list<ATTRIBUTE>* attributes)
-{
-    UNHANDLED_EXCEPTION_HANDLER_BEGIN
-    {
-        //FIXME:
-        //GetExecution name without widget name
-        WidgetExecutionPhase executionPhase =
-            request.getExecutionPhase();
-
-        FOREACH(itr, *attributes)
-        {
-            // Get attribute name
-            std::string attribute = *itr->first;
-
-            // Search for attribute handler
-            bool attributeFound = false;
-
-            for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
-                if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
-                    // Check if execution phase is valid
-                    if ((executionPhase &
-                         HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
-                        // Attribute found, but execution state forbids
-                        // to execute handler
-                        LogDebug("Request for attribute: '" << attribute <<
-                                 "' which is supported but forbidden at " <<
-                                 "widget execution phase: " << executionPhase);
-                        itr->second = NULL;
-                    } else {
-                        // Execution phase allows handler
-                        AttributeHandlerResponse attributeResponse =
-                            (*HANDLED_ATTRIBUTES_LIST[i].handler)(
-                                executionPhase,
-                                0);
-                        std::copy(attributeResponse.begin(),
-                                  attributeResponse.end(),
-                                  std::back_inserter(*itr->second));
-
-                        std::ostringstream attributeResponseFull;
-
-                        typedef AttributeHandlerResponse::const_iterator Iter;
-                        FOREACH(it, attributeResponse)
-                        {
-                            attributeResponseFull <<
-                            (it == attributeResponse.begin()
-                             ? "" : ", ") << *it;
-                        }
-
-                        LogDebug("Attribute(" << attribute <<
-                                 ") = " << attributeResponseFull.str());
-                    }
-
-                    attributeFound = true;
-                    break;
-                }
-            }
-
-            if (!attributeFound) {
-                LogWarning("Request for attribute: '" << attribute <<
-                           "' which is not supported");
-            }
-        }
-
-        return 0;
-    }
-    UNHANDLED_EXCEPTION_HANDLER_END
-}
-
-OperationSystemImpl::OperationSystemImpl()
-{
-}
-
-/*
- * end of class OperationSystemImpl
- */
-
-int FunctionParamImpl::getAttributesValues(const Request & /*request*/,
-        std::list<ATTRIBUTE> *attributes)
-{
-    FOREACH(iter, *attributes)
-    {
-        std::string attributeName = *(iter->first);
-
-        ParamMap::const_iterator i;
-        std::pair<ParamMap::const_iterator, ParamMap::const_iterator> jj =
-            paramMap.equal_range(attributeName);
-
-        for (i = jj.first; i != jj.second; ++i) {
-            iter->second->push_back(i->second);
-            LogDebug("Attribute: " << attributeName << " Value: " <<
-                     i->second);
-        }
-    }
-    return 0;
-}
diff --git a/src/services/ace/logic/attribute_facade.h b/src/services/ace/logic/attribute_facade.h
deleted file mode 100644 (file)
index 7b6898c..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file    attribute_facade.h
- * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version 1.0
- * @brief   This file contains the declaration of WebRuntimeImpl,
- *          ResourceInformationImpl, OperationSystemImpl
- */
-
-#ifndef ATTRIBUTE_FACADE_H
-#define ATTRIBUTE_FACADE_H
-
-#include <string>
-#include <map>
-#include <vector>
-
-#include <ace/WRT_INTERFACE.h>
-
-class Request;
-
-class WebRuntimeImpl : public IWebRuntime
-{
-  public:
-    // Return current sessionId
-    int getAttributesValuesLoop(const Request &request,
-            std::list<ATTRIBUTE>* attributes,
-            WidgetExecutionPhase executionPhase);
-
-    int getAttributesValues(const Request &request,
-            std::list<ATTRIBUTE>* attributes);
-    virtual std::string getSessionId(const Request &request);
-    WebRuntimeImpl();
-};
-
-class ResourceInformationImpl : public IResourceInformation
-{
-  public:
-    int getAttributesValuesLoop(const Request &request,
-            std::list<ATTRIBUTE>* attributes,
-            WidgetExecutionPhase executionPhase);
-    int getAttributesValues(const Request &request,
-            std::list<ATTRIBUTE>* attributes);
-    ResourceInformationImpl();
-};
-
-class OperationSystemImpl : public IOperationSystem
-{
-  public:
-    /**
-     * gather and set attributes values for specified attribute name
-     * @param attributes is a list of pairs(
-     *   first:   pointer to attribute name
-     *   second: list of values for attribute (std::string)  -
-     *   its a list of string (BONDI requirement), but usually there
-     *   will be only one string
-     */
-    int getAttributesValues(const Request &request,
-            std::list<ATTRIBUTE>* attributes);
-    OperationSystemImpl();
-};
-
-class FunctionParamImpl : public IFunctionParam
-{
-  public:
-    virtual int getAttributesValues(const Request & /*request*/,
-            std::list<ATTRIBUTE> *attributes);
-    void addAttribute(const std::string &key,
-            const std::string &value)
-    {
-        paramMap.insert(make_pair(key, value));
-    }
-    virtual ~FunctionParamImpl()
-    {
-    }
-
-  private:
-    typedef std::multimap<std::string, std::string> ParamMap;
-    ParamMap paramMap;
-};
-
-typedef std::vector <FunctionParamImpl> FunctionParams;
-
-#endif //ATTRIBUTE_FACADE_H
diff --git a/src/services/ace/logic/security_controller.cpp b/src/services/ace/logic/security_controller.cpp
deleted file mode 100644 (file)
index 32d9b4b..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * This class simply redirects the access requests to access control engine.
- * The aim is to hide access control engine specific details from WRT modules.
- * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
- * WRT specific and other information during the decision making.
- *
- * @file    security_controller.cpp
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @author  Ming Jin(ming79.jin@samsung.com)
- * @version 1.0
- * @brief   Implementation file for security controller
- */
-#include <security_controller.h>
-#include <ace/PolicyEnforcementPoint.h>
-#include <ace/WRT_INTERFACE.h>
-//#include <engine/PolicyEvaluatorFactory.h>
-//#include <logic/attribute_facade.h>
-#include <dpl/singleton_impl.h>
-#include <dpl/log/log.h>
-#include <security_logic.h>
-#include <security_caller.h>
-
-IMPLEMENT_SINGLETON(SecurityController)
-
-struct SecurityController::Impl
-{
-    SecurityLogic logic;
-};
-
-SecurityController::SecurityController()
-{
-    m_impl.Reset(new Impl);
-}
-
-SecurityController::~SecurityController()
-{
-}
-
-void SecurityController::OnEventReceived(
-    const SecurityControllerEvents::InitializeSyncEvent & /* event */)
-{
-    SecurityCallerSingleton::Instance().Run();
-    m_impl->logic.initialize();
-}
-
-void SecurityController::OnEventReceived(
-        const SecurityControllerEvents::UpdatePolicySyncEvent& /* event */)
-{
-    m_impl->logic.updatePolicy();
-}
-
-void SecurityController::OnEventReceived(
-    const SecurityControllerEvents::TerminateSyncEvent & /*event*/)
-{
-    SecurityCallerSingleton::Instance().Quit();
-    m_impl->logic.terminate();
-}
-
-void SecurityController::OnEventReceived(
-    const SecurityControllerEvents::CheckFunctionCallSyncEvent &ev)
-{
-    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1());
-}
-
-void SecurityController::OnEventReceived(
-    const SecurityControllerEvents::CheckRuntimeCallSyncEvent &ev)
-{
-    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1(), ev.GetArg2());
-}
-
-void SecurityController::OnEventReceived(
-           const SecurityControllerEvents::ValidatePopupResponseEvent &ev)
-{
-    m_impl->logic.validatePopupResponse(ev.GetArg0(),
-                                        ev.GetArg1(),
-                                        ev.GetArg2(),
-                                        ev.GetArg3(),
-                                        ev.GetArg4());
-}
diff --git a/src/services/ace/logic/security_controller.h b/src/services/ace/logic/security_controller.h
deleted file mode 100644 (file)
index 68df770..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * This class simply redirects the access requests to access control engine.
- * The aim is to hide access control engine specific details from WRT modules.
- * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
- * WRT specific and other information during the decision making.
- *
- * @file    security_controller.h
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @author  Ming Jin(ming79.jin@samsung.com)
- * @version 1.0
- * @brief   Header file for security controller
- */
-#ifndef SECURITY_CONTROLLER_H
-#define SECURITY_CONTROLLER_H
-
-#include <dpl/singleton.h>
-#include <dpl/event/controller.h>
-#include <dpl/generic_event.h>
-#include <dpl/scoped_ptr.h>
-#include <dpl/type_list.h>
-#include <string>
-#include <ace-dao-ro/PreferenceTypes.h>
-#include <ace/AbstractPolicyEnforcementPoint.h>
-#include <ace-dao-ro/PromptModel.h>
-#include <string>
-#include <dpl/event/inter_context_delegate.h>
-
-namespace Jobs {
-class Job;
-}
-
-namespace SecurityControllerEvents {
-DECLARE_GENERIC_EVENT_0(InitializeSyncEvent)
-DECLARE_GENERIC_EVENT_0(TerminateSyncEvent)
-DECLARE_GENERIC_EVENT_0(UpdatePolicySyncEvent)
-
-DECLARE_GENERIC_EVENT_2(CheckFunctionCallSyncEvent,
-                        PolicyResult *,
-                        Request *
-                       )
-
-DECLARE_GENERIC_EVENT_3(CheckRuntimeCallSyncEvent,
-                        PolicyResult *,
-                        Request *,
-                        std::string //sessionId
-                       )
-
-DECLARE_GENERIC_EVENT_5(ValidatePopupResponseEvent,
-                        Request *,
-                        bool, //is allowed
-                        Prompt::Validity,
-                        std::string, //sessionId
-                        bool* //check return value
-                       )
-
-} // namespace SecurityControllerEvents
-
-typedef DPL::TypeListDecl<
-    SecurityControllerEvents::InitializeSyncEvent,
-    SecurityControllerEvents::TerminateSyncEvent,
-    SecurityControllerEvents::UpdatePolicySyncEvent,
-    SecurityControllerEvents::ValidatePopupResponseEvent,
-    SecurityControllerEvents::CheckRuntimeCallSyncEvent,
-    SecurityControllerEvents::CheckFunctionCallSyncEvent>::Type
-SecurityControllerEventsTypeList;
-
-class SecurityController :
-        public DPL::Event::Controller<SecurityControllerEventsTypeList>
-{
-  protected:
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::InitializeSyncEvent &event);
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::UpdatePolicySyncEvent &event);
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::ValidatePopupResponseEvent &e);
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::TerminateSyncEvent &event);
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::CheckFunctionCallSyncEvent &e);
-    virtual void OnEventReceived(
-            const SecurityControllerEvents::CheckRuntimeCallSyncEvent &e);
-
-  private:
-    class Impl;
-    DPL::ScopedPtr<Impl> m_impl;
-
-    SecurityController();
-    //This desctructor must be in implementation file (cannot be autogenerated)
-    ~SecurityController();
-
-    friend class DPL::Singleton<SecurityController>;
-};
-
-typedef DPL::Singleton<SecurityController> SecurityControllerSingleton;
-
-#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/security_logic.cpp b/src/services/ace/logic/security_logic.cpp
deleted file mode 100644 (file)
index 48d7f8e..0000000
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * This class simply redirects the access requests to access control engine.
- * The aim is to hide access control engine specific details from WRT modules.
- * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
- * WRT specific and other information during the decision making.
- *
- * @file    security_controller.h
- # @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @author  Ming Jin(ming79.jin@samsung.com)
- * @author  Piotr Kozbial (p.kozbial@samsung.com)
- * @version 1.0
- * @brief   Header file for security logic
- */
-
-#include <security_logic.h>
-#include <attribute_facade.h>
-#ifdef WRT_SMACK_ENABLED
-#include <privilege-control.h>
-#endif
-#include <ace-dao-rw/AceDAO.h>
-#include <ace-dao-ro/AceDAOConversions.h>
-#include <ace/PolicyInformationPoint.h>
-#include <ace/PromptDecision.h>
-#include <dpl/log/log.h>
-
-namespace {
-
-Request::ApplicationType getAppType(const Request *request) {
-    AceDB::AppTypes appType =
-        AceDB::AceDAOReadOnly::getWidgetType(request->getWidgetHandle());
-    switch (appType) {
-    case AceDB::AppTypes::Tizen:
-        LogDebug("==== Found Tizen application. ====");
-        return Request::APP_TYPE_TIZEN;
-    case AceDB::AppTypes::WAC20:
-        LogDebug("==== Found Wac20 application. ====");
-        return Request::APP_TYPE_WAC20;
-    default:
-        LogDebug("==== Unknown application type. ====");
-    }
-    return Request::APP_TYPE_UNKNOWN;
-}
-
-} // anonymous namespace
-
-void SecurityLogic::initialize() {
-    AceDB::AceDAO::attachToThreadRW();
-    m_policyEnforcementPoint.initialize(new WebRuntimeImpl(),
-                                        new ResourceInformationImpl(),
-                                        new OperationSystemImpl());
-}
-
-void SecurityLogic::terminate() {
-    m_policyEnforcementPoint.terminate();
-    AceDB::AceDAO::detachFromThread();
-}
-
-
-void SecurityLogic::grantPlatformAccess(const Request& request)
-{
-    (void)request;
-#ifdef WRT_SMACK_ENABLED
-    try {
-        unsigned long long id =
-            static_cast<unsigned long long>(request.getWidgetHandle());
-        Request::DeviceCapabilitySet dc = request.getDeviceCapabilitySet();
-
-        size_t i,size = dc.size();
-        std::unique_ptr<const char*[]> array(new const char*[size+1]);
-
-        array[size] = NULL;
-        auto it = dc.begin();
-
-        for(i=0; (i<size) && (it!=dc.end()); ++i,++it) {
-            array[i] = it->c_str();
-        }
-        int ret = wrt_permissions_add(id, array.get());
-        if (PC_OPERATION_SUCCESS != ret) {
-            LogError("smack rules couldn't be granted");
-        }
-    } catch (std::bad_alloc&) {
-        LogError("smack rules couldn't be granted: memory allocation failed");
-    }
-#endif
-}
-
-PolicyResult SecurityLogic::checkFunctionCall(Request* request)
-{
-    Assert(NULL != request);
-
-    LogDebug("=== Check widget existance ===");
-    Try {
-        request->setAppType(getAppType(request));
-    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
-        LogError("==== Couldn't find widget for handle: " <<
-            request->getWidgetHandle() << ". Access denied. ====");
-        return PolicyEffect::DENY;
-    }
-
-    PolicyResult aceResult = m_policyEnforcementPoint.check(*request).policyResult;
-
-    if (aceResult == PolicyEffect::PERMIT) {
-        grantPlatformAccess(*request);
-        return PolicyEffect::PERMIT;
-    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
-               aceResult == PolicyEffect::PROMPT_SESSION ||
-               aceResult == PolicyEffect::PROMPT_BLANKET ||
-               aceResult == PolicyDecision::NOT_APPLICABLE ||
-               aceResult == PolicyResult::UNDETERMINED)
-    {
-        // TODO: check stored user answers!!!
-        // if necessary, grant SMACK rules
-        // return appropriately - the following is a dummy:
-        return aceResult;
-    } else {
-        return PolicyEffect::DENY;
-    }
-}
-
-PolicyResult SecurityLogic::checkFunctionCall(Request* request, const std::string &sessionId)
-{
-    Assert(NULL != request);
-    LogDebug("=== Check existance of widget === ");
-    Try {
-        request->setAppType(getAppType(request));
-    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
-        LogError("==== Couldn't find widget for handle: " <<
-            request->getWidgetHandle() << ". Access denied. ====");
-        return PolicyEffect::DENY;
-    }
-
-    ExtendedPolicyResult exAceResult = m_policyEnforcementPoint.check(*request);
-    PolicyResult aceResult = exAceResult.policyResult;
-
-    LogDebug("Result returned by policy " << aceResult << ". RuleID: " << exAceResult.ruleId);
-
-    if (aceResult == PolicyEffect::PERMIT) {
-        LogDebug("Grant access.");
-        grantPlatformAccess(*request);
-        return PolicyEffect::PERMIT;
-    }
-
-    if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
-        aceResult == PolicyEffect::DENY)
-    {
-        return aceResult;
-    }
-
-    OptionalCachedPromptDecision decision = AceDB::AceDAOReadOnly::getPromptDecision(
-        request->getWidgetHandle(),
-        exAceResult.ruleId);
-
-    if (decision.IsNull()) {
-        LogDebug("No CachedPromptDecision found.");
-        return aceResult;
-    }
-
-    if (aceResult == PolicyEffect::PROMPT_BLANKET) {
-        if (decision->decision == PromptDecision::ALLOW_ALWAYS) {
-            LogDebug("Found user decision. Result changed to PERMIT. Access granted");
-            grantPlatformAccess(*request);
-            return PolicyEffect::PERMIT;
-        }
-        if (decision->decision == PromptDecision::DENY_ALWAYS) {
-            LogDebug("Found user decision. Result changed to DENY.");
-            return PolicyEffect::DENY;
-        }
-        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
-            && !(decision->session.IsNull())
-            && sessionId == DPL::ToUTF8String(*(decision->session)))
-        {
-            LogDebug("Result changed to PERMIT. Access granted.");
-            grantPlatformAccess(*request);
-            return PolicyEffect::PERMIT;
-        }
-        if (decision->decision == PromptDecision::DENY_FOR_SESSION
-            && !(decision->session.IsNull())
-            && sessionId == DPL::ToUTF8String(*(decision->session)))
-        {
-            LogDebug("Found user decision. Result changed to DENY.");
-            return PolicyEffect::DENY;
-        }
-        return aceResult;
-    }
-
-    if (aceResult == PolicyEffect::PROMPT_SESSION) {
-        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
-            && !(decision->session.IsNull())
-            && sessionId == DPL::ToUTF8String(*(decision->session)))
-        {
-            LogDebug("Found user decision. Result changed to PERMIT. Access granted.");
-            grantPlatformAccess(*request);
-            return PolicyEffect::PERMIT;
-        }
-        if (decision->decision == PromptDecision::DENY_FOR_SESSION
-            && !(decision->session.IsNull())
-            && sessionId == DPL::ToUTF8String(*(decision->session)))
-        {
-            LogDebug("Found user decision. Result changed to DENY.");
-            return PolicyEffect::DENY;
-        }
-        return aceResult;
-    }
-
-    // This should not happend - all PolicyEffect values were supported before.
-    // This mean that someone has modyfied PolicyEffect enum. SPANK SPANK SPANK
-    LogError("Unsupported PolicyEffect!");
-    return PolicyEffect::DENY;
-}
-
-void SecurityLogic::validatePopupResponse(Request* request,
-                                          bool allowed,
-                                          Prompt::Validity validity,
-                                          const std::string& sessionId,
-                                          bool* retValue)
-{
-    Assert(NULL != retValue);
-    Assert(NULL != request);
-
-    LogDebug("Start");
-    LogDebug("User answered: " << allowed << " with validity: " << validity);
-    LogDebug("Check widget existance");
-    Try {
-        request->setAppType(getAppType(request));
-    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
-        LogError("==== Couldn't find widget for handle: " <<
-            request->getWidgetHandle() << ". Access denied. ====");
-        retValue = false;
-        return;
-    }
-
-    *retValue = false;
-    OptionalExtendedPolicyResult extendedAceResult =
-        m_policyEnforcementPoint.checkFromCache(*request);
-    if (extendedAceResult.IsNull()) {
-        LogDebug("No cached policy result - but it should be here");
-        LogDebug("returning " << *retValue);
-        return;
-    }
-
-    PolicyResult aceResult = extendedAceResult->policyResult;
-    if (aceResult == PolicyEffect::DENY) {
-        LogDebug("returning " << *retValue);
-        return;
-    }
-    if (aceResult == PolicyEffect::PERMIT) {
-        // TODO  we were asked for prompt validation
-        // but we got that no prompt should be opened - is this OK?
-        // (this is on the diagram in wiki)
-        *retValue = true;
-    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
-               aceResult == PolicyEffect::PROMPT_SESSION ||
-               aceResult == PolicyEffect::PROMPT_BLANKET)
-    {
-        Request::DeviceCapabilitySet devCaps =
-                request->getDeviceCapabilitySet();
-
-        FOREACH (it, devCaps) {
-            Request::DeviceCapability resourceId = *it;
-            LogDebug("Recheck: " << *it);
-            // 1) check if per-widget settings permit
-            AceDB::PreferenceTypes wgtPref =
-                AceDB::AceDAOReadOnly::getWidgetDevCapSetting(
-                    resourceId,
-                    request->getWidgetHandle());
-            if (AceDB::PreferenceTypes::PREFERENCE_DENY == wgtPref) {
-                LogDebug("returning " << *retValue);
-                return;
-            }
-            // 2) check if per-dev-cap settings permit
-            AceDB::PreferenceTypes resPerf =
-                AceDB::AceDAOReadOnly::getDevCapSetting(resourceId);
-            if (AceDB::PreferenceTypes::PREFERENCE_DENY == resPerf) {
-                LogDebug("returning " << *retValue);
-                return;
-            }
-
-            // 3) check for stored propmt answer - should not be there
-            // TODO  - is this check necessary?
-            AceDB::BaseAttributeSet attributes;
-            AceDB::AceDAOReadOnly::getAttributes(&attributes);
-            Request req(request->getWidgetHandle(),
-                        request->getExecutionPhase());
-            req.addDeviceCapability(resourceId);
-            PolicyInformationPoint *pip =
-                m_policyEnforcementPoint.getPip();
-
-            Assert(NULL != pip);
-
-            pip->getAttributesValues(&req, &attributes);
-            auto attrHash = AceDB::AceDaoConversions::convertToHash(attributes);
-
-            // 4) validate consistency of answer with policy result
-            Prompt::Validity clampedValidity =
-                    clampPromptValidity(validity, *(aceResult.getEffect()));
-
-            // 5) store answer in database if appropriate
-            // TODO  how about userParam? sessionId?
-            DPL::String userParam = DPL::FromUTF8String(sessionId);
-            DPL::OptionalString sessionOptional =
-                DPL::FromUTF8String(sessionId);
-
-            switch (clampedValidity) {
-            case Prompt::Validity::ALWAYS: {
-                AceDB::AceDAO::setPromptDecision(
-                    request->getWidgetHandle(),
-                    extendedAceResult->ruleId,
-                    sessionOptional,
-                    allowed ?
-                    PromptDecision::ALLOW_ALWAYS :
-                    PromptDecision::DENY_ALWAYS);
-                break; }
-            case Prompt::Validity::SESSION: {
-                AceDB::AceDAO::setPromptDecision(
-                    request->getWidgetHandle(),
-                    extendedAceResult->ruleId,
-                    sessionOptional,
-                    allowed ?
-                    PromptDecision::ALLOW_FOR_SESSION :
-                    PromptDecision::DENY_FOR_SESSION);
-                break; }
-
-            case Prompt::Validity::ONCE: {
-                LogInfo("Validity ONCE, not saving prompt decision to cache");
-                break; }
-            }
-
-        }
-        // access granted!
-        *retValue = allowed;
-    }
-    if (*retValue) {
-        // 6) grant smack label if not granted yet
-        grantPlatformAccess(*request);
-    }
-    LogDebug("Finish");
-    LogDebug("returning " << *retValue);
-}
-
-void SecurityLogic::updatePolicy()
-{
-    LogDebug("SecurityLogic::updatePolicy");
-    m_policyEnforcementPoint.updatePolicy();
-}
-
-Prompt::Validity SecurityLogic::clampPromptValidity(
-        Prompt::Validity validity,
-        PolicyEffect effect)
-{
-    switch (effect) {
-    case PolicyEffect::PROMPT_BLANKET: {
-        return validity; }
-    case PolicyEffect::PROMPT_SESSION: {
-        if (Prompt::Validity::ALWAYS == validity) {
-            LogInfo("ALWAYS returned from prompt in PROMPT_SESSION");
-            return Prompt::Validity::SESSION;
-        }
-        return validity; }
-    case PolicyEffect::PROMPT_ONESHOT: {
-        if (Prompt::Validity::ONCE != validity) {
-            LogInfo("Not ONCE returned from prompt in PROMPT_ONESHOT");
-        }
-        return Prompt::Validity::ONCE; }
-    case PolicyEffect::DENY:
-    case PolicyEffect::PERMIT:
-    default: {// other options - should not happen
-        LogError("This kind of policy effect does not deal with prompts");
-        return Prompt::Validity::ONCE;  }
-    }
-}
-
diff --git a/src/services/ace/logic/security_logic.h b/src/services/ace/logic/security_logic.h
deleted file mode 100644 (file)
index 71f8bae..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * This class simply redirects the access requests to access control engine.
- * The aim is to hide access control engine specific details from WRT modules.
- * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
- * WRT specific and other information during the decision making.
- *
- * @file    security_controller.h
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @author  Ming Jin(ming79.jin@samsung.com)
- * @author  Piotr Kozbial (p.kozbial@samsung.com)
- * @version 1.0
- * @brief   Header file for security logic
- */
-#ifndef SECURITY_LOGIC_H
-#define SECURITY_LOGIC_H
-
-#include <ace/Request.h>
-#include <ace/PolicyResult.h>
-#include <ace/AbstractPolicyEnforcementPoint.h>
-#include <ace/Preference.h>
-#include <ace/PolicyEnforcementPoint.h>
-#include <ace-dao-ro/PromptModel.h>
-
-/* SecurityLogic
- * May only be created and used by SecurityController.
- * There may be only one instance.
- */
-class SecurityLogic {
-  public:
-    SecurityLogic() {}
-    ~SecurityLogic() {}
-    // initialize/terminate
-    /** */
-    void initialize();
-    /** */
-    void terminate();
-
-    /** */
-    PolicyResult checkFunctionCall(Request*);
-    PolicyResult checkFunctionCall(Request*, const std::string &session);
-
-    void validatePopupResponse(Request* request,
-                               bool allowed,
-                               Prompt::Validity validity,
-                               const std::string& sessionId,
-                               bool* retValue);
-
-    /**
-     * Updates policy and clears policy cache
-     */
-    void updatePolicy();
-
-  private:
-    PolicyEnforcementPoint m_policyEnforcementPoint;
-
-    Prompt::Validity clampPromptValidity(Prompt::Validity validity,
-                                         PolicyEffect effect);
-    void grantPlatformAccess(const Request& request);
-};
-
-#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/simple_roaming_agent.cpp b/src/services/ace/logic/simple_roaming_agent.cpp
deleted file mode 100644 (file)
index 19e2b39..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file    simple_roaming_agent.cpp
- * @author  Pawel Sikorski (p.sikorski@samsung.com)
- * @author  Lukasz Marek (l.marek@samsung.com)
- * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version 1.0
- * @brief   roaming agent
- */
-
-#include "simple_roaming_agent.h"
-#include <vconf.h>
-#include <dpl/fast_delegate.h>
-#include <dpl/log/log.h>
-#include <dpl/singleton_impl.h>
-IMPLEMENT_SINGLETON(SimpleRoamingAgent)
-
-SimpleRoamingAgent::SimpleRoamingAgent()
-{
-    if (vconf_notify_key_changed(
-            VCONFKEY_TELEPHONY_SVC_ROAM,
-            vConfChagedCallback, this) < 0)
-    {
-        LogError("Cannot add vconf callback [" <<
-                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
-        Assert(false && "Cannot add vconf callback");
-    }
-
-    int result = 0;
-    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
-        LogError("Cannot get current roaming status");
-        Assert(false && "Cannot get current roaming status");
-    } else {
-        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
-        m_networkType = type ? ROAMING : HOME;
-        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
-    }
-
-}
-
-SimpleRoamingAgent::~SimpleRoamingAgent()
-{
-    if (vconf_ignore_key_changed(
-            VCONFKEY_TELEPHONY_SVC_ROAM,
-            vConfChagedCallback) < 0)
-    {
-        LogError("Cannot rm vconf callback [" <<
-                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
-        Assert(false && "Cannot remove vconf callback");
-    }
-
-}
-
-void SimpleRoamingAgent::vConfChagedCallback(keynode_t *keyNode, void *data)
-{
-    LogInfo("SimpleRoamingAgent::vConfChagedCallback ");
-    char *key = vconf_keynode_get_name(keyNode);
-
-    if (NULL == key) {
-        LogWarning("vconf key is null.");
-        return;
-    }
-    std::string keyString = key;
-    if (VCONFKEY_TELEPHONY_SVC_ROAM != keyString) {
-        LogError("Wrong key found");
-        Assert(false && "Wrong key found in vconf callback");
-        return;
-    }
-    SimpleRoamingAgent *agent = static_cast<SimpleRoamingAgent *>(data);
-    if (NULL == agent) {
-        LogError("Bad user arg from vconf lib");
-        Assert(false && "Bad user arg from vconf lib");
-        return;
-    }
-    int result = 0;
-    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
-        LogError("Cannot get current roaming status");
-        Assert(false && "Cannot get current roaming status");
-    } else {
-        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
-        agent->m_networkType = type ? ROAMING : HOME;
-        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
-    }
-}
diff --git a/src/services/ace/logic/simple_roaming_agent.h b/src/services/ace/logic/simple_roaming_agent.h
deleted file mode 100644 (file)
index 65b0bbe..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file    simple_roaming_agent.h
- * @author  Pawel Sikorski (p.sikorski@samsung.com)
- * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version 1.0
- * @brief   simple roaming agent
- */
-
-#ifndef WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
-#define WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
-
-#include <string>
-#include <dpl/singleton.h>
-#include <dpl/noncopyable.h>
-#include <vconf.h>
-
-class SimpleRoamingAgent : DPL::Noncopyable
-{
-  public:
-    bool IsRoamingOn() const
-    {
-        return ROAMING == m_networkType;
-    }
-
-  private:
-    enum NetworkType {ROAMING, HOME};
-
-    NetworkType m_networkType;
-
-    SimpleRoamingAgent();
-    virtual ~SimpleRoamingAgent();
-
-    static void vConfChagedCallback(keynode_t *keyNode, void *userParam);
-
-    friend class DPL::Singleton<SimpleRoamingAgent>;
-};
-
-typedef DPL::Singleton<SimpleRoamingAgent> SimpleRoamingAgentSingleton;
-
-#endif//WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
diff --git a/src/services/ace/socket/ace_service_callbacks.cpp b/src/services/ace/socket/ace_service_callbacks.cpp
deleted file mode 100644 (file)
index ac3f6cf..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service_callbacks.cpp
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Implementation of Ace Service callbacks
- */
-#include <string>
-#include <vector>
-#include <dpl/log/log.h>
-#include "ace_service_callbacks.h"
-#include <callback_api.h>
-#include <ace/Request.h>
-#include <ace/PolicyResult.h>
-#include <security_controller.h>
-#include <security_caller.h>
-#include <attribute_facade.h>
-
-namespace RPC {
-
-void AceServiceCallbacks::checkAccess(SocketConnection * connector){
-
-    int widgetHandle = 0;
-    std::string subject, resource, sessionId;
-    std::vector<std::string> paramNames, paramValues;
-    Try {
-        connector->read(&widgetHandle,
-                        &subject,
-                        &resource,
-                        &paramNames,
-                        &paramValues,
-                        &sessionId);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection read error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket Connection read error");
-    }
-
-    if (paramNames.size() != paramValues.size()) {
-        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException, "Varying sizes of parameter names and parameter values");
-    }
-    LogDebug("We got subject: " << subject);
-    LogDebug("We got resource: " << resource);
-
-    FunctionParamImpl params;
-    for (size_t i = 0; i < paramNames.size(); ++i) {
-        params.addAttribute(paramNames[i], paramValues[i]);
-    }
-
-    Request request(widgetHandle,
-                    WidgetExecutionPhase_Invoke,
-                    &params);
-    request.addDeviceCapability(resource);
-
-    PolicyResult result(PolicyEffect::DENY);
-    SecurityCallerSingleton::Instance().SendSyncEvent(
-        SecurityControllerEvents::CheckRuntimeCallSyncEvent(
-            &result,
-            &request,
-            sessionId));
-
-    int response = PolicyResult::serialize(result);
-
-    Try{
-        connector->write(response);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection write error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket Connection write error");
-    }
-}
-
-void AceServiceCallbacks::checkAccessInstall(SocketConnection * connector){
-
-    int widgetHandle;
-    std::string resource;
-
-    Try {
-        connector->read(&widgetHandle,
-                        &resource);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection read error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket Connection read error");
-    }
-
-    LogDebug("We got handle: " << widgetHandle);
-    LogDebug("We got resource: " << resource);
-
-    Request request(widgetHandle,
-          WidgetExecutionPhase_WidgetInstall);
-    request.addDeviceCapability(resource);
-
-    PolicyResult result(PolicyEffect::DENY);
-    SecurityCallerSingleton::Instance().SendSyncEvent(
-            SecurityControllerEvents::CheckFunctionCallSyncEvent(
-                    &result,
-                    &request));
-
-    int response = PolicyResult::serialize(result);
-
-    Try{
-        connector->write(response);
-    }  Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection write error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket Connection write error");
-    }
-}
-
-void AceServiceCallbacks::updatePolicy(SocketConnection * /*connector*/){
-
-
-    LogDebug("Policy update socket message received");
-    SecurityCallerSingleton::Instance().SendSyncEvent(
-            SecurityControllerEvents::UpdatePolicySyncEvent());
-}
-
-} //namespace RPC
diff --git a/src/services/ace/socket/ace_service_callbacks.h b/src/services/ace/socket/ace_service_callbacks.h
deleted file mode 100644 (file)
index e5ebc18..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service_callbacks.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header of Ace Service callbacks
- */
-
-#ifndef ACE_SERVICE_CALLBACKS_H_
-#define ACE_SERVICE_CALLBACKS_H_
-
-#include <memory>
-#include <SocketConnection.h>
-#include <dpl/log/log.h>
-
-namespace RPC {
-
-namespace AceServiceCallbacks {
-
-    // IN string subject
-    // IN string resource
-    // IN vector<string> function param names
-    // IN vector<string> function param values
-    // OUT int allow, deny, popup type
-    void checkAccess(SocketConnection * connector);
-
-    // IN string subject
-    // IN string resource
-    // OUT int allow, deny, popup type
-    void checkAccessInstall(SocketConnection * connector);
-
-    // Policy update trigger
-    void updatePolicy(SocketConnection * connector);
-
-};
-
-} //namespace RPC
-
-#endif /* ACE_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/ace/socket/api/ace_service_callbacks_api.h b/src/services/ace/socket/api/ace_service_callbacks_api.h
deleted file mode 100644 (file)
index dfd136b..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ace_service_callbacks_api.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header with api of implemented Ace Service callbacks
- */
-#ifndef ACE_SERVICE_CALLBACKS_API_H_
-#define ACE_SERVICE_CALLBACKS_API_H_
-
-#include <string>
-#include <utility>
-#include "ace_server_api.h"
-#include "ace_service_callbacks.h"
-#include "callback_api.h"
-
-namespace WrtSecurity{
-namespace AceServiceCallbacksApi{
-
-inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK() {
-    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
-                          RPC::AceServiceCallbacks::checkAccess);
-}
-
-inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_INSTALL_METHOD_CALLBACK() {
-    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
-                          RPC::AceServiceCallbacks::checkAccessInstall);
-}
-
-inline const std::pair<std::string, socketServerCallback> UPDATE_POLICY_METHOD_CALLBACK() {
-    return std::make_pair(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD(),
-                          RPC::AceServiceCallbacks::updatePolicy);
-}
-
-} // namespace AceServiceCallbacksApi
-} // namespace WrtSecurity
-
-
-#endif // ACE_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/caller/security_caller.cpp b/src/services/caller/security_caller.cpp
deleted file mode 100644 (file)
index 8fab788..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        popup_service_callbacks.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Implementation of Security Caller Thread singleton
- */
-
-#include <security_caller.h>
-#include <dpl/singleton_impl.h>
-
-IMPLEMENT_SINGLETON(SecurityCallerThread)
diff --git a/src/services/caller/security_caller.h b/src/services/caller/security_caller.h
deleted file mode 100644 (file)
index e1b68d0..0000000
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        popup_service_callbacks.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Header of Security Caller class used by services socket callbacks
- */
-
-#ifndef SECURITY_CALLER_H__
-#define SECURITY_CALLER_H__
-
-#include <dpl/thread.h>
-#include <dpl/assert.h>
-#include <dpl/singleton.h>
-
-#include <security_controller.h>
-
-#include <pthread.h>
-
-class IEventHolder
-{
- public:
-  virtual void FinalizeSending() = 0;
-  virtual ~IEventHolder() {};
-};
-
-template<class EventType>
-class EventHolderImpl : public IEventHolder
-{
-  EventType event;
-
- public:
-  EventHolderImpl(const EventType& e) : event(e) {}
-  virtual void FinalizeSending()
-  {
-    LogDebug("sending real sync event");
-    CONTROLLER_POST_SYNC_EVENT(SecurityController, event);
-  }
-};
-
-/*
- * Because Security Controller is a DPL::Controler class, its events
- * can be send only from a DPL managed thread. SecurityCallerTread class
- * has been implemented as a workaround of that constraint.
- * This class is a DPL managed thread that waits for requests
- * from non DPL managed threads and when receives one it posts event
- * to the Security Controler in charge of the calling thread.
- */
-
-
-class SecurityCallerThread : public DPL::Thread
-{
- private:
-  pthread_mutex_t m_mutex2;
-  pthread_mutex_t m_mutex;
-  pthread_cond_t m_cond;
-  pthread_cond_t m_cond2;
-  bool m_continue;
-  bool m_finished;
-  IEventHolder* m_eventHolder;
-  pthread_mutex_t m_syncMutex;
-
-
-  SecurityCallerThread() :
-    Thread(),
-    m_mutex2(PTHREAD_MUTEX_INITIALIZER),
-    m_mutex(PTHREAD_MUTEX_INITIALIZER),
-    m_cond(PTHREAD_COND_INITIALIZER),
-    m_cond2(PTHREAD_COND_INITIALIZER),
-    m_continue(true),
-    m_finished(false),
-    m_eventHolder(NULL),
-    m_syncMutex(PTHREAD_MUTEX_INITIALIZER)
-  {
-    LogDebug("constructor");
-  }
-
-  virtual ~SecurityCallerThread()
-  {
-    pthread_mutex_unlock(&m_syncMutex);
-    pthread_cond_destroy(&m_cond);
-    pthread_cond_destroy(&m_cond2);
-    pthread_mutex_destroy(&m_mutex2);
-    pthread_mutex_destroy(&m_mutex);
-    pthread_mutex_destroy(&m_syncMutex);
-  }
-
- protected:
-  /* main routine of the SecurityCallerThread */
-  virtual int ThreadEntry()
-  {
-    LogDebug("SecurityCallerThread start");
-    pthread_mutex_lock(&m_mutex); // lock shared data
-
-    while (m_continue) // main loop
-    {
-      if (m_eventHolder) // if m_eventHolder is set, the request has been received
-      {
-        m_eventHolder->FinalizeSending(); // send actual event in charge of calling thread
-        delete m_eventHolder;
-        m_eventHolder = NULL;
-        LogDebug("setting finished state");
-        pthread_mutex_lock(&m_syncMutex); // lock m_finished
-        m_finished = true;
-        pthread_mutex_unlock(&m_syncMutex); // unlock m_finished
-        LogDebug("finished");
-        pthread_cond_signal(&m_cond2); // signal a calling thread that event has been posted.
-      }
-      LogDebug("waiting for event");
-      // atomically:
-      // unlock m_mutex, wait on m_cond until signal received, lock m_mutex
-      pthread_cond_wait(&m_cond, &m_mutex);
-      LogDebug("found an event");
-    }
-
-    pthread_mutex_unlock(&m_mutex);
-
-    return 0;
-  }
-
- public:
-  void Quit()
-  {
-    LogDebug("Quit called");
-    pthread_mutex_lock(&m_mutex);    // lock shared data
-    m_continue = false;              // main loop condition set to false
-    pthread_mutex_unlock(&m_mutex);  // unlock shard data
-    pthread_cond_signal(&m_cond);
-  }
-
-  template <class EventType>
-  void SendSyncEvent(const EventType& event)
-  {
-    // prevent SendSyncEvent being called by multiple threads at the same time.
-    pthread_mutex_lock(&m_mutex2);
-    LogDebug("sending sync event");
-    bool correct_thread = false;
-    Try {
-      LogDebug("Checking if this is unmanaged thread");
-      DPL::Thread::GetCurrentThread();
-    } Catch (DPL::Thread::Exception::UnmanagedThread) {
-      correct_thread = true;
-    }
-    Assert(correct_thread &&
-           "This method may not be called from DPL managed thread or main thread");
-    LogDebug("putting an event to be posted");
-    pthread_mutex_lock(&m_mutex);  // lock shared data
-    Assert(m_eventHolder == NULL && "Whooops");
-    m_eventHolder = new EventHolderImpl<EventType>(event); // put an event to be posted
-    pthread_mutex_unlock(&m_mutex); // unlock shared data
-    LogDebug("Signal caller thread that new event has been created");
-    pthread_cond_signal(&m_cond);   // signal SecurityCallerThread to wake up because new
-                                    // event is waiting to be posted
-
-    LogDebug("waiting untill send completes");
-    pthread_mutex_lock(&m_syncMutex); /* wait until send completes */
-    while (!m_finished)
-    {
-        pthread_cond_wait(&m_cond2, &m_syncMutex); // wait until event is posted
-    }
-    LogDebug("done");
-    m_finished = false;
-    pthread_mutex_unlock(&m_syncMutex);
-    pthread_mutex_unlock(&m_mutex2);
-  }
-
- private:
-  friend class DPL::Singleton<SecurityCallerThread>;
-};
-
-typedef DPL::Singleton<SecurityCallerThread> SecurityCallerSingleton;
-
-
-
-#endif //SECURITY_CALLER_H__
diff --git a/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h b/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h
deleted file mode 100644 (file)
index df9817b..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_server_api.h
- * @author
- * @version     1.0
- * @brief       This file contains definitions OCSP server interface & methods specifically needed by DBus.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
-
-#include "ocsp_server_api.h"
-#include<string>
-
-namespace WrtSecurity{
-namespace OcspServerApi{
-
-
-// RPC test function
-// IN std::string
-// OUT std::string
-inline const std::string ECHO_METHOD()
-{
-    return "echo";
-}
-
-
-
-}
-};
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp b/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
deleted file mode 100644 (file)
index 2acc5d8..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_service_dbus_interface.cpp
- * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
- * @version     1.0
- * @brief       Implementation of OCSP server API.
- */
-#include "ocsp_server_dbus_interface.h"
-
-namespace RPC {
-
-using namespace WrtSecurity;
-
-OcspServerDBusInterface::OcspServerDBusInterface():
-    DPL::DBus::InterfaceDispatcher(OcspServerApi::INTERFACE_NAME())
-{
-    setXmlSignature("<node>"
-        "  <interface name='" + OcspServerApi::INTERFACE_NAME() + "'>"
-        "    <method name='" + OcspServerApi::ECHO_METHOD() + "'>"
-        "      <arg type='s' name='input' direction='in'/>"
-        "      <arg type='s' name='output' direction='out'/>"
-        "    </method>"
-        "    <method name='" + OcspServerApi::CHECK_ACCESS_METHOD() + "'>"
-        "      <arg type='i' name='input' direction='in'/>"
-        "      <arg type='i' name='output' direction='out'/>"
-        "    </method>"
-        "  </interface>"
-        "</node>");
-}
-
-
-void OcspServerDBusInterface::onMethodCall(
-        const gchar* argMethodName,
-        GVariant* argParameters,
-        GDBusMethodInvocation* argInvocation)
-{
-    if (OcspServerApi::ECHO_METHOD() == argMethodName){
-        // TODO: Deserialization should use
-        // DBus::SErverDeserialization::deserialize()
-        const gchar* arg = NULL;
-        g_variant_get(argParameters, "(&s)", &arg);
-        // TODO: Serialization should use
-        // DBus::SErverDeserialization::serialize()
-        gchar* response = g_strdup_printf(arg);
-        g_dbus_method_invocation_return_value(argInvocation,
-                                              g_variant_new ("(s)", response));
-        g_free (response);
-    } else if (OcspServerApi::CHECK_ACCESS_METHOD() == argMethodName) {
-        gint32 value;
-        g_variant_get(argParameters, "(i)", &value);
-
-        // TODO: this is making OCSP service a stub! this HAS to be moved
-        // with proper implementation to cert-svc daemon
-        gint32 response = 0; // Certificates are valid for now
-
-        GVariant* varResponse = g_variant_new ("(i)", response);
-                //This function will unref invocation and it will be freed
-        LogDebug("OCSP dbus interface tries to send result");
-        g_dbus_method_invocation_return_value(argInvocation, varResponse);
-    }
-}
-
-} // namespace RPC
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.h b/src/services/ocsp/dbus/ocsp_server_dbus_interface.h
deleted file mode 100644 (file)
index 748c0bd..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_service_dbus_interface.h
- * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
- * @version     1.0
- * @brief       Class that handles OCSP server API.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
-
-#include <list>
-#include <dpl/dbus/dbus_interface_dispatcher.h>
-#include "api/ocsp_server_dbus_api.h"
-
-namespace RPC {
-
-class OcspServerDBusInterface :
-    public DPL::DBus::InterfaceDispatcher
-{
-  public:
-    OcspServerDBusInterface();
-
-    virtual ~OcspServerDBusInterface()
-    {}
-
-    virtual void onMethodCall(const gchar* method_name,
-                              GVariant* parameters,
-                              GDBusMethodInvocation* invocation);
-};
-
-} // namespace RPC
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ocsp/ocsp_server_api.h b/src/services/ocsp/ocsp_server_api.h
deleted file mode 100644 (file)
index 61be515..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_server_api.h
- * @author
- * @version     1.0
- * @brief       This file contains definitions OCSP server interface & methods.
- */
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
-#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
-
-#include "ocsp_server_api.h"
-#include<string>
-
-namespace WrtSecurity{
-namespace OcspServerApi{
-
-// DBus interface name
-inline const std::string INTERFACE_NAME()
-{
-    return "org.tizen.OcspCheck";
-}
-
-// Function checks WidgetStatus for installed widget.
-// https://106.116.37.24/wiki/WebRuntime/Security/Widget_Signatures
-// IN WidgetHandle Widget ID in Database
-// OUT WidgetStatus GOOD/REVOKED
-inline const std::string CHECK_ACCESS_METHOD()
-{
-    return "OcspCheck";
-}
-
-}
-};
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
diff --git a/src/services/ocsp/ocsp_service.cpp b/src/services/ocsp/ocsp_service.cpp
deleted file mode 100644 (file)
index 34d3499..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file        ocsp_service.cpp
- * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
- * @version     1.0
- * @brief       This is implementation file of Ocsp service
- */
-
-#include "security_daemon.h"
-
-namespace OcspService {
-
-class OcspService : public SecurityDaemon::DaemonService
-{
-  private:
-    virtual void initialize()
-    {
-    }
-
-    virtual void start()
-    {
-    }
-
-    virtual void stop()
-    {
-    }
-
-    virtual void deinitialize()
-    {
-    }
-
-};
-
-DAEMON_REGISTER_SERVICE_MODULE(OcspService)
-
-}//namespace OcspService
-
diff --git a/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h b/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h
deleted file mode 100644 (file)
index fd9bf3e..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_service_callbacks_api.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header with api of implemented Ocsp Service callbacks
- */
-
-#ifndef OCSP_SERVICE_CALLBACKS_API_H_
-#define OCSP_SERVICE_CALLBACKS_API_H_
-
-#include <string>
-#include <utility>
-#include "SocketConnection.h"
-#include "ocsp_server_api.h"
-#include "ocsp_service_callbacks.h"
-#include "callback_api.h"
-
-namespace WrtSecurity{
-namespace OcspServiceCallbacksApi{
-
-inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK(){
-    return std::make_pair(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
-                          RPC::OcspServiceCallbacks::checkAccess);
-}
-
-} // namespace OcspServiceCallbacksApi
-} // namespace WrtSecurity
-
-#endif // OCSP_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.cpp b/src/services/ocsp/socket/ocsp_service_callbacks.cpp
deleted file mode 100644 (file)
index 8ff588a..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_service_callbacks.cpp
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Implementation of Ocsp Service callbacks
- */
-
-#include "ocsp_service_callbacks.h"
-#include <callback_api.h>
-
-namespace RPC {
-
-void OcspServiceCallbacks::checkAccess(SocketConnection * connector){
-    int response = 0;
-    Try {
-        connector->write(response);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket Connection write error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket Connection write error");
-    }
-}
-
-} // namespace RPC
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.h b/src/services/ocsp/socket/ocsp_service_callbacks.h
deleted file mode 100644 (file)
index df77a80..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        ocsp_service_callbacks.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header of Ocsp Service callbacks class
- */
-
-#ifndef OCSP_SERVICE_CALLBACKS_H_
-#define OCSP_SERVICE_CALLBACKS_H_
-
-#include <SocketConnection.h>
-
-namespace RPC {
-
-namespace OcspServiceCallbacks {
-    void checkAccess(SocketConnection * connector);
-};
-
-} // namespace RPC
-#endif /* OCSP_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.cpp b/src/services/popup/dbus/popup_response_dbus_interface.cpp
deleted file mode 100644 (file)
index f897eeb..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file    popup_response_dispatcher.cpp
- * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
- * @version 1.0
- * @brief
- */
-
-#include "popup_response_dbus_interface.h"
-#include <vector>
-#include <string>
-#include <dpl/dbus/dbus_server_deserialization.h>
-#include <dpl/dbus/dbus_server_serialization.h>
-#include <ace/Request.h>
-#include <ace-dao-ro/PromptModel.h>
-#include "popup_ace_data_types.h"
-//#include "access-control/engine/PromptModel.h"
-#include "attribute_facade.h"
-//#include "Request.h"
-#include "security_controller.h"
-
-namespace RPC
-{
-
-void PopupResponseDBusInterface::onMethodCall(const gchar* methodName,
-                                           GVariant* parameters,
-                                           GDBusMethodInvocation* invocation)
-{
-    using namespace WrtSecurity;
-#if 1
-    if (0 == g_strcmp0(methodName,
-            PopupServerApi::VALIDATION_METHOD().c_str()))
-    {
-        // popup answer data
-        bool allowed = false;
-        int serializedValidity = 0;
-
-        // ACE data
-        AceUserdata acedata;
-
-        if (!DPL::DBus::ServerDeserialization::deserialize(
-                parameters,
-                &allowed,
-                &serializedValidity,
-                &(acedata.handle),
-                &(acedata.subject),
-                &(acedata.resource),
-                &(acedata.paramKeys),
-                &(acedata.paramValues),
-                &(acedata.sessionId)))
-        {
-            g_dbus_method_invocation_return_dbus_error(
-                          invocation,
-                          "org.tizen.PopupResponse.UnknownError",
-                          "Error in deserializing input parameters");
-            return;
-        }
-
-        if (acedata.paramKeys.size() != acedata.paramValues.size()) {
-            g_dbus_method_invocation_return_dbus_error(
-                      invocation,
-                      "org.tizen.PopupResponse.UnknownError",
-                      "Varying sizes of parameter names and parameter values");
-            return;
-        }
-
-        FunctionParamImpl params;
-        for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
-            params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
-        }
-        Request request(acedata.handle,
-                        WidgetExecutionPhase_Invoke,
-                        &params);
-        request.addDeviceCapability(acedata.resource);
-
-        Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
-
-        bool response = false;
-        SecurityControllerEvents::ValidatePopupResponseEvent ev(
-            &request,
-            allowed,
-            validity,
-            acedata.sessionId,
-            &response);
-        CONTROLLER_POST_SYNC_EVENT(SecurityController, ev);
-
-        g_dbus_method_invocation_return_value(
-            invocation,
-            DPL::DBus::ServerSerialization::serialize(response));
-    }
-#endif
-}
-
-}
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.h b/src/services/popup/dbus/popup_response_dbus_interface.h
deleted file mode 100644 (file)
index 19e9494..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file    popup_response_dbus_interface.h
- * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
- * @author  Tomasz Swierczek (t.swierczek@samsung.com)
- * @version 1.0
- * @brief
- */
-
-#ifndef WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
-#define WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
-
-#include <dpl/dbus/dbus_interface_dispatcher.h>
-#include "popup_response_server_api.h"
-
-namespace RPC {
-
-class PopupResponseDBusInterface : public DPL::DBus::InterfaceDispatcher
-{
-public:
-    PopupResponseDBusInterface():
-            DPL::DBus::InterfaceDispatcher(
-                    WrtSecurity::PopupServerApi::INTERFACE_NAME())
-    {
-        using namespace WrtSecurity;
-
-        setXmlSignature("<node>"
-                 "  <interface name='" +
-                         PopupServerApi::INTERFACE_NAME() + "'>"
-                 "    <method name='" +
-                         PopupServerApi::VALIDATION_METHOD() + "'>"
-                         // popup answer data
-                 "      <arg type='b' name='allowed' direction='in'/>"
-                 "      <arg type='i' name='valid' direction='in'/>"
-                         // this is copied from ace_server_dbus_interface
-                 "      <arg type='i' name='handle' direction='in'/>"
-                 "      <arg type='s' name='subject' direction='in'/>"
-                 "      <arg type='s' name='resource' direction='in'/>"
-                 "      <arg type='as' name='parameter names' direction='in'/>"
-                 "      <arg type='as' name='parameter values' direction='in'/>"
-                 "      <arg type='s' name='sessionId' direction='in'/>"
-                 "      <arg type='b' name='response' direction='out'/>"
-                 "    </method>"
-                 "  </interface>"
-                 "</node>");
-
-    }
-
-    virtual ~PopupResponseDBusInterface()
-    {}
-
-    virtual void onMethodCall(const gchar* methodName,
-                              GVariant* parameters,
-                              GDBusMethodInvocation* invocation);
-};
-
-}
-
-#endif // WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
diff --git a/src/services/popup/popup_ace_data_types.h b/src/services/popup/popup_ace_data_types.h
deleted file mode 100644 (file)
index 1b5f734..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file    popup_ace_data_types.h
- * @author  Pawel Sikorski (p.sikorski@samsung.com)
- * @version 1.0
- * @brief
- */
-
-#ifndef POPUP_ACE_DATA_TYPES_H_
-#define POPUP_ACE_DATA_TYPES_H_
-
-#include <vector>
-#include <string>
-
-// additional data needed by PolicyEvaluaor to recognize Popup Response
-struct AceUserdata
-{
-    //TODO INVALID_WIDGET_HANDLE is defined in wrt_plugin_export.h.
-    // I do not want to include that file here...
-    AceUserdata(): handle(-1) {}
-
-    int handle;
-    std::string subject;
-    std::string resource;
-    std::vector<std::string> paramKeys;
-    std::vector<std::string> paramValues;
-    std::string sessionId;
-};
-
-typedef bool SecurityStatus;
-
-#endif /* POPUP_ACE_DATA_TYPES_H_ */
diff --git a/src/services/popup/popup_response_server_api.h b/src/services/popup/popup_response_server_api.h
deleted file mode 100644 (file)
index 47dd4d3..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/**
- * @file    popup_response_server_api.h
- * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
- * @version 1.0
- * @brief
- */
-
-#ifndef WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
-#define WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
-
-#include <string>
-
-namespace WrtSecurity{
-namespace PopupServerApi{
-
-inline const std::string INTERFACE_NAME()
-{
-    return "org.tizen.PopupResponse";
-}
-
-inline const std::string VALIDATION_METHOD()
-{
-    return "validate";
-}
-
-}
-}
-
-#endif // WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
-
diff --git a/src/services/popup/socket/api/popup_service_callbacks_api.h b/src/services/popup/socket/api/popup_service_callbacks_api.h
deleted file mode 100644 (file)
index d22b9c7..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        popup_service_callbacks_api.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header with api of Popup Service callbacks
- */
-
-#ifndef POPUP_SERVICE_CALLBACKS_API_H_
-#define POPUP_SERVICE_CALLBACKS_API_H_
-
-#include <string>
-#include <utility>
-#include "SocketConnection.h"
-#include "popup_response_server_api.h"
-#include "popup_service_callbacks.h"
-#include <callback_api.h>
-
-namespace WrtSecurity{
-namespace PopupServiceCallbacksApi{
-
-inline std::pair<std::string, socketServerCallback> VALIDATION_METHOD_CALLBACK(){
-    return std::make_pair(WrtSecurity::PopupServerApi::VALIDATION_METHOD(), RPC::PopupServiceCallbacks::validate);
-}
-
-} // namespace PopupServiceCallbacksApi
-} // namespace WrtSecurity
-
-#endif /* POPUP_SERVICE_CALLBACKS_API_H_ */
diff --git a/src/services/popup/socket/popup_service_callbacks.cpp b/src/services/popup/socket/popup_service_callbacks.cpp
deleted file mode 100644 (file)
index d3e88e0..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        popup_service_callbacks.cpp
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Implementation of Popup Service callbacks
- */
-
-#include "popup_service_callbacks.h"
-#include <callback_api.h>
-#include <ace/Request.h>
-#include <ace-dao-ro/PromptModel.h>
-#include <dpl/log/log.h>
-#include "attribute_facade.h"
-#include "popup_ace_data_types.h"
-#include "security_controller.h"
-#include <security_caller.h>
-
-namespace RPC {
-
-void PopupServiceCallbacks::validate(SocketConnection * connector){
-
-    bool allowed = false;
-    int serializedValidity = 0;
-
-    AceUserdata acedata;
-
-    Try {
-        connector->read(&allowed,
-                        &serializedValidity,
-                        &(acedata.handle),
-                        &(acedata.subject),
-                        &(acedata.resource),
-                        &(acedata.paramKeys),
-                        &(acedata.paramValues),
-                        &(acedata.sessionId));
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket connection read error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket connection read error");
-    }
-
-    if (acedata.paramKeys.size() != acedata.paramValues.size()) {
-        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                 "Varying sizes of parameter names vector and parameter values vector");
-    }
-    FunctionParamImpl params;
-    for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
-        params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
-    }
-    Request request(acedata.handle,
-                    WidgetExecutionPhase_Invoke,
-                    &params);
-    request.addDeviceCapability(acedata.resource);
-
-    Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
-
-    bool response = false;
-    SecurityControllerEvents::ValidatePopupResponseEvent ev(
-        &request,
-        allowed,
-        validity,
-        acedata.sessionId,
-        &response);
-    SecurityCallerSingleton::Instance().SendSyncEvent(ev);
-
-    Try {
-        connector->write(response);
-    } Catch (SocketConnection::Exception::SocketConnectionException){
-        LogError("Socket connection write error");
-        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
-                   "Socket connection write error");
-    }
-}
-
-} // namespace RPC
diff --git a/src/services/popup/socket/popup_service_callbacks.h b/src/services/popup/socket/popup_service_callbacks.h
deleted file mode 100644 (file)
index e7d30f2..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-/*
- * @file        popup_service_callbacks.h
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       Header of Popup Service callbacks
- */
-
-#ifndef POPUP_SERVICE_CALLBACKS_H_
-#define POPUP_SERVICE_CALLBACKS_H_
-
-#include <memory>
-#include <SocketConnection.h>
-
-namespace RPC {
-
-namespace PopupServiceCallbacks {
-    void validate(SocketConnection * connector);
-};
-
-} // namespace RPC
-#endif /* POPUP_SERVICE_CALLBACKS_H_ */
diff --git a/src/util/security-server-util-common.c b/src/util/security-server-util-common.c
new file mode 100644 (file)
index 0000000..e28786a
--- /dev/null
@@ -0,0 +1,367 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "security-server-common.h"
+#include "security-server-cookie.h"
+#include "security-server-comm.h"
+#include "security-server-util.h"
+#include "security-server.h"
+
+
+/* Get all cookie info response *
+ * packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x52 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |             tot # of cooks (32bit)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |            1st cmdline_len (32bit)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |           1st permission_len (32bit)          |
+ * ----------------------------------------------------------------|
+ * |   cont'd...   |                                               |
+ * |----------------                                               |
+ * |                         1st cookie                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         1st PID (32bit)                       |
+ * |---------------------------------------------------------------|
+ * |                     1st cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                           1st perm_1                          |
+ * |---------------------------------------------------------------|
+ * |                           1st perm_2                          |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+ * |                      2nd cmdline_len  (32bit)                 |
+ * |---------------------------------------------------------------|
+ * |                     2nd permission_len (32bit)                |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                        2nd cookie                             |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         2nd PID (32 bit)                      |
+ * |---------------------------------------------------------------|
+ * |                     2nd cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                           2st perm_1                          |
+ * |---------------------------------------------------------------|
+ * |                           2st perm_2                          |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                             ...                               |
+ * |                                                               |
+ * |                                                               |
+ */
+ unsigned char * get_all_cookie_info(cookie_list *list, int *size)
+{
+       cookie_list *current = list;
+       int ptr, total_num, total_size, tempnum, i;
+       unsigned char *buf = NULL, *tempptr = NULL;
+       response_header hdr;
+
+       total_size = sizeof(hdr) + sizeof(int);
+
+       buf = malloc(total_size); /* header size */
+       ptr = sizeof(hdr) + sizeof(int);
+       total_num = 0;  /* Total # of cookies initial value */
+
+       while(current != NULL)
+       {
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               total_num++;
+               total_size += sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + current->path_len + (current->permission_len * sizeof(int));
+               tempptr = realloc(buf, total_size);
+               if(tempptr == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Out of memory");
+                       return NULL;
+               }
+               buf = tempptr;
+
+               tempnum = current->path_len;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               tempnum = current->permission_len;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf+ptr, current->cookie, SECURITY_SERVER_COOKIE_LEN);
+               ptr += SECURITY_SERVER_COOKIE_LEN;
+               tempnum = current->pid;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf+ptr, current->path, current->path_len);
+               ptr += current->path_len;
+
+               for(i=0;i<current->permission_len;i++)
+               {
+                       tempnum = current->permissions[i];
+                       memcpy(buf+ptr, &tempnum, sizeof(int));
+                       ptr += sizeof(int);
+               }
+               current = current->next;
+       }
+
+       if(total_size > 65530)
+       {
+               SEC_SVR_DBG("Packet too big. message length overflow: %d", total_size);
+               free(buf);
+               return  NULL;
+       }
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE;
+       hdr.basic_hdr.msg_len =(unsigned short)( total_size - sizeof(hdr));
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+       memcpy(buf, &hdr, sizeof(hdr));
+       tempnum = total_num;
+       memcpy(buf + sizeof(hdr), &tempnum, sizeof(int));
+       *size = total_size;
+       return buf;
+}
+
+int send_all_cookie_info(const unsigned char *buf, int size, int sockfd)
+{
+       int ret;
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       ret = write(sockfd, buf, size);
+
+       if(ret < size)
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Get one cookie info response *
+ * packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x54 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |              cmdline_len (32bit)t)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |              permission_len (32bit)           |
+ * ----------------------------------------------------------------|
+ * |   cont'd...   |                                               |
+ * |----------------                                               |
+ * |                             cookie                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                           PID (32bit)                         |
+ * |---------------------------------------------------------------|
+ * |                         cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                             perm_1                            |
+ * |---------------------------------------------------------------|
+ * |                             perm_2                            |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+*/
+int send_one_cookie_info(const cookie_list *list, int sockfd)
+{
+       unsigned char *buf = NULL;
+       response_header hdr;
+       int total_size, ptr = 0, tempnum, ret, i;
+
+       total_size = sizeof(hdr) + sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
+       buf = malloc(total_size);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE;
+       hdr.basic_hdr.msg_len =sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr += sizeof(hdr);
+
+       tempnum = list->path_len;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       tempnum = list->permission_len;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(buf+ptr, list->cookie, SECURITY_SERVER_COOKIE_LEN);
+       ptr += SECURITY_SERVER_COOKIE_LEN;
+       tempnum = list->pid;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(buf+ptr, list->path, list->path_len);
+       ptr += list->path_len;
+
+       for(i=0;i<list->permission_len;i++)
+       {
+               tempnum = list->permissions[i];
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+       }
+
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               free(buf);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               free(buf);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       ret = write(sockfd, buf, total_size);
+       free(buf);
+       if(ret < total_size)
+           return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int util_process_all_cookie(int sockfd, cookie_list* list)
+{
+       unsigned char *buf = NULL;
+       int ret;
+       buf = get_all_cookie_info(list, &ret);
+       if(buf == NULL)
+       {
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       ret = send_all_cookie_info(buf, ret, sockfd);
+
+       if(buf != NULL)
+               free(buf);
+       return ret;
+}
+int util_process_cookie_from_pid(int sockfd, cookie_list* list)
+{
+       int pid, ret;
+       cookie_list *result = NULL;
+
+       ret = read(sockfd, &pid, sizeof(int));
+       if(ret < sizeof(int))
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(pid == 0)
+       {
+               SEC_SVR_DBG("%s", "ERROR: Default cookie is not allowed to be retrieved");
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       result = search_cookie_from_pid(list, pid);
+       if(result == NULL)
+       {
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       else
+       {
+               ret = send_one_cookie_info(result, sockfd);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
+               }
+       }
+       
+       return ret;
+}
+
+int util_process_cookie_from_cookie(int sockfd, cookie_list* list)
+{
+       unsigned char cookie[SECURITY_SERVER_COOKIE_LEN];
+       int ret;
+       cookie_list *result = NULL;
+
+       ret = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       result = search_cookie(list, cookie, 0);
+       if(result == NULL)
+       {
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       else
+       {
+               ret = send_one_cookie_info(result, sockfd);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
+               }
+       }
+       
+       return ret;
+}
diff --git a/src/util/security-server-util.c b/src/util/security-server-util.c
new file mode 100644 (file)
index 0000000..9e6e516
--- /dev/null
@@ -0,0 +1,773 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "security-server.h"
+#include "security-server-common.h"
+#include "security-server-util.h"
+#include "security-server-comm.h"
+
+#define TOTAL_PATH_MAX 256
+
+#define mszBase64Table  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+#define BASE64_PAD      '='
+
+
+
+ void printusage(char *cmdline)
+{
+       printf("%s\n", "Usage: ");
+       printf("%s [Options]\n", cmdline);
+       printf("%s\n", "[Options]");
+       printf("%s\n", "-a:\tList all active cookies ");
+       printf("%s\n", "-f [filename]:\tList a specific cookie information from file");
+       printf("%s\n", "\tThe file must contain binary form of cookie");
+       printf("%s\n", "-p [pid]:\tList a specific cookie information for a process by PID");
+       printf("%s\n", "-s [base64 encoded cookie]:\tList a specific cookie information for a process by given base64 encoded cookie value");
+       printf("%s\n", "Example:");
+       printf("%s -a\n", cmdline);
+       printf("%s -f /tmp/mycookie.bin\n", cmdline);
+       printf("%s -p 2115\n", cmdline);
+       printf("%s -s asC34fddaxd6NDVDA43GFD345TfCADF==\n", cmdline);
+}
+
+void printstr(const unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               printf("%c", data[i]);
+       }
+       printf("\n");
+}
+
+void printperm(const unsigned char *data, int num)
+{
+       int i, ptr, tempnum;
+       for(i=0, ptr=0;i<num;i++)
+       {
+               memcpy(&tempnum, data+ptr, sizeof(int));
+               printf("%d, ", tempnum);
+               ptr+= sizeof(int);
+               if(i % 6 == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+/* Send all cookie information request packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x51 |       Message Length = 0      |
+ * |---------------------------------------------------------------|
+ */
+int send_all_cookie_info_request(int sockfd)
+{
+
+       basic_header hdr;
+       int retval;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+int recv_all_cookie_info(int sockfd)
+{
+       int retval, total_cookie, ptr = 0, i, cmdline_len, perm_len, recved_pid;
+       response_header hdr;
+       unsigned char *buf = NULL;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, &hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               printf("Error: Receive failed %d\n", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               printf("Error: response error: %d\n", hdr.return_code);
+               return return_code_to_error_code(hdr.return_code);
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE)
+       {
+               printf("Error: response error: different msg type %d\n", hdr.basic_hdr.msg_id );
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       buf = malloc(hdr.basic_hdr.msg_len);
+       if(buf == NULL)
+       {
+               printf("Error: Out of memory\n");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
+       if(retval < hdr.basic_hdr.msg_len)
+       {
+               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
+               printhex(buf, retval);
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       memcpy(&total_cookie, buf, sizeof(int));
+       if(total_cookie == 0)
+       {
+               printf("There is no cookie available\n");
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_SUCCESS;
+       }
+       ptr = sizeof(int);
+       printf("--------------------------------\n");
+       for(i=0;i<total_cookie;i++)
+       {
+               printf("%dth cookie:\n", i+1);
+               memcpy(&cmdline_len, buf+ptr, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(&perm_len, buf+ptr, sizeof(int));
+               ptr+= sizeof(int);
+
+               printf("%s\n", "Cookie:");
+               printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
+               ptr += SECURITY_SERVER_COOKIE_LEN;
+               memcpy(&recved_pid, buf+ptr, sizeof(int));
+               ptr+= sizeof(int);
+               if(recved_pid == 0)
+               {
+                       printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
+                       printf("%s\n", "cmdline: N/A");
+                       printf("%s\n", "Permissions (gids): N/A");
+               }
+               else
+               {
+                       printf("PID: %d\n", recved_pid);
+
+                       printf("%s\n", "cmdline:");
+                       printstr(buf + ptr, cmdline_len);
+                       ptr += cmdline_len;
+
+                       printf("%s\n", "Permissions (gids):");
+                       printperm(buf + ptr, perm_len);
+                       ptr += (perm_len * sizeof(int));
+               }
+               printf("--------------------------------\n");
+       }
+       if(buf != NULL)
+               free(buf);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie information request from cookie packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x55 |       Message Length = 20     |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                         cookie                                |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_info_request_from_cookie(int sockfd, const unsigned char *cookie)
+{
+
+       basic_header hdr;
+       int retval;
+       int size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN;
+       unsigned char buf[size];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+/* Send cookie information request from pid packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x53 |       Message Length = 20     |
+ * |---------------------------------------------------------------|
+ * |                            pid                                |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_info_request_from_pid(int sockfd, int pid)
+{
+       basic_header hdr;
+       int retval;
+       int size = sizeof(hdr) + sizeof(int);
+       unsigned char buf[size];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf+sizeof(hdr), &pid, sizeof(int));
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+int recv_cookie_info_response(sockfd)
+{
+       unsigned char *buf = NULL;
+       int retval, cmdline_len, perm_len, recved_pid, ptr = 0;
+       response_header hdr;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, &hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               printf("Error: Receive failed %d\n", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               printf("Error: response error: %d\n", hdr.return_code);
+               return return_code_to_error_code(hdr.return_code);
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE)
+       {
+               printf("Error: response error: different msg type %d\n" ,hdr.basic_hdr.msg_id);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       buf = malloc(hdr.basic_hdr.msg_len);
+       if(buf == NULL)
+       {
+               printf("Error: Out of memory\n");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
+       if(retval < hdr.basic_hdr.msg_len)
+       {
+               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
+               printhex(buf, retval);
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       memcpy(&cmdline_len, buf+ptr, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(&perm_len, buf+ptr, sizeof(int));
+       ptr+= sizeof(int);
+
+       printf("%s\n", "Cookie:");
+       printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
+       ptr += SECURITY_SERVER_COOKIE_LEN;
+       memcpy(&recved_pid, buf+ptr, sizeof(int));
+       ptr+= sizeof(int);
+       if(recved_pid == 0)
+       {
+               printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
+               printf("%s\n", "cmdline: N/A");
+               printf("%s\n", "Permissions (gids): N/A");
+       }
+       else
+       {
+               printf("PID: %d\n", recved_pid);
+
+               printf("%s\n", "cmdline:");
+               printstr(buf + ptr, cmdline_len);
+               ptr += cmdline_len;
+
+               printf("%s\n", "Permissions (gids):");
+               printperm(buf + ptr, perm_len);
+       }
+
+       free(buf);
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+void util_send_all_cookie_info_request(void)
+{
+       int sockfd = -1, retval;
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_all_cookie_info_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_all_cookie_info(sockfd);
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie list: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+void util_read_cookie_from_bin_file(unsigned char *cookie, const char *path)
+{
+       char total_path[TOTAL_PATH_MAX] = {0, };
+       FILE *fp = NULL;
+       int ret;
+
+       if(path[0] == '/' || (path[0] == '.' && path[1] == '/'))
+       {
+               /* Using absolute path */
+               strncpy(total_path, path, TOTAL_PATH_MAX);
+       }
+       else
+       {
+               if (getcwd(total_path, TOTAL_PATH_MAX) == NULL)
+               {
+                       printf("Cannot open cookie file\n");
+                       exit(1);
+               }
+               snprintf(total_path, TOTAL_PATH_MAX, "%s/%s", total_path, path);
+       }
+
+       fp = fopen(total_path, "rb");
+       if(fp == NULL)
+       {
+               printf("Cannot open cookie file\n");
+               exit(1);
+       }
+
+       ret = fread(cookie, 1, SECURITY_SERVER_COOKIE_LEN, fp);
+       if(ret < SECURITY_SERVER_COOKIE_LEN)
+       {
+               printf("Cannot read cookie file: %d\n", ret);
+               fclose(fp);
+               exit(1);
+       }
+
+       fclose(fp);
+       return;
+}
+
+void util_send_cookie_info_request_from_cookie(unsigned char *cookie)
+{
+       int sockfd = -1, retval;
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_info_request_from_cookie(sockfd, cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_cookie_info_response(sockfd);
+       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
+       {
+               printf("There is no such cookie available\n");
+               goto error;
+       }
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie info: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+unsigned char* util_base64_decode(unsigned char* input, long inputLength, long* outputLength)
+{
+       unsigned char* pCurIn = input;
+       unsigned char* pCurOut;
+       long iOutCharNum = 0;
+       long lInputLength = inputLength;
+       char buf[4];
+       unsigned char* inCode;
+       unsigned char* output;
+       (*outputLength) = 0;
+       if((input == NULL) || (inputLength <= 0))
+       return NULL;
+
+        /* calculate length of output data */
+       for(; lInputLength > 0; lInputLength--)
+       {
+               if ((*pCurIn) == BASE64_PAD)
+               {
+                       (*outputLength) += ((iOutCharNum + 1) >> 1);
+                       if ((iOutCharNum == 2) &&
+                       ((lInputLength == 1) ||
+                       (*(pCurIn + 1) != BASE64_PAD)))
+                       {
+                               (*outputLength)++;
+                       }
+                       iOutCharNum = 0;
+                       break;
+               }
+               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
+               if (!inCode)
+                       continue;
+               iOutCharNum++;
+               if (iOutCharNum == 4)
+               {
+                       (*outputLength) += 3;
+                       iOutCharNum=0;
+               }
+       }
+       (*outputLength) += ((iOutCharNum + 1)/2);
+
+       /* allocate memory for output data*/
+       output = malloc( *outputLength + 1 );
+       if(NULL == output)
+       {
+               return NULL;
+       }
+       memset( output, 0, (*outputLength + 1) );
+       pCurOut = output;
+       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
+
+       /* decode data*/
+       pCurIn = input;
+
+       for(; inputLength>0; inputLength--)
+       {
+               if ((*pCurIn) == BASE64_PAD)
+               {
+                       /*end-padding processing*/
+                       if (iOutCharNum == 0)
+                       {
+                               return output;
+                       }
+                       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+                       if ((iOutCharNum == 3)||((iOutCharNum == 2) && ((lInputLength == 0) ||
+                       ((*(pCurIn + 1)) != BASE64_PAD))))
+                       {
+                               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+                       }
+                       return output;
+               }
+               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
+               if (!inCode)
+               {
+                       continue;
+               }
+               buf[iOutCharNum++] = (char)((unsigned long)inCode - (unsigned long)mszBase64Table);
+               if (iOutCharNum == 4)
+               {
+                       *(pCurOut++) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+                       *(pCurOut++) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+                       *(pCurOut++) = ((buf[2] & 0x03) << 6) + (buf[3] & 0x3F);
+                       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
+               }
+       }
+       if (iOutCharNum == 0)
+       {
+               return output;
+       }
+       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+       if (iOutCharNum == 3)
+       {
+               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+       }
+       return output;
+}
+
+void util_read_cookie_from_base64_string(unsigned char *cookie, const char *encoded_cookie)
+{
+       unsigned char *decoded_cookie = NULL;
+       int encoded_len, decoded_len;
+       encoded_len = strlen(encoded_cookie);
+
+       decoded_cookie = util_base64_decode((unsigned char *)encoded_cookie, encoded_len, (long *)&decoded_len);
+       if(decoded_len != SECURITY_SERVER_COOKIE_LEN)
+       {
+               printf("Base64 decode failed: %d\n", decoded_len);
+               exit(1);
+       }
+
+       if(decoded_cookie == NULL)
+       {
+               printf("%s", "BASE64 decode failed:\n");
+               exit(1);
+       }
+
+       memcpy(cookie, decoded_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(decoded_cookie != NULL)
+               free(decoded_cookie);
+
+       return;
+}
+
+void util_send_cookie_info_request_from_pid(const char *str_pid)
+{
+       int retval, sockfd, pid;
+
+       if(str_pid == NULL)
+       {
+               printf("Wrong PID\n");
+               return;
+       }
+
+       errno = 0;
+       pid = strtoul(str_pid, 0, 10);
+       if (errno != 0)
+       {
+               SEC_SVR_DBG("cannot change string to integer [%s]", str_pid);
+               return;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_info_request_from_pid(sockfd, pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_cookie_info_response(sockfd);
+       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
+       {
+               printf("There is no such cookie available\n");
+               goto error;
+       }
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie info: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+int main(int argc, char *argv[])
+{
+       int ret;
+       unsigned char cookie[20];
+       ret = getuid();
+       if(ret != 0)
+       {
+               printf("You must be root to test. Current UID: %d\nExiting...\n", ret);
+               exit(1);
+       }
+       if(argc < 2 || argc > 4)
+       {
+               printf("Wrong usage: %d\n", argc);
+               printusage(argv[0]);
+               exit(1);
+       }
+       if(strcmp(argv[1], "-a") == 0)
+       {
+               if(argc != 2)
+               {
+                       printf("Wrong usage: %d\n", argc);
+                       printusage(argv[0]);
+                       exit(1);
+               }
+                       
+               util_send_all_cookie_info_request();
+               exit(0);
+       }
+
+       if(argc < 3)
+       {
+               printf("Wrong usage: %d\n", argc);
+               printusage(argv[0]);
+               exit(1);
+       }
+
+       if(strcmp(argv[1], "-f") == 0)
+       {
+               util_read_cookie_from_bin_file(cookie, argv[2]);
+               util_send_cookie_info_request_from_cookie(cookie);
+               exit(0);
+       }
+
+       if(strcmp(argv[1], "-p") == 0)
+       {
+               util_send_cookie_info_request_from_pid(argv[2]);
+               exit(0);
+       }
+
+       if(strcmp(argv[1], "-s") == 0)
+       {
+               util_read_cookie_from_base64_string(cookie, argv[2]);
+               util_send_cookie_info_request_from_cookie(cookie);
+               exit(0);
+       }
+
+       printf("%s", "Wrong usage\n");
+       printusage(argv[0]);
+       exit(1);
+}