ENDIF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
SET(TARGET_SECURITY_SERVER "security-server")
-SET(TARGET_SECURITY_CLIENT "security-server-client")
SET(TARGET_SECURITY_MANAGER_CLIENT "security-manager-client")
SET(TARGET_SERVER_COMMON "security-server-commons")
# @author Tomasz Swierczek (t.swierczek@samsung.com)
#
-ADD_SUBDIRECTORY(security-server)
ADD_SUBDIRECTORY(security-manager)
+++ /dev/null
-# 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)
-# @brief
-#
-
-CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
-
-INSTALL(FILES
- ${CMAKE_BINARY_DIR}/build/security-server/security-server.pc
- DESTINATION
- ${LIB_INSTALL_DIR}/pkgconfig
- )
+++ /dev/null
-prefix=@CMAKE_INSTALL_PREFIX@
-exec_prefix=${prefix}
-libdir=@LIB_INSTALL_DIR@
-includedir=${prefix}/include
-
-Name: security-server
-Description: Security Server Package
-Version: 1.0.1
-Requires: openssl libsmack libprivilege-control
-Libs: -L${libdir} -lsecurity-server-client
-Cflags: -I${includedir}/security-server
+++ /dev/null
-<manifest>
- <request>
- <domain name="_" />
- </request>
-</manifest>
+++ /dev/null
-* Fri Aug 23 2013 Rusty Lynch <rusty.lynch@intel.com> submit/tizen/20130716.223318@0e96d3e
-- Cleanup spec and remove defunct system V startup scripts
-- smack API has changed; smack_new_label_from socket returns the label length.
-
-* Fri Jul 12 2013 Patrick McCarty <patrick.mccarty@linux.intel.com> b7787d6
-- Fix the manifest installation
-
License: Apache-2.0
Source0: %{name}-%{version}.tar.gz
Source1: security-server.manifest
-Source2: libsecurity-server-client.manifest
Source3: libsecurity-manager-client.manifest
BuildRequires: cmake
BuildRequires: zip
BuildRequires: pkgconfig(dlog)
-BuildRequires: pkgconfig(openssl)
BuildRequires: libattr-devel
BuildRequires: libcap-devel
BuildRequires: pkgconfig(libsmack)
%description
Tizen security server and utilities
-%package -n libsecurity-server-client
-Summary: Security server (client)
-Group: Security/Libraries
-Requires: security-server = %{version}-%{release}
-Requires(post): /sbin/ldconfig
-Requires(postun): /sbin/ldconfig
-
-%description -n libsecurity-server-client
-Tizen Security server client library
-
-%package -n libsecurity-server-client-devel
-Summary: Security server (client-devel)
-Group: Security/Development
-Requires: libsecurity-server-client = %{version}-%{release}
-Requires: libprivilege-control-devel
-
-%description -n libsecurity-server-client-devel
-Development files needed for using the security client
-
%package -n libsecurity-manager-client
Summary: Security manager (client)
Group: Security/Libraries
%description -n libsecurity-manager-client-devel
Development files needed for using the security manager client
-%package -n security-server-devel
-Summary: for web applications (Development)
-Group: Security/Development
-Requires: security-server = %{version}-%{release}
-
-%description -n security-server-devel
-Development files for the Tizen security server
-
-%package -n security-server-certs
-Summary: Certificates for web applications.
-Group: Security/Libraries
-Requires: security-server
-
-%description -n security-server-certs
-Certificates for the Tizen Web-Runtime
-
%prep
%setup -q
cp %{SOURCE1} .
-cp %{SOURCE2} .
cp %{SOURCE3} .
%build
rm -rf %{buildroot}
mkdir -p %{buildroot}/usr/share/license
cp LICENSE %{buildroot}/usr/share/license/%{name}
-cp LICENSE %{buildroot}/usr/share/license/libsecurity-server-client
cp LICENSE %{buildroot}/usr/share/license/libsecurity-manager-client
mkdir -p %{buildroot}/etc/security/
cp security-server-audit.conf %{buildroot}/etc/security/
mkdir -p %{buildroot}/usr/lib/systemd/system/multi-user.target.wants
mkdir -p %{buildroot}/usr/lib/systemd/system/sockets.target.wants
ln -s ../security-server.service %{buildroot}/usr/lib/systemd/system/multi-user.target.wants/security-server.service
-ln -s ../security-server-data-share.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-data-share.socket
-ln -s ../security-server-get-gid.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-get-gid.socket
-ln -s ../security-server-privilege-by-pid.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-privilege-by-pid.socket
-ln -s ../security-server-cookie-get.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-cookie-get.socket
-ln -s ../security-server-cookie-check.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-cookie-check.socket
-ln -s ../security-server-app-privilege-by-name.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-app-privilege-by-name.socket
-ln -s ../security-server-password-check.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-password-check.socket
-ln -s ../security-server-password-set.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-password-set.socket
-ln -s ../security-server-password-reset.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-server-password-reset.socket
ln -s ../security-manager-installer.socket %{buildroot}/usr/lib/systemd/system/sockets.target.wants/security-manager-installer.socket
%clean
systemctl daemon-reload
fi
-%post -n libsecurity-server-client -p /sbin/ldconfig
-
%post -n libsecurity-manager-client -p /sbin/ldconfig
-%postun -n libsecurity-server-client -p /sbin/ldconfig
-
%postun -n libsecurity-manager-client -p /sbin/ldconfig
%files -n security-server
%attr(-,root,root) /usr/lib/systemd/system/multi-user.target.wants/security-server.service
%attr(-,root,root) /usr/lib/systemd/system/security-server.service
%attr(-,root,root) /usr/lib/systemd/system/security-server.target
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-data-share.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-data-share.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-get-gid.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-get-gid.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-privilege-by-pid.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-privilege-by-pid.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-cookie-get.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-cookie-get.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-cookie-check.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-cookie-check.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-app-privilege-by-name.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-app-privilege-by-name.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-password-check.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-password-check.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-password-set.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-password-set.socket
-%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-server-password-reset.socket
-%attr(-,root,root) /usr/lib/systemd/system/security-server-password-reset.socket
%attr(-,root,root) /usr/lib/systemd/system/sockets.target.wants/security-manager-installer.socket
%attr(-,root,root) /usr/lib/systemd/system/security-manager-installer.socket
%attr(-,root,root) /etc/security/security-server-audit.conf
%attr(-,root,root) /etc/smack/app-rules-template.smack
%{_datadir}/license/%{name}
-%files -n libsecurity-server-client
-%manifest libsecurity-server-client.manifest
-%defattr(-,root,root,-)
-%{_libdir}/libsecurity-server-client.so.*
-%{_datadir}/license/libsecurity-server-client
-
-%files -n libsecurity-server-client-devel
-%manifest %{name}.manifest
-%defattr(-,root,root,-)
-%{_libdir}/libsecurity-server-client.so
-%{_libdir}/libsecurity-server-commons.so
-%{_includedir}/security-server/security-server.h
-%{_libdir}/pkgconfig/security-server.pc
%files -n libsecurity-manager-client
%manifest libsecurity-manager-client.manifest
%{_libdir}/libsecurity-manager-client.so
%{_libdir}/libsecurity-server-commons.so
%{_includedir}/security-manager/security-manager.h
+%{_includedir}/security-server/security-server.h
%{_libdir}/pkgconfig/security-manager.pc
PKG_CHECK_MODULES(SECURITY_SERVER_DEP
dlog
- openssl
libsmack
libprivilege-control
libsystemd-daemon
${SERVER2_PATH}/main/generic-socket-manager.cpp
${SERVER2_PATH}/main/socket-manager.cpp
${SERVER2_PATH}/main/server2-main.cpp
- ${SERVER2_PATH}/service/data-share.cpp
- ${SERVER2_PATH}/service/get-gid.cpp
- ${SERVER2_PATH}/service/app-permissions.cpp
- ${SERVER2_PATH}/service/cookie.cpp
- ${SERVER2_PATH}/service/cookie-jar.cpp
- ${SERVER2_PATH}/service/cookie-common.cpp
- ${SERVER2_PATH}/service/privilege-by-pid.cpp
- ${SERVER2_PATH}/service/password.cpp
- ${SERVER2_PATH}/service/password-file.cpp
- ${SERVER2_PATH}/service/password-manager.cpp
- ${SERVER2_PATH}/service/password-file-buffer.cpp
${SERVER2_PATH}/service/smack-common.cpp
${SERVER2_PATH}/service/smack-rules.cpp
${SERVER2_PATH}/service/installer.cpp
-lcap
)
-################################################################################
-
-SET(SECURITY_CLIENT_VERSION_MAJOR 1)
-SET(SECURITY_CLIENT_VERSION ${SECURITY_CLIENT_VERSION_MAJOR}.0.1)
-
-INCLUDE_DIRECTORIES(
- ${SERVER2_PATH}/client
- ${SERVER2_PATH}/common
- ${SERVER2_PATH}/dpl/core/include
- ${SERVER2_PATH}/dpl/log/include
- )
-
-SET(SECURITY_CLIENT_SOURCES
- ${SERVER2_PATH}/client/client-common.cpp
- ${SERVER2_PATH}/client/client-shared-memory.cpp
- ${SERVER2_PATH}/client/client-get-gid.cpp
- ${SERVER2_PATH}/client/client-app-permissions.cpp
- ${SERVER2_PATH}/client/client-cookie.cpp
- ${SERVER2_PATH}/client/client-privilege-by-pid.cpp
- ${SERVER2_PATH}/client/client-socket-privilege.cpp
- ${SERVER2_PATH}/client/client-password.cpp
- )
-
-ADD_LIBRARY(${TARGET_SECURITY_CLIENT} SHARED ${SECURITY_CLIENT_SOURCES})
-
-SET_TARGET_PROPERTIES(
- ${TARGET_SECURITY_CLIENT}
- PROPERTIES
- COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=hidden"
- SOVERSION ${SECURITY_CLIENT_VERSION_MAJOR}
- VERSION ${SECURITY_CLIENT_VERSION}
- )
-
-TARGET_LINK_LIBRARIES(${TARGET_SECURITY_CLIENT}
- ${SECURITY_SERVER_DEP_LIBRARIES}
- ${TARGET_SERVER_COMMON}
- )
################################################################################
################################################################################
-INSTALL(TARGETS ${TARGET_SECURITY_CLIENT} DESTINATION ${LIB_INSTALL_DIR})
INSTALL(TARGETS ${TARGET_SECURITY_MANAGER_CLIENT} DESTINATION ${LIB_INSTALL_DIR})
INSTALL(TARGETS ${TARGET_SECURITY_SERVER} DESTINATION bin)
################################################################################
-#CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
-#INSTALL
-
-################################################################################
-
ADD_SUBDIRECTORY(server)
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Contact: Bartlomiej Grzelewski <b.grzelewski@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
- */
-/*
- * @file client-app-permissions.cpp
- * @author Pawel Polawski (pawel.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This file contains implementation of
- * security_server_app_has_privilege function
- */
-
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <privilege-control.h>
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_app_has_privilege(const char *app_label,
- app_type_t app_type,
- const char *privilege_name,
- int *result)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
-
- LogDebug("security_server_app_has_privilege() called");
-
- try {
- if ((NULL == app_label) || (strlen(app_label) == 0)) {
- LogError("app_id is NULL or empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
- if ((NULL == privilege_name) || (strlen(privilege_name) == 0)) {
- LogError("privilege_name is NULL or empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
- if (NULL == result) {
- LogError("result is NULL");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- LogDebug("app_label: " << app_label);
- LogDebug("app_type: " << static_cast<int>(app_type));
- LogDebug("privilege_name: " << privilege_name);
-
- //put data into buffer
- Serialization::Serialize(send, static_cast<int>(PrivilegeCheckHdrs::CHECK_GIVEN_APP));
- Serialization::Serialize(send, std::string(app_label));
- Serialization::Serialize(send, static_cast<int>(app_type));
- Serialization::Serialize(send, std::string(privilege_name));
-
- //send buffer to server
- int apiResult = sendToServer(SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME, send.Pop(), recv);
- if (apiResult != SECURITY_SERVER_API_SUCCESS) {
- LogError("Error in sendToServer. Error code: " << apiResult);
- return apiResult;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, apiResult);
- if (apiResult == SECURITY_SERVER_API_SUCCESS) {
- Deserialization::Deserialize(recv, *result);
- }
- return apiResult;
-
- } catch (MessageBuffer::Exception::Base &e) {
- LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
- } catch (std::exception &e) {
- LogError("STD exception " << e.what());
- } catch (...) {
- LogError("Unknown exception occured");
- }
-
- return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-cookie.cpp
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This file contain implementation of cookie functions for getting cookies
- */
-
-
-#include <cstdio>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_get_cookie_size(void)
-{
- return SecurityServer::COOKIE_SIZE;
-}
-
-SECURITY_SERVER_API
-int security_server_request_cookie(char *cookie, size_t bufferSize)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
- std::vector<char> receivedCookie;
-
- LogDebug("security_server_request_cookie() called");
-
- return try_catch([&] {
- //checking parameters
- if (bufferSize < COOKIE_SIZE) {
- LogDebug("Buffer for cookie too small");
- return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
- }
- if (cookie == NULL) {
- LogDebug("Cookie pointer empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::GET_COOKIE);
-
- //send buffer to server
- int retval = sendToServer(SERVICE_SOCKET_COOKIE_GET, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return retval;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- if (retval != SECURITY_SERVER_API_SUCCESS)
- return retval;
-
- Deserialization::Deserialize(recv, receivedCookie);
- if (receivedCookie.size() != COOKIE_SIZE) {
- LogDebug("No match in cookie size");
- return SECURITY_SERVER_API_ERROR_BAD_RESPONSE;
- }
-
- memcpy(cookie, &receivedCookie[0], receivedCookie.size());
- return retval;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_get_cookie_pid(const char *cookie)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
- int pid;
- int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
- LogDebug("security_server_get_cookie_pid() called");
-
- if (cookie == NULL)
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- //preprae cookie to send
- std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
- return try_catch([&] {
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::CHECK_PID);
- Serialization::Serialize(send, key);
-
- //send buffer to server
- retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return retval;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- if (retval != SECURITY_SERVER_API_SUCCESS)
- return retval;
-
- Deserialization::Deserialize(recv, pid);
- return pid;
- });
-}
-
-SECURITY_SERVER_API
-char * security_server_get_smacklabel_cookie(const char *cookie)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
- int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
- std::string label;
-
- LogDebug("security_server_get_smacklabel_cookie() called");
-
- if (cookie == NULL)
- return NULL;
-
- //preprae cookie to send
- std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
- try {
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::CHECK_SMACKLABEL);
- Serialization::Serialize(send, key);
-
- //send buffer to server
- retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return NULL;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- if (retval != SECURITY_SERVER_API_SUCCESS)
- return NULL;
-
- Deserialization::Deserialize(recv, label);
-
- return strdup(label.c_str());
-
- } catch (MessageBuffer::Exception::Base &e) {
- LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
- } catch (std::exception &e) {
- LogDebug("STD exception " << e.what());
- } catch (...) {
- LogDebug("Unknown exception occured");
- }
-
- return NULL;
-}
-
-SECURITY_SERVER_API
-int security_server_check_privilege(const char *cookie, gid_t privilege)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
- int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
- LogDebug("security_server_check_privilege() called");
-
- if (cookie == NULL)
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- //preprae cookie to send
- std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
- return try_catch([&] {
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE_GID);
- Serialization::Serialize(send, key);
- Serialization::Serialize(send, (int)privilege);
-
- //send buffer to server
- retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return retval;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- return retval;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_cookie(
- const char *cookie SECURITY_SERVER_UNUSED,
- const char *object SECURITY_SERVER_UNUSED,
- const char *access_rights SECURITY_SERVER_UNUSED)
-{
-#if 0
- using namespace SecurityServer;
- MessageBuffer send, recv;
- int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
- LogDebug("security_server_check_privilege_by_cookie() called");
-
- if ((cookie == NULL) || (object == NULL) || (access_rights == NULL))
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- //preprae cookie to send
- std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
- std::string obj(object);
- std::string access(access_rights);
-
- return try_catch([&] {
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE);
- Serialization::Serialize(send, key);
- Serialization::Serialize(send, obj);
- Serialization::Serialize(send, access);
-
- //send buffer to server
- retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return retval;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- return retval;
- });
-#endif
- return SECURITY_SERVER_API_SUCCESS;
-}
-
-SECURITY_SERVER_API
-int security_server_get_uid_by_cookie(const char *cookie, uid_t *uid)
-{
- using namespace SecurityServer;
- MessageBuffer send, recv;
- int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
- LogDebug("security_server_get_uid_by_cookie() called");
-
- if ((cookie == NULL) || (uid == NULL))
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- //preprae cookie to send
- std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
- return try_catch([&] {
- //put data into buffer
- Serialization::Serialize(send, (int)CookieCall::CHECK_UID);
- Serialization::Serialize(send, key);
-
- //send buffer to server
- retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
- if (retval != SECURITY_SERVER_API_SUCCESS) {
- LogDebug("Error in sendToServer. Error code: " << retval);
- return retval;
- }
-
- //receive response from server
- Deserialization::Deserialize(recv, retval);
- if (retval == SECURITY_SERVER_API_SUCCESS) {
- int tmp;
- Deserialization::Deserialize(recv, tmp);
- *uid = static_cast<uid_t>(tmp);
- }
-
- return retval;
- });
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-get-gid.cpp
- * @author Jan Olszak (j.olszak@samsung.com)
- * @version 1.0
- * @brief This file constains implementation of get GID function.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_get_gid(const char *objectName) {
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (NULL == objectName){
- LogDebug("Objects name is NULL");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- int objectsNameLen = strlen(objectName);
- if (0 == objectsNameLen || objectsNameLen > SECURITY_SERVER_MAX_OBJ_NAME){
- LogDebug("Objects name is empty or too long");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
- Serialization::Serialize(send, std::string(objectName));
-
- int retCode = sendToServer(
- SERVICE_SOCKET_GET_GID,
- send.Pop(),
- recv);
-
- if (retCode != SECURITY_SERVER_API_SUCCESS)
- return retCode;
-
- Deserialization::Deserialize(recv, retCode);
-
- // Return if errors
- if (retCode < 0)
- return retCode;
-
- // No errors, return gid
- gid_t gid;
- Deserialization::Deserialize(recv, gid);
- return static_cast<int>(gid);
- });
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-password.cpp
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief This file contains implementation of password functions.
- */
-
-#include <cstring>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-
-namespace {
-
-inline bool isPasswordIncorrect(const char* pwd)
-{
- return (pwd == NULL || strlen(pwd) == 0 || strlen(pwd) > SecurityServer::MAX_PASSWORD_LEN);
-}
-
-} // namespace anonymous
-
-SECURITY_SERVER_API
-int security_server_is_pwd_valid(unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (NULL == current_attempts || NULL == max_attempts ||
- NULL == valid_secs) {
-
- LogError("Wrong input param");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
-
- *current_attempts = 0;
- *max_attempts = 0;
- *valid_secs = 0;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_IS_PWD_VALID));
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogDebug("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- if(retCode == SECURITY_SERVER_API_ERROR_PASSWORD_EXIST) {
- Deserialization::Deserialize(recv, *current_attempts);
- Deserialization::Deserialize(recv, *max_attempts);
- Deserialization::Deserialize(recv, *valid_secs);
- }
-
- return retCode;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_chk_pwd(const char *challenge,
- unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (current_attempts == NULL || max_attempts == NULL || valid_secs == NULL ||
- isPasswordIncorrect(challenge)) {
- LogError("Wrong input param");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
-
- *current_attempts = 0;
- *max_attempts = 0;
- *valid_secs = 0;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PWD));
- Serialization::Serialize(send, std::string(challenge));
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogDebug("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- switch (retCode) {
- case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
- case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
- case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
- case SECURITY_SERVER_API_SUCCESS:
- Deserialization::Deserialize(recv, *current_attempts);
- Deserialization::Deserialize(recv, *max_attempts);
- Deserialization::Deserialize(recv, *valid_secs);
- break;
- default:
- break;
- }
-
- return retCode;
- });
-}
-
-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)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (NULL == cur_pwd)
- cur_pwd = "";
-
- if (isPasswordIncorrect(new_pwd) || strlen(cur_pwd) > MAX_PASSWORD_LEN) {
- LogError("Wrong input param.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD));
- Serialization::Serialize(send, std::string(cur_pwd));
- Serialization::Serialize(send, std::string(new_pwd));
- Serialization::Serialize(send, max_challenge);
- Serialization::Serialize(send, valid_period_in_days);
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- MessageBuffer send, recv;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_VALIDITY));
- Serialization::Serialize(send, valid_period_in_days);
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- MessageBuffer send, recv;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE));
- Serialization::Serialize(send, max_challenge);
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_reset_pwd(const char *new_pwd,
- const unsigned int max_challenge,
- const unsigned int valid_period_in_days)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (isPasswordIncorrect(new_pwd)) {
- LogError("Wrong input param.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_RST_PWD));
- Serialization::Serialize(send, std::string(new_pwd));
- Serialization::Serialize(send, max_challenge);
- Serialization::Serialize(send, valid_period_in_days);
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_RESET, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_history(int history_size)
-{
- using namespace SecurityServer;
-
- return try_catch([&] {
- if (history_size > static_cast<int>(MAX_PASSWORD_HISTORY) || history_size < 0) {
- LogError("Wrong input param.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_HISTORY));
- Serialization::Serialize(send, static_cast<unsigned int>(history_size));
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (SECURITY_SERVER_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
-}
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-check-privilege-by-pid.cpp
- * @author Jan Cybulski (j.cybulski@samsung.com)
- * @version 1.0
- * @brief This file constains implementation of security-server API for
- * checking privilege by process id.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-#include <signal.h>
-
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_pid(
- int pid SECURITY_SERVER_UNUSED,
- const char *object SECURITY_SERVER_UNUSED,
- const char *access_rights SECURITY_SERVER_UNUSED)
-{
-#if 0
- using namespace SecurityServer;
- return try_catch([&] {
- if (1 != smack_check())
- return SECURITY_SERVER_API_SUCCESS;
-
- // Checking whether a process with pid exists
- if ((pid < 0) || ((kill(pid, 0) == -1) && (errno == ESRCH))) {
- LogDebug("pid is invalid, process: " << pid << " does not exist");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- if (NULL == object || 0 == strlen(object)) {
- LogDebug("object param is NULL or empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- if (NULL == access_rights || 0 == strlen(access_rights)) {
- LogDebug("access_right param is NULL or empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
- Serialization::Serialize(send, pid);
- Serialization::Serialize(send, std::string(object));
- Serialization::Serialize(send, std::string(access_rights));
-
- int result = sendToServer(
- SERVICE_SOCKET_PRIVILEGE_BY_PID,
- send.Pop(),
- recv);
-
- if (result != SECURITY_SERVER_API_SUCCESS)
- return result;
-
- Deserialization::Deserialize(recv, result);
- return result;
- });
-#endif
- return SECURITY_SERVER_API_SUCCESS;
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-shared-memory.cpp
- * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version 1.0
- * @brief This file constains implementation of shared memory api.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_app_give_access(const char *customer_label, int customer_pid) {
- using namespace SecurityServer;
- return try_catch([&] {
- if (1 != smack_check())
- return SECURITY_SERVER_API_SUCCESS;
-
- if (NULL == customer_label || 0 == strlen(customer_label))
- {
- LogDebug("customer_label is NULL or empty");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- MessageBuffer send, recv;
- Serialization::Serialize(send, std::string(customer_label));
- Serialization::Serialize(send, customer_pid);
-
- int result = sendToServer(
- SERVICE_SOCKET_SHARED_MEMORY,
- send.Pop(),
- recv);
-
- if (result != SECURITY_SERVER_API_SUCCESS)
- return result;
-
- Deserialization::Deserialize(recv, result);
- return result;
- });
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file client-socket-privilege.cpp
- * @author Zofia Abramowska (z.abramowska@samsung.com)
- * @version 1.0
- * @brief This file constains implementation of socket privilege api.
- */
-#include <memory>
-
-#include <sys/socket.h>
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-
-#include <security-server.h>
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_sockfd(
- int sockfd SECURITY_SERVER_UNUSED,
- const char *object SECURITY_SERVER_UNUSED,
- const char *access_rights SECURITY_SERVER_UNUSED)
-{
-#if 0
- char *subject = NULL;
- int ret;
- std::string path;
- std::unique_ptr<char, void (*)(void*)throw ()> subjectPtr(NULL, std::free);
-
- //for get socket options
- struct ucred cr;
- socklen_t len = sizeof(struct ucred);
-
- //SMACK runtime check
- if (!SecurityServer::smack_runtime_check())
- {
- LogDebug("No SMACK support on device");
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- if (sockfd < 0 || !object || !access_rights)
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- ret = smack_new_label_from_socket(sockfd, &subject);
- if (ret >= 0) {
- subjectPtr.reset(subject);
- subject = NULL;
- } else {
- LogError("Failed to get new label from socket. Object="
- << object << ", access=" << access_rights
- << ", error=" << strerror(errno));
- return SECURITY_SERVER_API_ERROR_SOCKET;
- }
-
- ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
- if (ret < 0) {
- LogError("Error in getsockopt(). Errno: "
- << strerror(errno) << ", subject="
- << (subjectPtr.get() ? subjectPtr.get() : "NULL")
- << ", object=" << object << ", access=" << access_rights
- << ", error=" << strerror(errno));
- return SECURITY_SERVER_API_ERROR_SOCKET;
- }
-
- return security_server_check_privilege_by_pid(cr.pid, object, access_rights);
-#endif
- return SECURITY_SERVER_API_SUCCESS;
-}
-
-SECURITY_SERVER_API
-char *security_server_get_smacklabel_sockfd(int fd)
-{
- char *label = NULL;
-
- if (!SecurityServer::smack_check())
- {
- LogDebug("No SMACK support on device");
- label = (char*) malloc(1);
- if (label) label[0] = '\0';
- return label;
- }
-
- if (smack_new_label_from_socket(fd, &label) < 0)
- {
- LogError("Client ERROR: Unable to get socket SMACK label");
- return NULL;
- }
-
- return label;
-}
namespace SecurityServer {
#define SOCKET_PATH_PREFIX "/run/"
-#define SOCKET_PATH_PREFIX_SECURITY_SERVER SOCKET_PATH_PREFIX "security-server/"
#define SOCKET_PATH_PREFIX_SECURITY_MANAGER SOCKET_PATH_PREFIX "security-manager/"
-char const * const SERVICE_SOCKET_SHARED_MEMORY =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-data-share.socket";
-char const * const SERVICE_SOCKET_GET_GID =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-get-gid.socket";
-char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-privilege-by-pid.socket";
-char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-app-privilege-by-name.socket";
-char const * const SERVICE_SOCKET_COOKIE_GET =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-cookie-get.socket";
-char const * const SERVICE_SOCKET_COOKIE_CHECK =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-cookie-check.socket";
-char const * const SERVICE_SOCKET_PASSWD_CHECK =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-password-check.socket";
-char const * const SERVICE_SOCKET_PASSWD_SET =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-password-set.socket";
-char const * const SERVICE_SOCKET_PASSWD_RESET =
- SOCKET_PATH_PREFIX_SECURITY_SERVER "security-server-api-password-reset.socket";
-
char const * const SERVICE_SOCKET_INSTALLER =
SOCKET_PATH_PREFIX_SECURITY_MANAGER "security-manager-installer.socket";
-const size_t COOKIE_SIZE = 20;
-
-const size_t MAX_PASSWORD_LEN = 32;
-const unsigned int MAX_PASSWORD_HISTORY = 50;
-const unsigned int PASSWORD_INFINITE_EXPIRATION_DAYS = 0;
-const unsigned int PASSWORD_INFINITE_ATTEMPT_COUNT = 0;
-const unsigned int PASSWORD_API_NO_EXPIRATION = 0xFFFFFFFF;
-
-const int SECURITY_SERVER_MAX_OBJ_NAME = 30;
-
} // namespace SecurityServer
#ifndef _SECURITY_SERVER_PROTOCOLS_
#define _SECURITY_SERVER_PROTOCOLS_
-#include <cstddef>
-#include <time.h>
#include <vector>
-#include <utility>
#include <string>
struct app_inst_req {
namespace SecurityServer {
-extern char const * const SERVICE_SOCKET_SHARED_MEMORY;
-extern char const * const SERVICE_SOCKET_GET_GID;
-extern char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID;
-extern char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME;
-extern char const * const SERVICE_SOCKET_COOKIE_GET;
-extern char const * const SERVICE_SOCKET_COOKIE_CHECK;
-extern char const * const SERVICE_SOCKET_PASSWD_CHECK;
-extern char const * const SERVICE_SOCKET_PASSWD_SET;
-extern char const * const SERVICE_SOCKET_PASSWD_RESET;
extern char const * const SERVICE_SOCKET_INSTALLER;
-enum class AppPermissionsAction { ENABLE, DISABLE };
-
-enum class CookieCall
-{
- GET_COOKIE,
- CHECK_PID,
- CHECK_SMACKLABEL,
- CHECK_PRIVILEGE_GID,
- CHECK_PRIVILEGE,
- CHECK_GID,
- CHECK_UID
-};
-
-enum class PrivilegeCheckHdrs
-{
- CHECK_GIVEN_APP,
- CHECK_CALLER_APP
-};
-extern const size_t COOKIE_SIZE;
-
-enum class PasswordHdrs
-{
- HDR_IS_PWD_VALID,
- HDR_CHK_PWD,
- HDR_SET_PWD,
- HDR_SET_PWD_VALIDITY,
- HDR_SET_PWD_MAX_CHALLENGE,
- HDR_RST_PWD,
- HDR_SET_PWD_HISTORY
-};
-
enum class SecurityModuleCall
{
APP_INSTALL,
APP_UNINSTALL
};
-extern const size_t MAX_PASSWORD_LEN;
-extern const unsigned int MAX_PASSWORD_HISTORY;
-extern const unsigned int PASSWORD_INFINITE_EXPIRATION_DAYS;
-extern const unsigned int PASSWORD_INFINITE_ATTEMPT_COUNT;
-extern const unsigned int PASSWORD_API_NO_EXPIRATION;
-
-extern const int SECURITY_SERVER_MAX_OBJ_NAME;
-
} // namespace SecuritySever
#endif // _SECURITY_SERVER_PROTOCOLS_
#include <socket-manager.h>
-#include <data-share.h>
-#include <get-gid.h>
-#include <privilege-by-pid.h>
-#include <app-permissions.h>
-#include <cookie.h>
-#include <password.h>
#include <installer.h>
IMPLEMENT_SAFE_SINGLETON(SecurityServer::Log::LogSystem);
LogInfo("Start!");
SecurityServer::SocketManager manager;
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::CookieService);
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::SharedMemoryService);
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::GetGidService);
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::PrivilegeByPidService);
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::AppPermissionsService);
- REGISTER_SOCKET_SERVICE(manager, SecurityServer::PasswordService);
REGISTER_SOCKET_SERVICE(manager, SecurityServer::InstallerService);
manager.MainLoop();
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Contact: Bartlomiej Grzelewski <b.grzelewski@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
- */
-/*
- * @file app-permissions.cpp
- * @author Pawel Polawski (pawel.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This file contains implementation of security_server_app_has_permission
- * on server side
- */
-
-#include <memory>
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-#include <privilege-control.h>
-
-#include <sys/smack.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <app-permissions.h>
-#include <protocols.h>
-#include <security-server.h>
-#include <privilege-control.h>
-
-namespace {
-
-int privilegeToSecurityServerError(int error) {
- switch (error) {
- case PC_OPERATION_SUCCESS: return SECURITY_SERVER_API_SUCCESS;
- case PC_ERR_FILE_OPERATION: return SECURITY_SERVER_API_ERROR_UNKNOWN;
- case PC_ERR_MEM_OPERATION: return SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
- case PC_ERR_NOT_PERMITTED: return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
- case PC_ERR_INVALID_PARAM: return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- case PC_ERR_INVALID_OPERATION:
- case PC_ERR_DB_OPERATION:
- default:
- ;
- }
- return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
-
-// interface ids
-const SecurityServer::InterfaceID CHECK_APP_PRIVILEGE = 1;
-
-} // namespace anonymous
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector AppPermissionsService::GetServiceDescription() {
- return ServiceDescriptionVector {
- { SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME,
- "security-server::api-app-privilege-by-name",
- CHECK_APP_PRIVILEGE }
- };
-}
-
-void AppPermissionsService::accept(const AcceptEvent &event) {
- LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.interfaceID = event.interfaceID;
-}
-
-void AppPermissionsService::write(const WriteEvent &event) {
- LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-void AppPermissionsService::process(const ReadEvent &event) {
- LogDebug("Read event for counter: " << event.connectionID.counter);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void AppPermissionsService::close(const CloseEvent &event) {
- LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-bool AppPermissionsService::processOne(const ConnectionID &conn,
- MessageBuffer &buffer,
- InterfaceID interfaceID)
-{
- LogDebug("Begin of an iteration");
-
- //waiting for all data
- if (!buffer.Ready()) {
- return false;
- }
-
- LogDebug("Entering app_permissions server side handler");
-
- switch(interfaceID) {
-
- case CHECK_APP_PRIVILEGE:
- return processCheckAppPrivilege(conn, buffer);
-
- default:
- LogDebug("Unknown interfaceId. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-}
-
-bool AppPermissionsService::processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer)
-{
- MessageBuffer send;
- std::string privilege_name;
- std::string app_label;
- int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- app_type_t app_type;
- bool has_permission = false;
- PrivilegeCheckHdrs checkType = PrivilegeCheckHdrs::CHECK_GIVEN_APP;
-
- LogDebug("Processing app privilege check request");
-
- //receive data from buffer
- Try {
- int temp;
- Deserialization::Deserialize(buffer, temp); // call type
- checkType = static_cast<PrivilegeCheckHdrs>(temp);
- LogDebug("App privilege check call type: "
- << (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP ?
- "CHECK_GIVEN_APP":"CHECK_CALLER_APP"));
- if (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP) { //app_label present only in this case
- Deserialization::Deserialize(buffer, app_label); //get app_label
- }
- Deserialization::Deserialize(buffer, temp); //get app type
- app_type = static_cast<app_type_t>(temp);
-
- Deserialization::Deserialize(buffer, privilege_name); //get privilege name
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- //print received data
- LogDebug("app_label: " << app_label);
- LogDebug("app_type: " << static_cast<int>(app_type));
- LogDebug("privilege_name: " << privilege_name);
-
- LogDebug("Calling perm_app_has_permission()");
- result = perm_app_has_permission(app_label.c_str(), app_type, privilege_name.c_str(), &has_permission);
- LogDebug("perm_app_has_permission() returned: " << result << " , permission enabled: " << has_permission);
-
- //send response
- Serialization::Serialize(send, privilegeToSecurityServerError(result));
- Serialization::Serialize(send, static_cast<int>(has_permission));
- m_serviceManager->Write(conn, send.Pop());
- return true;
-}
-
-} // namespace SecurityServer
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Contact: Bartlomiej Grzelewski <b.grzelewski@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
- */
-/*
- * @file app-permissions.h
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This function contains header for implementation of
- * security_server_app_has_permissions on server side
- */
-
-#ifndef _SECURITY_SERVER_APP_PERMISSIONS_
-#define _SECURITY_SERVER_APP_PERMISSIONS_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-
-namespace SecurityServer {
-
-class AppPermissionsService :
- public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<AppPermissionsService>
-{
-public:
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-
-private:
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
-
- bool processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer);
-
- ConnectionInfoMap m_connectionInfoMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
+++ /dev/null
-#include <cookie-common.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <dpl/log/log.h>
-
-namespace SecurityServer {
-
-int getPidPath(char *path, unsigned int pathSize, int pid)
-{
- int retval;
- char link[pathSize];
-
- snprintf(link, pathSize, "/proc/%d/exe", pid);
- retval = readlink(link, path, pathSize-1);
- if (retval < 0) {
- LogDebug("Unable to get process path");
- return -1;
- }
- path[retval] = '\0';
-
- return 0;
-}
-
-} // namespace SecurityServer
+++ /dev/null
-/*
- * security-server
- *
- * Copyright (c) 2000 - 2013 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 _COOKIE_COMMON_H_
-#define _COOKIE_COMMON_H_
-
-namespace SecurityServer {
-
-/*
- * Simple function for translating PID to process path
- */
-int getPidPath(char *path, unsigned int pathSize, int pid);
-
-} // namespace SecurityServer
-
-#endif // _COOKIE_COMMON_H_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file cookie-jar.cpp
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This function contain implementation of CookieJar class which holds cookies structures
- */
-
-#include <cookie-jar.h>
-#include <protocols.h>
-#include <cookie-common.h>
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-#include <vector>
-#include <stdbool.h>
-#include <unistd.h>
-#include <smack-check.h>
-#include <privilege-control.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <fstream>
-#include <linux/limits.h>
-#include <signal.h>
-#include <errno.h>
-#include <smack-common.h>
-
-namespace SecurityServer {
-
-CookieJar::CookieJar(void)
- : m_position(0)
-{
- LogDebug("Created CookieJar for handling cookies");
-}
-
-CookieJar::~CookieJar(void)
-{
- LogDebug("Deleted CookieJar");
-}
-
-const Cookie * CookieJar::GenerateCookie(int pid)
-{
- char key[COOKIE_SIZE];
- int retval;
-
- LogDebug("Cookie creation called");
-
- //create empty cookie class
- Cookie newCookie;
- newCookie.pid = pid;
-
- //check if there is no cookie for specified PID
- const Cookie *searchResult = SearchCookie(newCookie, CompareType::PID);
- if (searchResult != NULL) {
- LogDebug("Cookie exist for specified PID");
- return searchResult;
- }
-
- searchResult = &newCookie; //only for searchResult != NULL during while loop init
- while(searchResult != NULL) {
- //generate unique key
- std::ifstream urandom("/dev/urandom", std::ifstream::binary);
- urandom.read(key, COOKIE_SIZE);
- newCookie.cookieId.assign(key, key + COOKIE_SIZE);
-
- //check if key is unique
- searchResult = SearchCookie(newCookie, CompareType::COOKIE_ID);
- if (searchResult != NULL)
- LogDebug("Key is not unique");
- }
-
- //obtain process path
- char path[PATH_MAX];
- retval = getPidPath(path, PATH_MAX, pid);
- if (retval < 0) {
- LogDebug("Unable to get process path");
- return NULL;
- }
- newCookie.binaryPath = path;
-
- //get smack label if smack enabled
- if (smack_check()) {
- char label[SMACK_LABEL_LEN + 1];
- if (-1 == get_smack_label_from_process(pid, label)) {
- LogDebug("Unable to get smack label of process");
- return NULL;
- }
- newCookie.smackLabel = label;
- } else
- newCookie.smackLabel = "";
-
-
- //get GID list
- const int NAME_SIZE = 64;
- char filename[NAME_SIZE];
-
- snprintf(filename, NAME_SIZE, "/proc/%d/status", pid);
- std::ifstream status(filename, std::ifstream::binary);
- std::string line;
-
- while (std::getline(status, line)) { //read line from file
- const char *tmp = line.c_str();
- if (strncmp(line.c_str(), "Uid:", 4) == 0)
- newCookie.uid = atoi(&tmp[5]);
- else if (strncmp(line.c_str(), "Gid:", 4) == 0)
- newCookie.gid = atoi(&tmp[5]);
- else if (strncmp(line.c_str(), "Groups:", 7) == 0) {
- char delim[] = ": "; //separators for strtok: ' ' and ':'
- char *token = strtok(const_cast<char *>(tmp), delim); //1st string is "Group:"
- while ((token = strtok(NULL, delim))) {
- int gid = atoi(token);
- newCookie.permissions.push_back(gid);
- }
- }
- }
-
- //DEBUG ONLY
- //print info about cookie
- LogDebug("Cookie created");
- LogDebug("PID: " << newCookie.pid);
- LogDebug("UID: " << newCookie.uid);
- LogDebug("GID: " << newCookie.gid);
- LogDebug("PATH: " << newCookie.binaryPath);
- LogDebug("LABEL: " << newCookie.smackLabel);
- for (size_t k = 0; k < newCookie.permissions.size(); k++)
- LogDebug("GID: " << newCookie.permissions[k]);
-
- //only when cookie ready store it
- m_cookieList.push_back(newCookie);
- return &m_cookieList[m_cookieList.size() - 1];
-}
-
-void CookieJar::DeleteCookie(const Cookie &pattern, CompareType criterion)
-{
- if (m_cookieList.size() == 0) {
- LogDebug("Cookie list empty");
- return;
- }
-
- //for each cookie in list
- for (size_t i = 0; i < m_cookieList.size();) {
- if (CompareCookies(pattern, m_cookieList[i], criterion)) {
- LogDebug("Deleting cookie");
- if (i != m_cookieList.size() - 1)
- m_cookieList[i] = *m_cookieList.rbegin();
- m_cookieList.pop_back();
- } else
- ++i;
- }
-}
-
-const Cookie * CookieJar::SearchCookie(const Cookie &pattern, CompareType criterion) const
-{
- LogDebug("Searching for cookie");
-
- if (m_cookieList.size() == 0) {
- LogDebug("Cookie list empty");
- return NULL;
- }
-
- //for each cookie in list
- for (size_t i = 0; i < m_cookieList.size(); i++) {
- if (CompareCookies(pattern, m_cookieList[i], criterion)) {
- LogDebug("Cookie found");
- return &(m_cookieList[i]);
- }
- }
-
- LogDebug("Cookie not found");
- return NULL;
-}
-
-bool CookieJar::CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const
-{
- size_t permSize1 = c1.permissions.size();
- size_t permSize2 = c2.permissions.size();
-
- switch(criterion) {
- case CompareType::COOKIE_ID:
- return (c1.cookieId == c2.cookieId);
-
- case CompareType::PID:
- return (c1.pid == c2.pid);
-
- case CompareType::PATH:
- return (c1.binaryPath == c2.binaryPath);
-
- case CompareType::SMACKLABEL:
- return (c1.smackLabel == c2.smackLabel);
-
- case CompareType::PERMISSIONS:
- //we search for at least one the same GID
- for(size_t i = 0; i < permSize1; i++)
- for (size_t k = 0; k < permSize2; k++)
- if (c1.permissions[i] == c2.permissions[k])
- return true;
- return false;
-
- case CompareType::UID:
- return (c1.uid == c2.uid);
-
- case CompareType::GID:
- return (c1.gid == c2.gid);
-
- default:
- LogDebug("Wrong function parameters");
- return false;
- };
-}
-
-void CookieJar::GarbageCollector(size_t howMany)
-{
- if ((howMany == 0) || (howMany > m_cookieList.size())) {
- howMany = m_cookieList.size();
- }
-
- for (size_t i = 0; i < howMany; ++i) {
-
- if (m_position >= m_cookieList.size()) {
- m_position = 0;
- }
-
- if (kill(m_cookieList[m_position].pid, 0) && (errno == ESRCH)) {
- LogDebug("Cookie deleted " << " PID:" << m_cookieList[m_position].pid);
- if (m_position != (m_cookieList.size()-1))
- m_cookieList[m_position] = *m_cookieList.rbegin();
- m_cookieList.pop_back();
- } else {
- ++m_position;
- }
- }
-}
-
-} // namespace SecurityServer
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file cookie-jar.h
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This function contain header of CookieJar class which holds cookies structures
- */
-
-#ifndef _SECURITY_SERVER_COOKIE_JAR_
-#define _SECURITY_SERVER_COOKIE_JAR_
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-#include <vector>
-#include <stdbool.h>
-
-
-namespace SecurityServer {
-
-enum class CompareType
-{
- COOKIE_ID,
- PID,
- PATH,
- SMACKLABEL,
- PERMISSIONS,
- UID,
- GID
-};
-
-
-struct Cookie
-{
- std::vector<char> cookieId; //ID key
- pid_t pid; //owner PID
- uid_t uid; //owner UID
- gid_t gid; //owner GID
- std::string binaryPath; //path to owner binary
- std::string smackLabel; //owner SMACK label
- std::vector<int> permissions; //owner GIDs
-};
-
-
-class CookieJar
-{
-public:
- CookieJar(void);
- virtual ~CookieJar(void);
-
- const Cookie * GenerateCookie(int pid);
- void DeleteCookie(const Cookie &pattern, CompareType criterion);
-
- const Cookie * SearchCookie(const Cookie &pattern, CompareType criterion) const;
- bool CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const;
-
- // howMany - number of cookies that will be checked.
- // Set howMay to 0 to check all cookies.
- void GarbageCollector(size_t howMany);
-
-private:
- size_t m_position;
- std::vector<Cookie> m_cookieList;
-};
-
-
-} // namespace SecurityServer
-#endif // _SECURITY_SERVER_COOKIE_JAR_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file cookie.cpp
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This function contain implementation of CookieService
- */
-
-#include <memory>
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-#include <protocols.h>
-#include <cookie-common.h>
-#include <security-server.h>
-#include <cookie.h>
-#include <smack-check.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/smack.h>
-#include <linux/limits.h>
-
-//interfaces ID
-const int INTERFACE_GET = 0;
-const int INTERFACE_CHECK = 1;
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector CookieService::GetServiceDescription() {
- return ServiceDescriptionVector {
- {SERVICE_SOCKET_COOKIE_GET, "*", INTERFACE_GET },
- {SERVICE_SOCKET_COOKIE_CHECK, "security-server::api-cookie-check", INTERFACE_CHECK}
- };
- }
-
-void CookieService::accept(const AcceptEvent &event) {
- LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.interfaceID = event.interfaceID;
-}
-
-void CookieService::write(const WriteEvent &event) {
- LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-void CookieService::process(const ReadEvent &event) {
- LogDebug("Read event for counter: " << event.connectionID.counter);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void CookieService::close(const CloseEvent &event) {
- LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-bool CookieService::processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID)
-{
- LogDebug("Iteration begin");
- MessageBuffer send, recv;
- CookieCall msgType;
- bool removeGarbage = false;
-
- //waiting for all data
- if (!buffer.Ready()) {
- return false;
- }
-
- //receive data from buffer and check MSG_ID
- Try {
- int msgTypeInt;
- Deserialization::Deserialize(buffer, msgTypeInt); //receive MSG_ID
- msgType = static_cast<CookieCall>(msgTypeInt);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- bool retval = false;
-
- //use received data
- if (interfaceID == INTERFACE_GET) {
- switch(msgType) {
- case CookieCall::GET_COOKIE:
- LogDebug("Entering get-cookie server side handler");
- retval = cookieRequest(send, conn.sock);
- removeGarbage = true;
- break;
-
- default:
- LogDebug("Error, unknown function called by client");
- retval = false;
- break;
- };
- } else if (interfaceID == INTERFACE_CHECK) {
- switch(msgType) {
- case CookieCall::CHECK_PID:
- LogDebug("Entering pid-by-cookie server side handler");
- retval = pidByCookieRequest(buffer, send);
- break;
-
- case CookieCall::CHECK_SMACKLABEL:
- LogDebug("Entering smacklabel-by-cookie server side handler");
- retval = smackLabelByCookieRequest(buffer, send);
- break;
-
- case CookieCall::CHECK_PRIVILEGE_GID:
- LogDebug("Entering check-privilege-by-cookie-gid server side handler");
- retval = privilegeByCookieGidRequest(buffer, send);
- break;
-
- case CookieCall::CHECK_PRIVILEGE:
- LogDebug("Entering check-privilege-by-cookie side handler");
- retval = privilegeByCookieRequest(buffer, send);
- break;
-
- case CookieCall::CHECK_UID:
- LogDebug("Entering get-uid-by-cookie side handler");
- retval = uidByCookieRequest(buffer, send);
- break;
-
- case CookieCall::CHECK_GID:
- LogDebug("Entering get-gid-by-cookie side handler");
- retval = gidByCookieRequest(buffer, send);
- break;
-
- default:
- LogDebug("Error, unknown function called by client");
- retval = false;
- break;
- };
- } else {
- LogDebug("Error, wrong interface");
- retval = false;
- }
-
- if (retval) {
- //send response
- m_serviceManager->Write(conn, send.Pop());
- } else {
- LogDebug("Closing socket because of error");
- m_serviceManager->Close(conn);
- }
-
- // Each time you add one cookie check 2 others.
- if (removeGarbage)
- m_cookieJar.GarbageCollector(2);
-
- return retval;
-}
-
-bool CookieService::cookieRequest(MessageBuffer &send, int socket)
-{
- struct ucred cr;
- unsigned len = sizeof(cr);
-
- if (0 != getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &cr, &len))
- return false;
-
- const Cookie *generatedCookie = m_cookieJar.GenerateCookie(cr.pid);
-
- if (generatedCookie == NULL) {
- //unable to create cookie
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_UNKNOWN);
- return true;
- }
-
- //checking if binary path match created / found cookie
- char path[PATH_MAX];
- int ret = getPidPath(path, PATH_MAX, cr.pid);
-
- if (ret < 0) {
- LogError("Unable to check process binary path");
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_UNKNOWN);
- } else {
- if (generatedCookie->binaryPath.compare(path)) {
- LogDebug("Found cookie but no match in bin path");
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_UNKNOWN);
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- Serialization::Serialize(send, generatedCookie->cookieId);
- }
- }
-
- return true;
-}
-
-bool CookieService::pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- Serialization::Serialize(send, (int)searchResult->pid);
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
- }
-
- return true;
-}
-
-bool CookieService::smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- Serialization::Serialize(send, searchResult->smackLabel);
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
- }
-
- return true;
-}
-
-bool CookieService::privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
- int gid;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- Deserialization::Deserialize(buffer, gid);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL)
- //search for specified GID on permissions list
- for (size_t i = 0; i < searchResult->permissions.size(); i++)
- if (searchResult->permissions[i] == gid) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- return true;
- }
-
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
-
- return true;
-}
-
-bool CookieService::privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
- std::string subject;
- std::string object;
- std::string access;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- Deserialization::Deserialize(buffer, object);
- Deserialization::Deserialize(buffer, access);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL) {
- if (!smack_check()) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- } else {
- subject = searchResult->smackLabel;
- int retval;
-
- if ((retval = smack_have_access(subject.c_str(), object.c_str(), access.c_str())) == 1)
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
- LogSmackAudit("SS_SMACK: "
- << " subject=" << subject
- << ", object=" << object
- << ", access=" << access
- << ", result=" << retval);
- }
- }
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
- }
-
- return true;
-}
-
-bool CookieService::uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- Serialization::Serialize(send, (int)searchResult->uid);
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
- }
-
- return true;
-}
-
-bool CookieService::gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
- std::vector<char> cookieKey;
-
- Try {
- Deserialization::Deserialize(buffer, cookieKey);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- return false;
- }
-
- Cookie searchPattern;
- searchPattern.cookieId = cookieKey;
-
- const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
- if (searchResult != NULL) {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
- Serialization::Serialize(send, (int)searchResult->gid);
- } else {
- Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
- }
-
- return true;
-}
-
-} // namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file cookie.h
- * @author Pawel Polawski (p.polawski@partner.samsung.com)
- * @version 1.0
- * @brief This function contain header for implementation of cookie get API
- */
-
-#ifndef _SECURITY_SERVER_COOKIE_GET_
-#define _SECURITY_SERVER_COOKIE_GET_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-#include <cookie-jar.h>
-
-namespace SecurityServer {
-
-class CookieService :
- public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<CookieService>
-{
-public:
-
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-
-private:
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
-
- bool cookieRequest(MessageBuffer &send, int socket);
-
- bool pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
- bool smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
- bool privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send);
- bool privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-
- bool uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
- bool gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-
- CookieJar m_cookieJar;
-
- ConnectionInfoMap m_connectionInfoMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file data-share.cpp
- * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version 1.0
- * @brief Implementation of api-data-share service.
- */
-
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <data-share.h>
-#include <security-server.h>
-#include <security-server-util.h>
-#include <smack-check.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector SharedMemoryService::GetServiceDescription() {
- return ServiceDescriptionVector
- {{SERVICE_SOCKET_SHARED_MEMORY, "security-server::api-data-share"}};
-}
-
-void SharedMemoryService::accept(const AcceptEvent &event) {
- LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
-}
-
-void SharedMemoryService::write(const WriteEvent &event) {
- LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-bool SharedMemoryService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
- LogDebug("Iteration begin");
- static const char * const revoke = "-----";
- static const char * const permissions = "rwxat";
- char *providerLabel = NULL;
- std::string clientLabel;
- int clientPid = 0;
- int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- struct smack_accesses *smack = NULL;
-
- if (!buffer.Ready()) {
- return false;
- }
-
- Try {
- Deserialization::Deserialize(buffer, clientLabel);
- Deserialization::Deserialize(buffer, clientPid);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- if (smack_check()) {
- if (0 > smack_new_label_from_socket(conn.sock, &providerLabel)) {
- LogDebug("Error in smack_new_label_from_socket");
- retCode = SECURITY_SERVER_API_ERROR_GETTING_SOCKET_LABEL_FAILED;
- goto end;
- }
-
- if (!util_smack_label_is_valid(clientLabel.c_str())) {
- LogDebug("Invalid smack label: " << clientLabel);
- retCode = SECURITY_SERVER_API_ERROR_BAD_REQUEST;
- goto end;
- }
-
- if (smack_accesses_new(&smack)) {
- LogDebug("Error in smack_accesses_new");
- goto end;
- }
-
- if (smack_accesses_add_modify(smack, clientLabel.c_str(), providerLabel,
- permissions, revoke))
- {
- LogDebug("Error in smack_accesses_add_modify");
- goto end;
- }
-
- if (smack_accesses_apply(smack)) {
- LogDebug("Error in smack_accesses_apply");
- retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
- goto end;
- }
- LogDebug("Access granted. Subject: " << clientLabel << " Provider: " << providerLabel);
- }
- retCode = SECURITY_SERVER_API_SUCCESS;
-end:
- free(providerLabel);
- smack_accesses_free(smack);
-
- MessageBuffer sendBuffer;
- Serialization::Serialize(sendBuffer, retCode);
- m_serviceManager->Write(conn, sendBuffer.Pop());
- return true;
-}
-
-void SharedMemoryService::process(const ReadEvent &event) {
- LogDebug("Read event for counter: " << event.connectionID.counter);
- auto &buffer = m_messageBufferMap[event.connectionID.counter];
- buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, buffer));
-}
-
-void SharedMemoryService::close(const CloseEvent &event) {
- LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file data-share.h
- * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version 1.0
- * @brief Implementation of api-data-share
- */
-
-#ifndef _SECURITY_SERVER_DATA_SHARE_
-#define _SECURITY_SERVER_DATA_SHARE_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class SharedMemoryService
- : public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<SharedMemoryService>
-{
-public:
- typedef std::map<int, MessageBuffer> MessageBufferMap;
-
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-private:
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-
- MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_DATA_SHARE_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file get-gid.cpp
- * @author Jan Olszak (j.olszak@samsung.com)
- * @version 1.0
- * @brief Implementation of api-get-gid service.
- */
-
-#include <unistd.h>
-#include <sys/smack.h>
-#include <grp.h>
-#include <unistd.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <get-gid.h>
-#include <security-server.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector GetGidService::GetServiceDescription() {
- return ServiceDescriptionVector
- {{SERVICE_SOCKET_GET_GID, "security-server::api-get-gid"}};
-}
-
-void GetGidService::accept(const AcceptEvent &event) {
- LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
-}
-
-void GetGidService::write(const WriteEvent &event) {
- LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-
-/*
- * Searches for group ID by given group name
- */
-int GetGidService::setGid(std::string& obj)
-{
- int ret = 0;
- struct group *grpbuf = NULL;
- struct group grp;
- std::vector<char> buf;
-
- /*
- * The maximum needed size for buf can be found using sysconf(3)
- * with the argument _SC_GETGR_R_SIZE_MAX. If _SC_GETGR_R_SIZE_MAX is not
- * returned we set max_buf_size to 1024 bytes. Enough to store few groups.
- */
- long int maxBufSize = sysconf(_SC_GETGR_R_SIZE_MAX);
- if (maxBufSize == -1)
- maxBufSize = 1024;
-
-
- /*
- * There can be some corner cases when for example user is assigned to a
- * lot of groups. In that case if buffer is to small getgrnam_r will
- * return ERANGE error. Solution could be calling getgrnam_r with bigger
- * buffer until it's big enough.
- */
- do {
- try{
- buf.resize(maxBufSize);
- }catch(std::bad_alloc&) {
- ret = SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
- LogError("Out Of Memory");
- return ret;
- }
- maxBufSize *= 2;
- } while ((ret = getgrnam_r(obj.c_str(), &grp, &(buf[0]), buf.size(), &grpbuf)) == ERANGE);
-
- // Check for errors:
- if (ret != 0){
- ret = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- LogError("getgrnam_r failed with error: " << strerror(errno));
- return ret;
-
- } else if (grpbuf == NULL) {
- ret = SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT;
- LogError("Cannot find gid for group: " << obj);
- return ret;
- }
-
- m_gid = grpbuf->gr_gid;
-
- return ret;
-}
-
-
-bool GetGidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
- LogDebug("Iteration begin");
- std::string objectName;
- int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
- if (!buffer.Ready()) {
- return false;
- }
-
- // Get objects name:
- Try {
- Deserialization::Deserialize(buffer, objectName);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- // Get GID
- retCode = setGid(objectName);
-
- // Send the result
- MessageBuffer sendBuffer;
- Serialization::Serialize(sendBuffer, retCode);
- Serialization::Serialize(sendBuffer, m_gid);
- m_serviceManager->Write(conn, sendBuffer.Pop());
- return true;
-}
-
-void GetGidService::process(const ReadEvent &event) {
- LogDebug("Read event for counter: " << event.connectionID.counter);
- auto &buffer = m_messageBufferMap[event.connectionID.counter];
- buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, buffer));
-}
-
-void GetGidService::close(const CloseEvent &event) {
- LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file get-gid.h
- * @author Jan Olszak (j.olszak@samsung.com)
- * @version 1.0
- * @brief Implementation of api-get-gid
- */
-
-#ifndef _SECURITY_SERVER_GET_GID_
-#define _SECURITY_SERVER_GET_GID_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class GetGidService :
- public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<GetGidService>
-{
-public:
- typedef std::map<int, MessageBuffer> MessageBufferMap;
-
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-private:
- gid_t m_gid;
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
- int setGid(std::string& objectName);
- MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_GET_GID_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-exception.h
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Definition of PasswordException class.
- */
-
-#ifndef _PASSWORD_EXCEPTION_H_
-#define _PASSWORD_EXCEPTION_H_
-
-#include <dpl/exception.h>
-
-namespace SecurityServer
-{
- class PasswordException
- {
- public:
- DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, OutOfData)
- DECLARE_EXCEPTION_TYPE(Base, NoData)
- DECLARE_EXCEPTION_TYPE(Base, FStreamOpenError)
- DECLARE_EXCEPTION_TYPE(Base, FStreamWriteError)
- DECLARE_EXCEPTION_TYPE(Base, FStreamReadError)
- DECLARE_EXCEPTION_TYPE(Base, NoPasswords)
- DECLARE_EXCEPTION_TYPE(Base, PasswordNotActive)
- DECLARE_EXCEPTION_TYPE(Base, MakeDirError)
- DECLARE_EXCEPTION_TYPE(Base, TimerError)
- };
-} //namespace SecurityServer
-
-#endif //_PASSWORD_EXCEPTION_H_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-file-buffer.h
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of PasswordFileBuffer, used for serialization in PasswordFile class
- */
-
-#include <password-file-buffer.h>
-
-#include <fstream>
-#include <iterator>
-
-#include <dpl/log/log.h>
-#include <dpl/fstream_accessors.h>
-
-#include <security-server.h>
-#include <password-exception.h>
-
-#include <fcntl.h>
-#include <string.h>
-#include <unistd.h>
-
-namespace SecurityServer
-{
- PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
-
- void PasswordFileBuffer::Read(size_t num, void *bytes)
- {
- if(m_buffer.empty()) {
- LogError("Buffer doesn't contain any data.");
- Throw(PasswordException::NoData);
- }
-
- if((m_bufferReadBytes + num) > m_buffer.size()) {
- LogError("Not enough buffer to read " << num << " data.");
- Throw(PasswordException::OutOfData);
- }
-
- memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
-
- m_bufferReadBytes += num;
- }
-
- void PasswordFileBuffer::Write(size_t num, const void *bytes)
- {
- const char* buffer = static_cast<const char*>(bytes);
- std::copy(buffer, buffer+num, std::back_inserter(m_buffer));
- }
-
- void PasswordFileBuffer::Save(const std::string &path)
- {
- std::ofstream file(path, std::ofstream::trunc);
-
- if(!file.good()) {
- LogError("Error while opening file stream.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- file.write(m_buffer.data(), m_buffer.size());
- if(!file) {
- LogError("Failed to write data.");
- Throw(PasswordException::FStreamWriteError);
- }
-
- file.flush();
- fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(file)); // flush kernel space buffer
- file.close();
- }
-
- void PasswordFileBuffer::Load(const std::string &path)
- {
- std::ifstream file(path, std::ifstream::binary);
-
- if(!file.good()) {
- LogError("Error while opening file stream.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- //reset read bytes counter
- m_bufferReadBytes = 0;
-
- m_buffer.assign(std::istreambuf_iterator<char>(file),
- std::istreambuf_iterator<char>());
-
- if(!file) {
- LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
- Throw(PasswordException::FStreamReadError);
- }
- }
-
-} //namespace SecurityServer
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-file-buffer.h
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of password file buffer, used for serialization in password-manager.h
- */
-
-#ifndef _PASSWORD_FILE_BUFFER_H_
-#define _PASSWORD_FILE_BUFFER_H_
-
-#include <stddef.h>
-#include <vector>
-#include <string>
-
-#include <dpl/serialization.h>
-
-namespace SecurityServer
-{
- class PasswordFileBuffer: public IStream
- {
- public:
- PasswordFileBuffer();
-
- virtual void Read(size_t num, void *bytes);
- virtual void Write(size_t num, const void *bytes);
-
- void Save(const std::string &path);
- void Load(const std::string &path);
-
- private:
- typedef std::vector<char> DataBuffer;
-
- DataBuffer m_buffer;
- size_t m_bufferReadBytes;
- };
-} //namespace SecurityServer
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-file.cpp
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of PasswordFile, used to manage password files.
- */
-#include <password-file.h>
-
-#include <fstream>
-#include <algorithm>
-#include <limits>
-
-#include <fcntl.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <openssl/sha.h>
-
-#include <dpl/log/log.h>
-#include <dpl/fstream_accessors.h>
-
-#include <security-server.h>
-#include <protocols.h>
-#include <password-exception.h>
-#include <password-file-buffer.h>
-
-namespace {
- const std::string DATA_DIR = "/opt/data/security-server";
- const std::string PASSWORD_FILE = DATA_DIR + "/password";
- const std::string OLD_VERSION_PASSWORD_FILE = DATA_DIR + "/password.pwd";
- const std::string ATTEMPT_FILE = DATA_DIR + "/attempt";
- const double RETRY_TIMEOUT = 0.5;
- const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
- const unsigned int CURRENT_FILE_VERSION = 3;
-} // namespace anonymous
-
-namespace SecurityServer
-{
- const time_t PASSWORD_INFINITE_EXPIRATION_TIME = std::numeric_limits<time_t>::max();
-
- class NoPassword: public IPassword
- {
- public:
- NoPassword(IStream&) {}
- NoPassword() {}
-
- void Serialize(IStream &stream) const
- {
- Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::NONE));
- }
-
- bool match(const std::string &) const
- {
- return false;
- }
- };
-
- class SHA256Password: public IPassword
- {
- public:
- SHA256Password(IStream& stream)
- {
- Deserialization::Deserialize(stream, m_hash);
- }
-
- SHA256Password(const std::string &password)
- : m_hash(hash(password)) {}
-
- SHA256Password(const RawHash& hash)
- : m_hash(hash) {}
-
- void Serialize(IStream &stream) const
- {
- Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::SHA256));
- Serialization::Serialize(stream, m_hash);
- }
-
- bool match(const std::string &password) const
- {
- return m_hash == hash(password);
- }
- private:
- RawHash m_hash;
-
- static RawHash hash(const std::string &password)
- {
- RawHash result(SHA256_DIGEST_LENGTH);
-
- SHA256_CTX context;
- SHA256_Init(&context);
- SHA256_Update(&context, reinterpret_cast<const unsigned char*>(password.c_str()),
- password.size());
- SHA256_Final(result.data(), &context);
-
- return result;
- }
- };
-
- // deserialization of new password format
- template <>
- void Deserialization::Deserialize(IStream& stream, IPasswordPtr& ptr)
- {
- unsigned int algorithm;
- Deserialization::Deserialize(stream, algorithm);
- switch (algorithm) {
- case (unsigned int)IPassword::PasswordType::NONE:
- ptr.reset(new NoPassword());
- break;
- case (unsigned int)IPassword::PasswordType::SHA256:
- ptr.reset(new SHA256Password(stream));
- break;
- default:
- Throw(PasswordException::FStreamReadError);
- }
- }
-
- PasswordFile::PasswordFile(): m_passwordCurrent(new NoPassword()),
- m_maxAttempt(PASSWORD_INFINITE_ATTEMPT_COUNT),
- m_maxHistorySize(0),
- m_expireTime(PASSWORD_INFINITE_EXPIRATION_TIME),
- m_passwordActive(false), m_attempt(0)
- {
- // check if data directory exists
- // if not create it
- if (!dirExists(DATA_DIR.c_str())) {
- if(mkdir(DATA_DIR.c_str(), 0700)) {
- LogError("Failed to create directory for files. Error: " << strerror(errno));
- Throw(PasswordException::MakeDirError);
- }
- }
-
- preparePwdFile();
- prepareAttemptFile();
- resetTimer();
- }
-
- void PasswordFile::resetState()
- {
- m_passwordCurrent.reset(new NoPassword());
- m_maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
- m_maxHistorySize = 0;
- m_expireTime = PASSWORD_INFINITE_EXPIRATION_TIME;
- m_passwordActive = false;
- }
-
- void PasswordFile::resetTimer()
- {
- m_retryTimerStart = ClockType::now();
- m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
- }
-
- void PasswordFile::preparePwdFile()
- {
- // check if password file exists
- if (!fileExists(PASSWORD_FILE)) {
- // if old format file exist - load it
- if (tryLoadMemoryFromOldFormatFile()) {
- // save in new format
- writeMemoryToFile();
- // and remove old file
- remove(OLD_VERSION_PASSWORD_FILE.c_str());
- return;
- }
-
- LogSecureDebug("PWD_DBG not found password file. Creating.");
-
- //create file
- writeMemoryToFile();
- } else { //if file exists, load data
- LogSecureDebug("PWD_DBG found password file. Opening.");
- try {
- loadMemoryFromFile();
- } catch (...) {
- LogError("Invalid " << PASSWORD_FILE << " file format");
- resetState();
- writeMemoryToFile();
- }
- }
- }
-
- void PasswordFile::prepareAttemptFile()
- {
- // check if attempt file exists
- // if not create it
- if (!fileExists(ATTEMPT_FILE)) {
- LogSecureDebug("PWD_DBG not found attempt file. Creating.");
-
- writeAttemptToFile();
- } else {
- LogSecureDebug("PWD_DBG found attempt file. Opening.");
- std::ifstream attemptFile(ATTEMPT_FILE);
- if(!attemptFile) {
- LogError("Failed to open attempt file.");
- // ignore error
- return;
- }
-
- attemptFile.read(reinterpret_cast<char*>(&m_attempt), sizeof(unsigned int));
- if(!attemptFile) {
- LogError("Failed to read attempt count.");
- // ignore error
- resetAttempt();
- }
- }
- }
-
- bool PasswordFile::fileExists(const std::string &filename) const
- {
- struct stat buf;
-
- return ((stat(filename.c_str(), &buf) == 0));
- }
-
- bool PasswordFile::dirExists(const std::string &dirpath) const
- {
- struct stat buf;
-
- return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
- }
-
- void PasswordFile::writeMemoryToFile() const
- {
- PasswordFileBuffer pwdBuffer;
-
- LogSecureDebug("Saving max_att: " << m_maxAttempt << ", history_size: " <<
- m_maxHistorySize << ", m_expireTime: " << m_expireTime << ", isActive: " <<
- m_passwordActive);
-
- //serialize password attributes
- Serialization::Serialize(pwdBuffer, CURRENT_FILE_VERSION);
- Serialization::Serialize(pwdBuffer, m_maxAttempt);
- Serialization::Serialize(pwdBuffer, m_maxHistorySize);
- Serialization::Serialize(pwdBuffer, m_expireTime);
- Serialization::Serialize(pwdBuffer, m_passwordActive);
- Serialization::Serialize(pwdBuffer, m_passwordCurrent);
- Serialization::Serialize(pwdBuffer, m_passwordHistory);
-
- pwdBuffer.Save(PASSWORD_FILE);
-
- chmod(PASSWORD_FILE.c_str(), FILE_MODE);
- }
-
- void PasswordFile::loadMemoryFromFile()
- {
- PasswordFileBuffer pwdFile;
-
- pwdFile.Load(PASSWORD_FILE);
-
- unsigned int fileVersion = 0;
- Deserialization::Deserialize(pwdFile, fileVersion);
- if (fileVersion != CURRENT_FILE_VERSION)
- Throw(PasswordException::FStreamReadError);
-
- m_passwordHistory.clear();
-
- Deserialization::Deserialize(pwdFile, m_maxAttempt);
- Deserialization::Deserialize(pwdFile, m_maxHistorySize);
- Deserialization::Deserialize(pwdFile, m_expireTime);
- Deserialization::Deserialize(pwdFile, m_passwordActive);
- Deserialization::Deserialize(pwdFile, m_passwordCurrent);
- Deserialization::Deserialize(pwdFile, m_passwordHistory);
-
- LogSecureDebug("Loaded max_att: " << m_maxAttempt << ", history_size: " <<
- m_maxHistorySize << ", m_expireTime: " << m_expireTime << ", isActive: " <<
- m_passwordActive);
- }
-
- bool PasswordFile::tryLoadMemoryFromOldFormatFile()
- {
- struct stat oldFileStat;
- if (stat(OLD_VERSION_PASSWORD_FILE.c_str(), &oldFileStat) != 0)
- return false;
-
- static const int ELEMENT_SIZE = sizeof(unsigned) + SHA256_DIGEST_LENGTH;
- static const int VERSION_1_REMAINING = sizeof(unsigned) * 4;
- static const int VERSION_2_REMAINING = VERSION_1_REMAINING + sizeof(bool);
- int remaining = oldFileStat.st_size % ELEMENT_SIZE;
-
- if (remaining != VERSION_1_REMAINING && remaining != VERSION_2_REMAINING)
- return false;
-
- try {
- PasswordFileBuffer pwdFile;
- pwdFile.Load(OLD_VERSION_PASSWORD_FILE);
-
- Deserialization::Deserialize(pwdFile, m_maxAttempt);
- Deserialization::Deserialize(pwdFile, m_maxHistorySize);
- Deserialization::Deserialize(pwdFile, m_expireTime);
- if (m_expireTime == 0)
- m_expireTime = PASSWORD_INFINITE_EXPIRATION_TIME;
- if (remaining == VERSION_2_REMAINING)
- Deserialization::Deserialize(pwdFile, m_passwordActive);
- else
- m_passwordActive = true;
-
- // deserialize passwords in old format
- struct OldPassword {
- OldPassword() {}
- OldPassword(IStream &stream)
- {
- Deserialization::Deserialize(stream, m_hash);
- }
- IPassword::RawHash m_hash;
- };
- std::list<OldPassword> oldFormatPasswords;
- Deserialization::Deserialize(pwdFile, oldFormatPasswords);
-
- // convert passwords to new format
- m_passwordHistory.clear();
- if (oldFormatPasswords.empty()) {
- m_passwordCurrent.reset(new NoPassword());
- m_passwordActive = false;
- } else {
- m_passwordCurrent.reset(new SHA256Password(oldFormatPasswords.front().m_hash));
- std::for_each(++oldFormatPasswords.begin(), oldFormatPasswords.end(),
- [&] (const OldPassword& pwd)
- {m_passwordHistory.push_back(IPasswordPtr(new SHA256Password(pwd.m_hash)));}
- );
- }
- } catch (...) {
- LogWarning("Invalid " << OLD_VERSION_PASSWORD_FILE << " file format");
- resetState();
- return false;
- }
-
- return true;
- }
-
- void PasswordFile::writeAttemptToFile() const
- {
- std::ofstream attemptFile(ATTEMPT_FILE, std::ofstream::trunc);
-
- if(!attemptFile.good()) {
- LogError("Failed to open attempt file.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- attemptFile.write(reinterpret_cast<const char*>(&m_attempt), sizeof(unsigned int));
- if(!attemptFile) {
- LogError("Failed to write attempt count.");
- Throw(PasswordException::FStreamWriteError);
- }
-
- attemptFile.flush();
- fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(attemptFile)); // flush kernel space buffer
- attemptFile.close();
- }
-
- void PasswordFile::activatePassword()
- {
- m_passwordActive = true;
- }
-
- bool PasswordFile::isPasswordActive() const
- {
- return m_passwordActive;
- }
-
- void PasswordFile::setMaxHistorySize(unsigned int history)
- {
- //setting history should be independent from password being set
- m_maxHistorySize = history;
-
- while(m_passwordHistory.size() > history)
- m_passwordHistory.pop_back();
- }
-
- unsigned int PasswordFile::getMaxHistorySize() const
- {
- return m_maxHistorySize;
- }
-
- unsigned int PasswordFile::getAttempt() const
- {
- return m_attempt;
- }
-
- void PasswordFile::resetAttempt()
- {
- m_attempt = 0;
- }
-
- void PasswordFile::incrementAttempt()
- {
- m_attempt++;
- }
-
- int PasswordFile::getMaxAttempt() const
- {
- return m_maxAttempt;
- }
-
- void PasswordFile::setMaxAttempt(unsigned int maxAttempt)
- {
- m_maxAttempt = maxAttempt;
- }
-
- bool PasswordFile::isPasswordReused(const std::string &password) const
- {
- LogSecureDebug("Checking if pwd is reused. HistorySize: " << m_passwordHistory.size() <<
- ", MaxHistorySize: " << getMaxHistorySize());
-
- //go through history and check if password existed earlier
- if(std::any_of(m_passwordHistory.begin(), m_passwordHistory.end(),
- [&password](const IPasswordPtr& pwd) { return pwd->match(password); })) {
- LogSecureDebug("Passwords match!");
- return true;
- }
-
- LogSecureDebug("isPasswordReused: No passwords match, password not reused.");
- return false;
- }
-
- void PasswordFile::setPassword(const std::string &password)
- {
- //put current password to history
- m_passwordHistory.push_front(std::move(m_passwordCurrent));
-
- //erase last password if we exceed max history size
- if(m_passwordHistory.size() > getMaxHistorySize())
- m_passwordHistory.pop_back();
-
- //replace current password with new one
- m_passwordCurrent.reset(new SHA256Password(password));
- }
-
- bool PasswordFile::checkPassword(const std::string &password) const
- {
- return m_passwordCurrent->match(password);
- }
-
- void PasswordFile::setExpireTime(time_t expireTime)
- {
- if(isPasswordActive())
- m_expireTime = expireTime;
- else {
- LogError("Can't set expiration time, password not active.");
- Throw(PasswordException::PasswordNotActive);
- }
- }
-
- unsigned int PasswordFile::getExpireTimeLeft() const
- {
- if(m_expireTime != PASSWORD_INFINITE_EXPIRATION_TIME) {
- time_t timeLeft = m_expireTime - time(NULL);
- return (timeLeft < 0) ? 0 : static_cast<unsigned int>(timeLeft);
- } else
- return PASSWORD_API_NO_EXPIRATION;
- }
-
- bool PasswordFile::checkExpiration() const
- {
- //return true if expired, else false
- return ((m_expireTime != PASSWORD_INFINITE_EXPIRATION_TIME) && (time(NULL) > m_expireTime));
- }
-
- bool PasswordFile::checkIfAttemptsExceeded() const
- {
- return ((m_maxAttempt != PASSWORD_INFINITE_ATTEMPT_COUNT) && (m_attempt > m_maxAttempt));
- }
-
- bool PasswordFile::isIgnorePeriod() const
- {
- TimePoint retryTimerStop = ClockType::now();
- TimeDiff diff = retryTimerStop - m_retryTimerStart;
-
- m_retryTimerStart = retryTimerStop;
-
- return (diff.count() < RETRY_TIMEOUT);
- }
-
- bool PasswordFile::isHistoryActive() const
- {
- return (m_maxHistorySize != 0);
- }
-} //namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-file.h
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of PasswordFile, used to manage password files.
- */
-#ifndef _PASSWORD_FILE_H_
-#define _PASSWORD_FILE_H_
-
-#include <string>
-#include <vector>
-#include <list>
-#include <chrono>
-#include <memory>
-
-#include <time.h>
-
-#include <dpl/serialization.h>
-
-namespace SecurityServer
-{
- extern const time_t PASSWORD_INFINITE_EXPIRATION_TIME;
-
- struct IPassword: public ISerializable
- {
- typedef std::vector<unsigned char> RawHash;
-
- enum class PasswordType : unsigned int
- {
- NONE = 0,
- SHA256 = 1,
- };
-
- virtual bool match(const std::string &password) const = 0;
- };
-
- typedef std::unique_ptr<IPassword> IPasswordPtr;
- typedef std::list<IPasswordPtr> PasswordList;
-
- class PasswordFile
- {
- public:
- PasswordFile();
-
- void writeMemoryToFile() const;
- void writeAttemptToFile() const;
-
- void setPassword(const std::string &password);
- bool checkPassword(const std::string &password) const;
-
- void activatePassword();
- bool isPasswordActive() const;
-
- void setMaxHistorySize(unsigned int history);
- unsigned int getMaxHistorySize() const;
-
- unsigned int getExpireTimeLeft() const;
- void setExpireTime(time_t expireTime);
-
- //attempt manipulating functions
- unsigned int getAttempt() const;
- void resetAttempt();
- void incrementAttempt();
- int getMaxAttempt() const;
- void setMaxAttempt(unsigned int maxAttempt);
-
- bool isPasswordReused(const std::string &password) const;
-
- bool checkExpiration() const;
- bool checkIfAttemptsExceeded() const;
- bool isIgnorePeriod() const;
-
- bool isHistoryActive() const;
-
- private:
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7))
- typedef std::chrono::steady_clock ClockType;
-#else
- typedef std::chrono::monotonic_clock ClockType;
-#endif
- typedef std::chrono::duration<double> TimeDiff;
- typedef std::chrono::time_point<ClockType, TimeDiff> TimePoint;
-
- void loadMemoryFromFile();
- bool tryLoadMemoryFromOldFormatFile();
-
- void resetTimer();
- void preparePwdFile();
- void prepareAttemptFile();
- void resetState();
- bool fileExists(const std::string &filename) const;
- bool dirExists(const std::string &dirpath) const;
-
- mutable TimePoint m_retryTimerStart;
-
- //password file data
- IPasswordPtr m_passwordCurrent;
- PasswordList m_passwordHistory;
- unsigned int m_maxAttempt;
- unsigned int m_maxHistorySize;
- time_t m_expireTime;
- bool m_passwordActive;
-
- //attempt file data
- unsigned int m_attempt;
- };
-} //namespace SecurityServer
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-manager.cpp
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of password management functions
- */
-
-#include <password-manager.h>
-
-#include <iostream>
-#include <iterator>
-#include <algorithm>
-
-#include <limits.h>
-
-#include <dpl/log/log.h>
-
-#include <protocols.h>
-
-#include <security-server.h>
-
-namespace {
- bool calculateExpiredTime(unsigned int receivedDays, time_t &validSecs)
- {
- validSecs = SecurityServer::PASSWORD_INFINITE_EXPIRATION_TIME;
-
- //when receivedDays means infinite expiration, return default validSecs value.
- if(receivedDays == SecurityServer::PASSWORD_INFINITE_EXPIRATION_DAYS)
- return true;
-
- time_t curTime = time(NULL);
-
- if (receivedDays > ((UINT_MAX - curTime) / 86400)) {
- LogError("Incorrect input param.");
- return false;
- } else {
- validSecs = (curTime + (receivedDays * 86400));
- return true;
- }
- }
-} //namespace
-
-namespace SecurityServer
-{
- int PasswordManager::isPwdValid(unsigned int ¤tAttempt, unsigned int &maxAttempt,
- unsigned int &expirationTime) const
- {
- if (!m_pwdFile.isPasswordActive()) {
- LogError("Current password not active.");
- return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
- } else {
- currentAttempt = m_pwdFile.getAttempt();
- maxAttempt = m_pwdFile.getMaxAttempt();
- expirationTime = m_pwdFile.getExpireTimeLeft();
-
- return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
- }
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::checkPassword(const std::string &challenge, unsigned int ¤tAttempt,
- unsigned int &maxAttempt, unsigned int &expirationTime)
- {
- LogSecureDebug("Inside checkPassword function.");
-
- if (m_pwdFile.isIgnorePeriod()) {
- LogError("Retry timeout occurred.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
- }
-
- if (!m_pwdFile.isPasswordActive()) {
- LogError("Password not active.");
- return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
- }
-
- m_pwdFile.incrementAttempt();
- m_pwdFile.writeAttemptToFile();
-
- currentAttempt = m_pwdFile.getAttempt();
- maxAttempt = m_pwdFile.getMaxAttempt();
- expirationTime = m_pwdFile.getExpireTimeLeft();
-
- if (m_pwdFile.checkIfAttemptsExceeded()) {
- LogError("Too many tries.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
- }
-
- if (!m_pwdFile.checkPassword(challenge)) {
- LogError("Wrong password.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
- }
-
- if (m_pwdFile.checkExpiration()) {
- LogError("Password expired.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
- }
-
- m_pwdFile.resetAttempt();
- m_pwdFile.writeAttemptToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::setPassword(const std::string ¤tPassword,
- const std::string &newPassword,
- const unsigned int receivedAttempts,
- const unsigned int receivedDays)
- {
- LogSecureDebug("Curpwd = " << currentPassword << ", newpwd = " << newPassword <<
- ", recatt = " << receivedAttempts << ", recdays = " << receivedDays);
-
- time_t valid_secs = 0;
-
- if (m_pwdFile.isIgnorePeriod()) {
- LogError("Retry timeout occured.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
- }
-
- //check if passwords are correct
- if (currentPassword.size() > MAX_PASSWORD_LEN) {
- LogError("Current password length failed.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- if (newPassword.size() > MAX_PASSWORD_LEN) {
- LogError("New password length failed.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- //check delivered currentPassword
- //when m_passwordActive flag is true, currentPassword shouldn't be empty
- if (currentPassword.empty() && m_pwdFile.isPasswordActive()) {
- LogError("Password is already set. Max history: " << m_pwdFile.getMaxHistorySize());
- return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
- }
-
- //increment attempt count before checking it against max attempt count
- m_pwdFile.incrementAttempt();
- m_pwdFile.writeAttemptToFile();
-
- // check attempt
- if (m_pwdFile.checkIfAttemptsExceeded()) {
- LogError("Too many attempts.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
- }
-
- //check current password, however only when we don't send empty string as current.
- if(!currentPassword.empty()) {
- if(!m_pwdFile.checkPassword(currentPassword)) {
- LogError("Wrong password.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
- }
- }
-
- //check if password expired
- if (m_pwdFile.checkExpiration()) {
- LogError("Password expired.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
- }
-
- //check history, however only if history is active
- if (m_pwdFile.isPasswordActive() && m_pwdFile.isHistoryActive()) {
- if (m_pwdFile.isPasswordReused(newPassword)) {
- LogError("Password reused.");
- return SECURITY_SERVER_API_ERROR_PASSWORD_REUSED;
- }
- }
-
- if(!calculateExpiredTime(receivedDays, valid_secs)) {
- LogError("Received expiration time incorrect.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- //setting password
- m_pwdFile.setPassword(newPassword);
- m_pwdFile.activatePassword();
- m_pwdFile.setMaxAttempt(receivedAttempts);
- m_pwdFile.setExpireTime(valid_secs);
- m_pwdFile.writeMemoryToFile();
-
- m_pwdFile.resetAttempt();
- m_pwdFile.writeAttemptToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::setPasswordValidity(const unsigned int receivedDays)
- {
- time_t valid_secs = 0;
-
- LogSecureDebug("received_days: " << receivedDays);
-
- if (!m_pwdFile.isPasswordActive()) {
- LogError("Current password is not active.");
- return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
- }
-
- if(!calculateExpiredTime(receivedDays, valid_secs))
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- m_pwdFile.setExpireTime(valid_secs);
- m_pwdFile.writeMemoryToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::resetPassword(const std::string &newPassword,
- const unsigned int receivedAttempts,
- const unsigned int receivedDays)
- {
- time_t valid_secs = 0;
-
- if(!calculateExpiredTime(receivedDays, valid_secs))
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
- m_pwdFile.setPassword(newPassword);
- m_pwdFile.activatePassword();
- m_pwdFile.setMaxAttempt(receivedAttempts);
- m_pwdFile.setExpireTime(valid_secs);
- m_pwdFile.writeMemoryToFile();
-
- m_pwdFile.resetAttempt();
- m_pwdFile.writeAttemptToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::setPasswordHistory(const unsigned int history)
- {
- if(history > MAX_PASSWORD_HISTORY) {
- LogError("Incorrect input param.");
- return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
- }
-
- m_pwdFile.setMaxHistorySize(history);
- m_pwdFile.writeMemoryToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-
- int PasswordManager::setPasswordMaxChallenge(const unsigned int maxChallenge)
- {
- // check if there is password
- if (!m_pwdFile.isPasswordActive()) {
- LogError("Password not active.");
- return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
- }
-
- m_pwdFile.setMaxAttempt(maxChallenge);
- m_pwdFile.writeMemoryToFile();
-
- m_pwdFile.resetAttempt();
- m_pwdFile.writeAttemptToFile();
-
- return SECURITY_SERVER_API_SUCCESS;
- }
-} //namespace SecurityServer
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password-manager.h
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of password management functions
- */
-
-#ifndef _PASSWORDMANAGER_H_
-#define _PASSWORDMANAGER_H_
-
-#include <string>
-
-#include <password-file.h>
-
-namespace SecurityServer
-{
- class PasswordManager
- {
- public:
- //checking functions
- int isPwdValid(unsigned int ¤tAttempt, unsigned int &maxAttempt,
- unsigned int &expirationTime) const;
- int checkPassword(const std::string& challenge, unsigned int ¤tAttempt,
- unsigned int &maxAttempt, unsigned int &expTime);
- //no const in checkPassword, attempts are updated
-
- //setting functions
- int setPassword(const std::string ¤tPassword, const std::string &newPassword,
- const unsigned int receivedAttempts, const unsigned int receivedDays);
- int setPasswordValidity(const unsigned int receivedDays);
- int resetPassword(const std::string &newPassword, const unsigned int receivedAttempts,
- const unsigned int receivedDays);
- int setPasswordHistory(const unsigned int history);
- int setPasswordMaxChallenge(const unsigned int maxChallenge);
-
- private:
- PasswordFile m_pwdFile;
- };
-} //namespace SecurityServer
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password.cpp
- * @author Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of password service
- */
-
-#include <iostream>
-#include <string>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <password.h>
-
-#include <security-server.h>
-#include <password-exception.h>
-
-namespace SecurityServer {
-
-namespace {
-// Service may open more than one socket.
-// These ID's will be assigned to sockets
-// and will be used only by service.
-// When new connection arrives, AcceptEvent
-// will be generated with proper ID to inform
-// service about input socket.
-//
-// Please note: SocketManager does not use it and
-// does not check it in any way.
-//
-// If your service requires only one socket
-// (uses only one socket labeled with smack)
-// you may ignore this ID (just pass 0)
-const InterfaceID SOCKET_ID_CHECK = 0;
-const InterfaceID SOCKET_ID_SET = 1;
-const InterfaceID SOCKET_ID_RESET = 2;
-
-} // namespace anonymous
-
-GenericSocketService::ServiceDescriptionVector PasswordService::GetServiceDescription()
-{
- return ServiceDescriptionVector {
- {SERVICE_SOCKET_PASSWD_CHECK, "security-server::api-password-check", SOCKET_ID_CHECK},
- {SERVICE_SOCKET_PASSWD_SET, "security-server::api-password-set", SOCKET_ID_SET},
- {SERVICE_SOCKET_PASSWD_RESET, "security-server::api-password-reset", SOCKET_ID_RESET}
- };
-}
-
-void PasswordService::accept(const AcceptEvent &event)
-{
- LogSecureDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
-
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.interfaceID = event.interfaceID;
-}
-
-void PasswordService::write(const WriteEvent &event)
-{
- LogSecureDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-void PasswordService::process(const ReadEvent &event)
-{
- LogSecureDebug("Read event for counter: " << event.connectionID.counter);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void PasswordService::close(const CloseEvent &event)
-{
- LogSecureDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-int PasswordService::processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
- unsigned int &cur_att, unsigned int &max_att,
- unsigned int &exp_time)
-{
- int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
- switch (hdr) {
- case PasswordHdrs::HDR_IS_PWD_VALID:
- result = m_pwdManager.isPwdValid(cur_att, max_att, exp_time);
- break;
-
- case PasswordHdrs::HDR_CHK_PWD: {
- std::string challenge;
- Deserialization::Deserialize(buffer, challenge);
- result = m_pwdManager.checkPassword(challenge, cur_att, max_att, exp_time);
- break;
- }
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
-
- return result;
-}
-
-int PasswordService::processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
-{
- int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
- std::string curPwd, newPwd;
- unsigned int rec_att = 0, rec_days = 0, rec_max_challenge = 0, rec_history = 0;
-
- switch(hdr) {
- case PasswordHdrs::HDR_SET_PWD:
- Deserialization::Deserialize(buffer, curPwd);
- Deserialization::Deserialize(buffer, newPwd);
- Deserialization::Deserialize(buffer, rec_att);
- Deserialization::Deserialize(buffer, rec_days);
- result = m_pwdManager.setPassword(curPwd, newPwd, rec_att, rec_days);
- break;
-
- case PasswordHdrs::HDR_SET_PWD_VALIDITY:
- Deserialization::Deserialize(buffer, rec_days);
- result = m_pwdManager.setPasswordValidity(rec_days);
- break;
-
- case PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE:
- Deserialization::Deserialize(buffer, rec_max_challenge);
- result = m_pwdManager.setPasswordMaxChallenge(rec_max_challenge);
- break;
-
- case PasswordHdrs::HDR_SET_PWD_HISTORY:
- Deserialization::Deserialize(buffer, rec_history);
- result = m_pwdManager.setPasswordHistory(rec_history);
- break;
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
-
- return result;
-}
-
-int PasswordService::processResetFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
-{
- int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
- std::string newPwd;
- unsigned int rec_att = 0, rec_days = 0;
-
- switch(hdr) {
- case PasswordHdrs::HDR_RST_PWD:
- Deserialization::Deserialize(buffer, newPwd);
- Deserialization::Deserialize(buffer, rec_att);
- Deserialization::Deserialize(buffer, rec_days);
- result = m_pwdManager.resetPassword(newPwd, rec_att, rec_days);
- break;
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
-
- return result;
-}
-
-bool PasswordService::processOne(const ConnectionID &conn, MessageBuffer &buffer,
- InterfaceID interfaceID)
-{
- LogSecureDebug("Iteration begin");
-
- MessageBuffer sendBuffer;
-
- int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- unsigned int cur_att = 0, max_att = 0, exp_time = 0;
-
- if (!buffer.Ready())
- return false;
-
- Try { //try..catch for MessageBuffer errors, closes connection when exception is thrown
- int tempHdr;
- Deserialization::Deserialize(buffer, tempHdr);
- PasswordHdrs hdr = static_cast<PasswordHdrs>(tempHdr);
-
- try { //try..catch for internal service errors, assigns error code for returning.
- switch (interfaceID) {
- case SOCKET_ID_CHECK:
- retCode = processCheckFunctions(hdr, buffer, cur_att, max_att, exp_time);
- break;
-
- case SOCKET_ID_SET:
- retCode = processSetFunctions(hdr, buffer);
- break;
-
- case SOCKET_ID_RESET:
- retCode = processResetFunctions(hdr, buffer);
- break;
-
- default:
- LogError("Wrong interfaceID.");
- Throw(Exception::IncorrectHeader);
- }
- } catch (PasswordException::Base &e) {
- LogError("Password error: " << e.DumpToString());
- retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- } catch (std::exception &e) {
- LogError("STD error: " << e.what());
- retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
- }
-
- //everything is OK, send return code and extra data
- Serialization::Serialize(sendBuffer, retCode);
-
- //Returning additional information should occur only when checking functions
- //are called, and under certain return values
- if(interfaceID == SOCKET_ID_CHECK)
- {
- switch(retCode)
- {
- case SECURITY_SERVER_API_ERROR_PASSWORD_EXIST:
- case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
- case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
- case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
- Serialization::Serialize(sendBuffer, cur_att);
- Serialization::Serialize(sendBuffer, max_att);
- Serialization::Serialize(sendBuffer, exp_time);
- break;
-
- case SECURITY_SERVER_API_SUCCESS:
- if(hdr == PasswordHdrs::HDR_CHK_PWD) {
- Serialization::Serialize(sendBuffer, cur_att);
- Serialization::Serialize(sendBuffer, max_att);
- Serialization::Serialize(sendBuffer, exp_time);
- }
- break;
-
- default:
- break;
- }
- }
-
- m_serviceManager->Write(conn, sendBuffer.Pop());
- } Catch (MessageBuffer::Exception::Base) {
- LogError("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- } Catch (PasswordService::Exception::Base) {
- LogError("Incorrect message header. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
-
-
- return true;
-}
-
-} // namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file password.h
- * @author Zigniew Jasinski (z.jasinski@samsung.com)
- * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version 1.0
- * @brief Implementation of password service
- */
-
-#ifndef _SECURITY_SERVER_PASSWORD_
-#define _SECURITY_SERVER_PASSWORD_
-
-#include <map>
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-#include <protocols.h>
-
-#include <password-manager.h>
-
-namespace SecurityServer
-{
- class PasswordService
- : public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<PasswordService>
- {
- public:
- class Exception
- {
- public:
- DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, IncorrectHeader)
- };
-
- //service functions
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-
- private:
- //internal service functions
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
- int processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer, unsigned int &cur_att,
- unsigned int &max_att, unsigned int &exp_time);
- int processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
- int processResetFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
-
- // service attributes
- PasswordManager m_pwdManager;
- ConnectionInfoMap m_connectionInfoMap;
- };
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_PASSWORD_
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*
- * @file privilege-by-pid.cpp
- * @author Jan Cybulski (j.cybulski@samsung.com)
- * @version 1.0
- * @brief Implementation of check-privilege-by-pid service.
- */
-
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <privilege-by-pid.h>
-
-#include <security-server.h>
-#include <security-server-util.h>
-#include <smack-check.h>
-
-#include <privilege-control.h>
-#include <smack-common.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector PrivilegeByPidService::GetServiceDescription() {
- return ServiceDescriptionVector
- {{SERVICE_SOCKET_PRIVILEGE_BY_PID, "security-server::api-privilege-by-pid" }};
-}
-
-void PrivilegeByPidService::accept(const AcceptEvent &event) {
- LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
-}
-
-void PrivilegeByPidService::write(const WriteEvent &event) {
- LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
-}
-
-bool PrivilegeByPidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
- LogDebug("Iteration begin");
-
- int retval;
- int pid;
- std::string object;
- std::string access_rights;
- char subject[SMACK_LABEL_LEN + 1] = {0};
-
- int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-
- if (!buffer.Ready()) {
- return false;
- }
-
- Try {
- Deserialization::Deserialize(buffer, pid);
- Deserialization::Deserialize(buffer, object);
- Deserialization::Deserialize(buffer, access_rights);
- } Catch (MessageBuffer::Exception::Base) {
- LogDebug("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- if (smack_check()) {
- retval = smack_pid_have_access(pid, object.c_str(), access_rights.c_str());
- LogDebug("smack_pid_have_access returned " << retval);
-
- if (-1 != get_smack_label_from_process(pid, subject)) {
- // subject label is set to empty string
- LogError("get_smack_label_from_process failed. Subject label has not been read.");
- } else {
- LogSecureDebug("Subject label of client PID " << pid << " is: " << subject);
- }
- } else {
- LogDebug("SMACK is not available. Subject label has not been read.");
- retval = 1;
- }
-
- if (retval == 1) //there is permission
- retCode = SECURITY_SERVER_API_SUCCESS;
- else //there is no permission
- retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-
- MessageBuffer sendBuffer;
- Serialization::Serialize(sendBuffer, retCode);
- m_serviceManager->Write(conn, sendBuffer.Pop());
-
- if (retval != 1) {
- char *path = read_exe_path_from_proc(pid);
-
- LogSmackAudit("SS_SMACK: "
- << "caller_pid=" << pid
- << ", subject=" << subject
- << ", object=" << object
- << ", access=" << access_rights
- << ", result=" << retval
- << ", caller_path=" << (path ? path : "" ));
-
- free(path);
- }
-
- return true;
-}
-
-void PrivilegeByPidService::process(const ReadEvent &event) {
- LogDebug("Read event for counter: " << event.connectionID.counter);
- auto &buffer = m_messageBufferMap[event.connectionID.counter];
- buffer.Push(event.rawBuffer);
-
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, buffer));
-}
-
-void PrivilegeByPidService::close(const CloseEvent &event) {
- LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
+++ /dev/null
-/*
- * Copyright (c) 2000 - 2013 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
- */
-/*hcpp
- * @author Jan Cybulski (j.cybulski@samsung.com)
- * @version 1.0
- * @brief Implementation of api-check-privilege-by-pid
- */
-
-#ifndef _SECURITY_SERVER_PRIVILEGE_BY_PID_
-#define _SECURITY_SERVER_PRIVILEGE_BY_PID_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class PrivilegeByPidService
- : public SecurityServer::GenericSocketService
- , public SecurityServer::ServiceThread<PrivilegeByPidService>
-{
-public:
- typedef std::map<int, MessageBuffer> MessageBufferMap;
-
- ServiceDescriptionVector GetServiceDescription();
-
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
-
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
-private:
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-
- MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_DATA_SHARE_
INSTALL(FILES
${CMAKE_SOURCE_DIR}/systemd/security-server.service
${CMAKE_SOURCE_DIR}/systemd/security-server.target
- ${CMAKE_SOURCE_DIR}/systemd/security-server-data-share.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-get-gid.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-privilege-by-pid.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-cookie-get.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-cookie-check.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-app-privilege-by-name.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-password-reset.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-password-check.socket
- ${CMAKE_SOURCE_DIR}/systemd/security-server-password-set.socket
${CMAKE_SOURCE_DIR}/systemd/security-manager-installer.socket
DESTINATION
/usr/lib/systemd/system
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-app-privilege-by-name.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-cookie-check.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-cookie-get.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-data-share.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-get-gid.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-password-check.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-password-reset.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-password-set.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target
+++ /dev/null
-[Socket]
-ListenStream=/run/security-server/security-server-api-privilege-by-pid.socket
-SocketMode=0777
-SmackLabelIPIn=*
-SmackLabelIPOut=@
-
-Service=security-server.service
-
-[Unit]
-Wants=security-server.target
-Before=security-server.target
-
-[Install]
-WantedBy=sockets.target