Use common HAL API and accordingly refactoring password manger for password file 00/322700/6
authorDongik Lee <dongik.lee@samsung.com>
Wed, 26 Mar 2025 06:25:28 +0000 (15:25 +0900)
committerDongik Lee <dongik.lee@samsung.com>
Wed, 16 Apr 2025 05:30:22 +0000 (14:30 +0900)
Change-Id: I2a1e4e12d5fafd26e623597bdae0e7664f92e093

28 files changed:
CMakeLists.txt
packaging/auth-fw.spec
src/common/CMakeLists.txt
src/server/CMakeLists.txt
src/server/plugin/CMakeLists.txt [deleted file]
src/server/plugin/generic-backend/ipassword-file.h [deleted file]
src/server/plugin/generic-backend/ipassword.cpp [deleted file]
src/server/plugin/generic-backend/ipassword.h [deleted file]
src/server/plugin/generic-backend/password-file-buffer.cpp [deleted file]
src/server/plugin/generic-backend/password-file-buffer.h [deleted file]
src/server/plugin/sw-backend/password-file.cpp [deleted file]
src/server/plugin/sw-backend/password-file.h [deleted file]
src/server/plugin/tz-backend/password-file.cpp [deleted file]
src/server/plugin/tz-backend/password-file.h [deleted file]
src/server/service/include/password-manager.h
src/server/service/include/plugin-loader.h [deleted file]
src/server/service/include/plugin-manager.h [deleted file]
src/server/service/include/policy-file-buffer.h [new file with mode: 0644]
src/server/service/password-manager.cpp
src/server/service/password-policy-manager.cpp
src/server/service/password.cpp
src/server/service/plugin-loader.cpp [deleted file]
src/server/service/plugin-manager.cpp [deleted file]
src/server/service/policy-file-buffer.cpp [new file with mode: 0644]
src/server/service/policy-file.cpp
tests/CMakeLists.txt
tests/test-sw-backend.cpp [deleted file]
tests/test-util.cpp

index c7f542711d8493611566fe52258cd804bb8dcfc9..2f21d5fadea3fb83fef2662a48b0078eeb74084f 100644 (file)
@@ -59,8 +59,6 @@ ADD_DEFINITIONS("-DSOCK_PASSWD_CHECK=\"${SOCK_PASSWD_CHECK}\"")
 ADD_DEFINITIONS("-DSOCK_PASSWD_SET=\"${SOCK_PASSWD_SET}\"")
 ADD_DEFINITIONS("-DSOCK_PASSWD_RESET=\"${SOCK_PASSWD_RESET}\"")
 ADD_DEFINITIONS("-DSOCK_PASSWD_POLICY=\"${SOCK_PASSWD_POLICY}\"")
-ADD_DEFINITIONS("-DPLUGIN_SW_BACKEND_PATH=\"${PLUGIN_SW_BACKEND_PATH}\"")
-ADD_DEFINITIONS("-DPLUGIN_TZ_BACKEND_PATH=\"${PLUGIN_TZ_BACKEND_PATH}\"")
 
 IF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
     ADD_DEFINITIONS("-DBUILD_TYPE_DEBUG")
@@ -72,15 +70,12 @@ SET(INCLUDE_PATH ${PROJECT_SOURCE_DIR}/src/include)
 SET(COMMON_PATH  ${PROJECT_SOURCE_DIR}/src/common)
 SET(CLIENT_PATH  ${PROJECT_SOURCE_DIR}/src/client)
 SET(SERVER_PATH  ${PROJECT_SOURCE_DIR}/src/server)
-SET(PLUGIN_PATH  ${PROJECT_SOURCE_DIR}/src/server/plugin)
 SET(DPL_PATH     ${PROJECT_SOURCE_DIR}/src/dpl)
 
 SET(TARGET_SERVER ${SERVICE_NAME})
 SET(TARGET_CLIENT ${SERVICE_NAME}-client)
 SET(TARGET_CLIENT_ADMIN ${SERVICE_NAME}-client-admin)
 SET(TARGET_COMMON ${SERVICE_NAME}-commons)
-SET(TARGET_SW_BACKEND ${SERVICE_NAME}-sw-backend)
-SET(TARGET_TZ_BACKEND ${SERVICE_NAME}-tz-backend)
 SET(TARGET_TEST ${SERVICE_NAME}-test)
 
 ADD_SUBDIRECTORY(src)
index 17e091fa320c7370e3454e9f291a54e1c0bf7228..6af9953c91ff26726620eb99b1c01f6bdd39202d 100644 (file)
@@ -8,8 +8,7 @@ Source0:    %{name}-%{version}.tar.gz
 Source1001: %{name}.manifest
 Source1002: lib%{name}-client.manifest
 Source1003: lib%{name}-client-admin.manifest
-Source1004: lib%{name}-sw-backend.manifest
-Source1005: %{name}-test.manifest
+Source1004: %{name}-test.manifest
 BuildRequires: cmake
 BuildRequires: pkgconfig(dlog)
 BuildRequires: pkgconfig(libsmack)
@@ -19,6 +18,7 @@ BuildRequires: pkgconfig(cynara-client)
 BuildRequires: pkgconfig(cynara-creds-socket)
 BuildRequires: pkgconfig(cynara-session)
 BuildRequires: pkgconfig(security-manager)
+BuildRequires: pkgconfig(hal-api-security)
 Requires: security-config
 Requires: lib%{name}-sw-backend = %{version}-%{release}
 %{?systemd_requires}
@@ -31,9 +31,7 @@ Authentication framework which is consist of client library and server daemon
 %global run_dir %{?TZ_SYS_RUN:%TZ_SYS_RUN}%{!?TZ_SYS_RUN:/var/run}
 %global bin_dir %{?TZ_SYS_BIN:%TZ_SYS_BIN}%{!?TZ_SYS_BIN:%_bindir}
 # image creation error occured if /usr/sbin used for ldconfig
-#%global sbin_dir %{?TZ_SYS_SBIN:%TZ_SYS_SBIN}%{!?TZ_SYS_SBIN:%_sbindir}
 %global sbin_dir /sbin
-%global plugin_dir %{_datadir}/auth-fw
 %global rw_data_dir %{?TZ_SYS_DATA:%TZ_SYS_DATA/%name}%{!?TZ_SYS_DATA:/opt/data/%name}
 %global sock_passwd_check %{name}-passwd-check.socket
 %global sock_passwd_set %{name}-passwd-set.socket
@@ -89,9 +87,6 @@ export CXXFLAGS+=" -Wno-maybe-uninitialized"
         -DBIN_DIR:PATH=%{bin_dir} \
         -DRUN_DIR:PATH=%{run_dir} \
         -DRW_DATA_DIR:PATH=%{rw_data_dir} \
-        -DPLUGIN_DIR:PATH=%{plugin_dir} \
-        -DPLUGIN_SW_BACKEND_PATH=%{plugin_dir}/lib%{name}-sw-backend.so.%{version} \
-        -DPLUGIN_TZ_BACKEND_PATH=%{plugin_dir}/lib%{name}-tz-backend.so.%{version} \
         -DSYSTEMD_UNIT_DIR:PATH=%{_unitdir} \
         -DINCLUDE_DIR:PATH=%{_includedir} \
         -DSOCK_PASSWD_CHECK=%{sock_passwd_check} \
@@ -112,7 +107,7 @@ make %{?jobs:-j%jobs}
 
 mkdir -p %{buildroot}/%{rw_data_dir}
 
-cp -a %{SOURCE1001} %{SOURCE1002} %{SOURCE1003} %{SOURCE1004} %{SOURCE1005} %{buildroot}%{_datadir}/
+cp -a %{SOURCE1001} %{SOURCE1002} %{SOURCE1003} %{SOURCE1004} .
 
 %post
 %{sbin_dir}/ldconfig
@@ -150,7 +145,7 @@ fi
 %postun -n lib%{name}-client-admin -p %{sbin_dir}/ldconfig
 
 %files
-%manifest %{_datadir}/%{name}.manifest
+%manifest %{name}.manifest
 %license LICENSE
 %{bin_dir}/%{name}
 %{_libdir}/lib%{name}-commons.so.*
@@ -167,12 +162,12 @@ fi
 %dir %attr(770, %{user_name}, %{group_name}) %{rw_data_dir}
 
 %files -n lib%{name}-client
-%manifest %{_datadir}/lib%{name}-client.manifest
+%manifest lib%{name}-client.manifest
 %license LICENSE
 %{_libdir}/lib%{name}-client.so.*
 
 %files -n lib%{name}-client-admin
-%manifest %{_datadir}/lib%{name}-client-admin.manifest
+%manifest lib%{name}-client-admin.manifest
 %license LICENSE
 %{_libdir}/lib%{name}-client-admin.so.*
 
@@ -186,24 +181,6 @@ fi
 %{_includedir}/%{name}/auth-passwd-policy-types.h
 %{_libdir}/pkgconfig/*.pc
 
-## SW-Backend(PasswordFile) Package ##########################################
-%package -n lib%{name}-sw-backend
-Summary: Authentication framework (sw-backend)
-Group: Security/Libraries
-BuildRequires: pkgconfig(openssl3)
-Requires: %{name} = %{version}
-Requires(post): %{sbin_dir}/ldconfig
-Requires(postun): %{sbin_dir}/ldconfig
-
-%description -n lib%{name}-sw-backend
-SW-Backend for authentication framework
-
-%files -n lib%{name}-sw-backend
-%manifest %{_datadir}/lib%{name}-sw-backend.manifest
-%license LICENSE
-%{plugin_dir}/lib%{name}-sw-backend.so
-%{plugin_dir}/lib%{name}-sw-backend.so.*
-
 ## Test Package ##############################################################
 %package test
 Summary: Authentication framework (test)
@@ -216,5 +193,5 @@ Requires: %{name} = %{version}
 Testcases for authentication framework
 
 %files test
-%manifest %{_datadir}/%{name}-test.manifest
+%manifest %{name}-test.manifest
 %{bin_dir}/%{name}-test
index 9fb03510c214746d60d2fe5d5c4a1910b39366d3..7413a7768bea169078c0e83f64919af57478aaf8 100644 (file)
@@ -25,7 +25,6 @@ INCLUDE_DIRECTORIES(
     ${COMMON_DEP_INCLUDE_DIRS}
     ${INCLUDE_PATH}
     ${COMMON_PATH}/include
-    ${PLUGIN_PATH}/include
     ${DPL_PATH}/core/include
     ${DPL_PATH}/log/include
     )
index 828a0b428a7de29a3ab818e538ba8f4aa48ebeb8..fb234260823618bfeb6f23f6616b0e252e1f74af 100644 (file)
@@ -1,5 +1,6 @@
 PKG_CHECK_MODULES(SERVER_DEP
     REQUIRED
+    hal-api-security
     libsmack
     libsystemd
     cynara-client
@@ -19,7 +20,10 @@ INCLUDE_DIRECTORIES(
     ${SERVER_PATH}/service/include
     ${DPL_PATH}/core/include
     ${DPL_PATH}/log/include
-    ${PLUGIN_PATH}/
+    )
+
+LINK_DIRECTORIES(
+    ${SERVER_DEP_LIBRARY_DIRS}
     )
 
 SET(SERVER_SOURCES
@@ -31,11 +35,9 @@ SET(SERVER_SOURCES
     service/password-manager.cpp
     service/password-policy-manager.cpp
     service/policy-file.cpp
-    service/plugin-loader.cpp
-    service/plugin-manager.cpp
+    service/policy-file-buffer.cpp
     service/privilege-check.cpp
     service/user-check.cpp
-    plugin/generic-backend/password-file-buffer.cpp
     )
 
 SET_SOURCE_FILES_PROPERTIES(${SERVER_SOURCES}
@@ -64,6 +66,4 @@ INSTALL(TARGETS ${TARGET_SERVER}
         GROUP_EXECUTE
         WORLD_READ
         WORLD_EXECUTE
-    )
-
-ADD_SUBDIRECTORY(plugin)
+    )
\ No newline at end of file
diff --git a/src/server/plugin/CMakeLists.txt b/src/server/plugin/CMakeLists.txt
deleted file mode 100644 (file)
index 2f4d62e..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-### SW-BACKEND ############################################################################
-PKG_CHECK_MODULES(SW_BACKEND_DEP
-    REQUIRED
-    openssl3
-    )
-
-INCLUDE_DIRECTORIES(
-    SYSTEM
-    ${SW_BACKEND_DEP_INCLUDE_DIRS}
-    ${COMMON_PATH}/include
-    ${SERVER_PATH}/service/include
-    ${DPL_PATH}/core/include
-    ${DPL_PATH}/log/include
-    ${PLUGIN_PATH}
-    )
-
-SET(SW_BACKEND_SOURCES
-    generic-backend/ipassword.cpp
-    generic-backend/password-file-buffer.cpp
-    sw-backend/password-file.cpp
-    )
-
-ADD_LIBRARY(${TARGET_SW_BACKEND} SHARED ${SW_BACKEND_SOURCES})
-
-SET_TARGET_PROPERTIES(
-    ${TARGET_SW_BACKEND}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
-        SOVERSION ${API_VERSION}
-        VERSION ${VERSION}
-    )
-
-TARGET_LINK_LIBRARIES(${TARGET_SW_BACKEND} ${SW_BACKEND_DEP_LIBRARIES} ${TARGET_COMMON})
-
-INSTALL(TARGETS ${TARGET_SW_BACKEND} DESTINATION ${PLUGIN_DIR})
-
-### TZ-BACKEND ############################################################################
-PKG_CHECK_MODULES(TZ_BACKEND_DEP
-    REQUIRED
-    )
-
-INCLUDE_DIRECTORIES(
-    SYSTEM
-    ${TZ_BACKEND_DEP_INCLUDE_DIRS}
-    ${COMMON_PATH}/include
-    ${SERVER_PATH}/service/include
-    ${DPL_PATH}/core/include
-    ${DPL_PATH}/log/include
-    ${PLUGIN_PATH}
-    )
-
-SET(TZ_BACKEND_SOURCES
-    generic-backend/ipassword.cpp
-    generic-backend/password-file-buffer.cpp
-    tz-backend/password-file.cpp
-    )
-
-ADD_LIBRARY(${TARGET_TZ_BACKEND} SHARED ${TZ_BACKEND_SOURCES})
-
-SET_TARGET_PROPERTIES(
-    ${TARGET_TZ_BACKEND}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
-        SOVERSION ${API_VERSION}
-        VERSION ${VERSION}
-    )
-
-TARGET_LINK_LIBRARIES(${TARGET_TZ_BACKEND} ${TZ_BACKEND_DEP_LIBRARIES} ${TARGET_COMMON})
-
-#INSTALL(TARGETS ${TARGET_TZ_BACKEND} DESTINATION ${PLUGIN_DIR})
diff --git a/src/server/plugin/generic-backend/ipassword-file.h b/src/server/plugin/generic-backend/ipassword-file.h
deleted file mode 100644 (file)
index 4e0cf64..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *  Copyright (c) 2018 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
- */
-#ifndef _IPASSWORD_FILE_H_
-#define _IPASSWORD_FILE_H_
-
-#include <generic-backend/ipassword.h>
-
-#include <string>
-
-#include <time.h>
-
-namespace AuthPasswd {
-
-struct IPasswordFile {
-       IPasswordFile() = default;
-       virtual ~IPasswordFile() = default;
-
-       IPasswordFile(const IPasswordFile&) = delete;
-       IPasswordFile& operator=(const IPasswordFile&) = delete;
-
-       IPasswordFile(IPasswordFile&&) = delete;
-       IPasswordFile& operator=(IPasswordFile&&) = delete;
-
-       virtual void writeMemoryToFile() const = 0;
-       virtual void writeAttemptToFile() const = 0;
-
-       virtual void setPassword(unsigned int passwdType, const std::string &password) = 0;
-       virtual bool checkPassword(unsigned int passwdType,
-                                                          const std::string &password) = 0;
-
-       virtual bool isPasswordActive() const = 0;
-
-       virtual unsigned int getPasswordType() const = 0;
-
-       virtual void setMaxHistorySize(unsigned int history) = 0;
-       virtual unsigned int getMaxHistorySize() const = 0;
-
-       virtual unsigned int getExpireTime() const = 0;
-       virtual void setExpireTime(unsigned int expireTime) = 0;
-
-       virtual unsigned int getExpireTimeLeft() const = 0;
-       virtual void setExpireTimeLeft(time_t expireTimeLeft) = 0;
-
-       virtual unsigned int getAttempt() const = 0;
-       virtual void resetAttempt() = 0;
-       virtual void incrementAttempt() = 0;
-       virtual int getMaxAttempt() const = 0;
-       virtual void setMaxAttempt(unsigned int maxAttempt) = 0;
-
-       virtual bool isPasswordReused(const std::string &password) const = 0;
-
-       virtual bool checkExpiration() const = 0;
-       virtual bool checkIfAttemptsExceeded() const = 0;
-       virtual bool isIgnorePeriod() const = 0;
-
-       virtual bool isHistoryActive() const = 0;
-};
-
-using PasswordFileFactory = AuthPasswd::IPasswordFile* (*)(unsigned int);
-
-} //namespace AuthPasswd
-
-#endif
diff --git a/src/server/plugin/generic-backend/ipassword.cpp b/src/server/plugin/generic-backend/ipassword.cpp
deleted file mode 100644 (file)
index 9bac00c..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- *  Copyright (c) 2019 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
- */
-#include <generic-backend/ipassword.h>
-#include <generic-backend/password-file-buffer.h>
-
-#include <error-description.h>
-#include <password-exception.h>
-
-#include <dpl/fstream_accessors.h>
-
-#include <openssl/sha.h>
-
-namespace AuthPasswd {
-
-NoPassword::NoPassword(IStream&)
-{
-}
-
-void NoPassword::Serialize(IStream &stream) const
-{
-       Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::NONE));
-}
-
-bool NoPassword::match(const std::string &pass) const
-{
-       return pass.empty();
-}
-
-SHA256Password::SHA256Password(IStream &stream)
-{
-       Deserialization::Deserialize(stream, m_hash);
-}
-
-SHA256Password::SHA256Password(const std::string &password) : m_hash(hash(password))
-{
-}
-
-SHA256Password::SHA256Password(const RawHash &paramHash) : m_hash(paramHash)
-{
-}
-
-void SHA256Password::Serialize(IStream &stream) const
-{
-       Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::SHA256));
-       Serialization::Serialize(stream, m_hash);
-}
-
-bool SHA256Password::match(const std::string &password) const
-{
-       return m_hash == hash(password);
-}
-
-RawHash SHA256Password::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;
-}
-
-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);
-       }
-}
-
-} //namespace AuthPasswd
diff --git a/src/server/plugin/generic-backend/ipassword.h b/src/server/plugin/generic-backend/ipassword.h
deleted file mode 100644 (file)
index 21dcd33..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *  Copyright (c) 2019 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
- */
-#ifndef _IPASSWORD_H_
-#define _IPASSWORD_H_
-
-#include <string>
-#include <memory>
-#include <limits>
-
-#include <time.h>
-
-#include <dpl/serialization.h>
-
-namespace AuthPasswd {
-
-constexpr time_t PASSWORD_INFINITE_EXPIRATION_TIME = std::numeric_limits<time_t>::max();
-
-struct IPassword;
-using RawHash = std::vector<unsigned char>;
-using IPasswordPtr = std::shared_ptr<IPassword>;
-using PasswordList = std::list<IPasswordPtr>;
-
-struct IPassword: public ISerializable {
-
-       enum class PasswordType : unsigned int {
-               NONE = 0,
-               SHA256 = 1,
-       };
-
-       virtual bool match(const std::string &password) const = 0;
-};
-
-class NoPassword: public IPassword {
-public:
-       NoPassword() = default;
-       NoPassword(IStream &);
-
-       void Serialize(IStream &stream) const;
-       bool match(const std::string &pass) const;
-};
-
-class SHA256Password: public IPassword {
-public:
-       SHA256Password(IStream &stream);
-       SHA256Password(const std::string &password);
-       SHA256Password(const RawHash &paramHash);
-
-       void Serialize(IStream &stream) const;
-       bool match(const std::string &password) const;
-
-private:
-       static RawHash hash(const std::string &password);
-
-       RawHash m_hash;
-};
-
-template <>
-void Deserialization::Deserialize(IStream &stream, IPasswordPtr &ptr);
-
-} //namespace AuthPasswd
-
-#endif
diff --git a/src/server/plugin/generic-backend/password-file-buffer.cpp b/src/server/plugin/generic-backend/password-file-buffer.cpp
deleted file mode 100644 (file)
index ee809cd..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Jooseong Lee <jooseong.lee@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 <generic-backend/password-file-buffer.h>
-
-#include <fstream>
-#include <iterator>
-
-#include <dpl/log/log.h>
-#include <dpl/fstream_accessors.h>
-
-#include <auth-passwd-error.h>
-#include <password-exception.h>
-
-#include <fcntl.h>
-#include <string.h>
-#include <unistd.h>
-
-namespace AuthPasswd {
-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);
-       }
-
-       void *ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
-
-       if (ret == 0) {
-               LogError("Failed to read " << num << " bytes.");
-               Throw(PasswordException::MemoryError);
-       }
-
-       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. file=" << path);
-               Throw(PasswordException::FStreamOpenError);
-       }
-
-       file.write(m_buffer.data(), m_buffer.size());
-
-       if (!file) {
-               LogError("Failed to write data. file=" << path);
-               Throw(PasswordException::FStreamWriteError);
-       }
-
-       file.flush();
-       if (::fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(file)) != 0)
-               LogError("Failed to synchronize a file's state. file=" << path);
-       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. file=" << path);
-               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() << ", file=" << path);
-               Throw(PasswordException::FStreamReadError);
-       }
-}
-
-} //namespace AuthPasswd
diff --git a/src/server/plugin/generic-backend/password-file-buffer.h b/src/server/plugin/generic-backend/password-file-buffer.h
deleted file mode 100644 (file)
index 2e87cef..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Jooseong Lee <jooseong.lee@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 AuthPasswd {
-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 AuthPasswd
-
-#endif
diff --git a/src/server/plugin/sw-backend/password-file.cpp b/src/server/plugin/sw-backend/password-file.cpp
deleted file mode 100644 (file)
index ca61228..0000000
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Jooseong Lee <jooseong.lee@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)
- * @author      Jooseong Lee (jooseong.lee@samsung.com)
- * @version     1.0
- * @brief       Implementation of PasswordFile, used to manage password files.
- */
-#include <sw-backend/password-file.h>
-
-#include <fstream>
-#include <algorithm>
-
-#include <fcntl.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <dpl/log/log.h>
-#include <dpl/fstream_accessors.h>
-
-#include <auth-passwd-policy-types.h>
-#include <auth-passwd-error.h>
-
-#include <error-description.h>
-#include <policy.h>
-#include <password-exception.h>
-#include <generic-backend/password-file-buffer.h>
-
-extern "C" {
-
-AuthPasswd::IPasswordFile* PasswordFileFactory(unsigned int user)
-{
-       return new AuthPasswd::SWBackend::PasswordFile(user);
-}
-
-} // extern "C"
-
-namespace {
-const std::string PASSWORD_FILE = "/password";
-const std::string OLD_VERSION_PASSWORD_FILE = "/password.old";
-const std::string ATTEMPT_FILE = "/attempt";
-const double RETRY_TIMEOUT = 0.5;
-const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
-const unsigned int CURRENT_FILE_VERSION = 5;
-} // namespace anonymous
-
-namespace AuthPasswd {
-namespace SWBackend {
-
-PasswordFile::PasswordFile(unsigned int user) :
-       m_user(user),
-       m_passwordCurrent(new NoPassword()),
-       m_maxAttempt(PASSWORD_INFINITE_ATTEMPT_COUNT),
-       m_maxHistorySize(0),
-       m_expireTime(PASSWORD_INFINITE_EXPIRATION_DAYS),
-       m_expireTimeLeft(PASSWORD_INFINITE_EXPIRATION_TIME),
-       m_passwordActive(false),
-       m_passwordRcvActive(false),
-       m_attempt(0)
-{
-       // check if data directory exists
-       // if not create it
-       std::string userDir = createDir(RW_DATA_DIR, m_user);
-
-       if (!dirExists(RW_DATA_DIR)) {
-               if (mkdir(RW_DATA_DIR, 0700)) {
-                       LogError("Failed to create directory for files. Error: " << errnoToString());
-                       Throw(PasswordException::MakeDirError);
-               }
-       }
-
-       if (!dirExists(userDir.c_str())) {
-               if (mkdir(userDir.c_str(), 0700)) {
-                       LogError("Failed to create directory for files. Error: " << errnoToString());
-                       Throw(PasswordException::MakeDirError);
-               }
-       }
-
-       preparePwdFile();
-       prepareAttemptFile();
-       resetTimer();
-}
-
-void PasswordFile::resetState()
-{
-       m_maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
-       m_maxHistorySize = 0;
-       m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
-       m_expireTimeLeft = PASSWORD_INFINITE_EXPIRATION_TIME;
-       m_passwordRcvActive = false;
-       m_passwordActive = false;
-       m_passwordCurrent.reset(new NoPassword());
-}
-
-void PasswordFile::resetTimer()
-{
-       m_retryTimerStart = ClockType::now();
-       m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
-}
-
-void PasswordFile::preparePwdFile()
-{
-       std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
-       std::string oldVersionPwdFile = createDir(RW_DATA_DIR, m_user) + OLD_VERSION_PASSWORD_FILE;
-
-       // check if password file exists
-       if (!fileExists(pwdFile)) {
-               // if old format file exist - load it
-               if (loadMemoryFromFile(oldVersionPwdFile)) {
-                       // save in new format
-                       writeMemoryToFile();
-
-                       // and remove old file
-                       if (remove(oldVersionPwdFile.c_str())) {
-                               LogError("Failed to remove file" << oldVersionPwdFile <<
-                                                " Error: " << errnoToString());
-                               Throw(PasswordException::RemoveError);
-                       }
-
-                       return;
-               }
-
-               LogSecureDebug("PWD_DBG not found " << m_user << " password file. Creating.");
-               //create file
-               writeMemoryToFile();
-       } else {     //if file exists, load data
-               LogSecureDebug("PWD_DBG found " << m_user << " password file. Opening.");
-
-               try {
-                       loadMemoryFromFile(pwdFile);
-               } catch (...) {
-                       LogError("Invalid " << pwdFile << " file format");
-                       resetState();
-                       writeMemoryToFile();
-               }
-       }
-}
-
-void PasswordFile::prepareAttemptFile()
-{
-       std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
-
-       // check if attempt file exists
-       // if not create it
-       if (!fileExists(attemptFile)) {
-               LogSecureDebug("PWD_DBG not found " << m_user << " attempt file. Creating.");
-               writeAttemptToFile();
-       } else {
-               LogSecureDebug("PWD_DBG found " << m_user << " attempt file. Opening.");
-               std::ifstream AttemptFile(attemptFile);
-
-               if (!AttemptFile) {
-                       LogError("Failed to open " << m_user << " attempt file.");
-                       // ignore error
-                       return;
-               }
-
-               AttemptFile.read(reinterpret_cast<char *>(&m_attempt), sizeof(unsigned int));
-
-               if (!AttemptFile) {
-                       LogError("Failed to read " << m_user << " 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));
-}
-
-std::string PasswordFile::createDir(const std::string &dir, unsigned int user) const
-{
-       std::string User = std::to_string(user);
-       return dir + "/" + User;
-}
-
-void PasswordFile::writeMemoryToFile() const
-{
-       std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
-       writeMemoryToFile(pwdFile);
-}
-
-void PasswordFile::writeMemoryToFile(const std::string& passwdFilePath) const
-{
-       PasswordFileBuffer pwdBuffer;
-       LogSecureDebug("User: " << m_user << ", saving max_att: " << m_maxAttempt <<
-               ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
-               m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
-               ", isActive: " << m_passwordActive << ", isRcvActive: " <<
-               m_passwordRcvActive << ", m_passwordType: " << m_passwordType);
-       //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_expireTimeLeft);
-       Serialization::Serialize(pwdBuffer, m_passwordRcvActive);
-       Serialization::Serialize(pwdBuffer, m_passwordActive);
-       Serialization::Serialize(pwdBuffer, m_passwordCurrent);
-       Serialization::Serialize(pwdBuffer, m_passwordHistory);
-       Serialization::Serialize(pwdBuffer, m_passwordType);
-
-       pwdBuffer.Save(passwdFilePath);
-       if (chmod(passwdFilePath.c_str(), FILE_MODE)) {
-               LogError("Failed to chmod for " << passwdFilePath << " Error: " << errnoToString());
-               Throw(PasswordException::ChmodError);
-       }
-}
-
-bool PasswordFile::loadMemoryFromFile(const std::string& passwdFilePath)
-{
-       struct stat fileStat;
-
-       if (stat(passwdFilePath.c_str(), &fileStat) != 0)
-               return false;
-
-       PasswordFileBuffer pwdBuffer;
-       pwdBuffer.Load(passwdFilePath);
-       unsigned int fileVersion = 0;
-       Deserialization::Deserialize(pwdBuffer, fileVersion);
-
-       switch (fileVersion) {
-       case 1:
-       case 2:
-       case 3:
-               Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
-               Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
-               Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
-               Deserialization::Deserialize(pwdBuffer, m_passwordActive);
-               Deserialization::Deserialize(pwdBuffer, m_passwordCurrent);
-               Deserialization::Deserialize(pwdBuffer, m_passwordHistory);
-               m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
-               m_passwordRcvActive = false;
-               m_passwordType = 0; // Normal
-               // update file to new format
-               writeMemoryToFile(passwdFilePath);
-               break;
-       case 4:
-               Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
-               Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
-               Deserialization::Deserialize(pwdBuffer, m_expireTime);
-               Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
-               Deserialization::Deserialize(pwdBuffer, m_passwordRcvActive);
-               Deserialization::Deserialize(pwdBuffer, m_passwordActive);
-               Deserialization::Deserialize(pwdBuffer, m_passwordCurrent);
-               Deserialization::Deserialize(pwdBuffer, m_passwordHistory);
-               m_passwordType = 0; // Normal
-               break;
-       default:
-               LogError("Invaild password version: " << fileVersion);
-               Throw(PasswordException::FStreamReadError);
-       }
-
-       LogSecureDebug("loadMemoryFromFile: File=" << passwdFilePath <<
-                ":: User: " << m_user << ", loaded max_att: " << m_maxAttempt <<
-               ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
-               m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
-               ", isActive: " << m_passwordActive << ", isRcvActive: " <<
-               m_passwordRcvActive<< ", m_passwordType: " << m_passwordType);
-       return true;
-}
-
-void PasswordFile::writeAttemptToFile() const
-{
-       std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
-       std::ofstream AttemptFile(attemptFile, std::ofstream::trunc);
-
-       if (!AttemptFile.good()) {
-               LogError("Failed to open " << m_user << " attempt file.");
-               Throw(PasswordException::FStreamOpenError);
-       }
-
-       AttemptFile.write(reinterpret_cast<const char *>(&m_attempt), sizeof(unsigned int));
-
-       if (!AttemptFile) {
-               LogError("Failed to write " << m_user << " attempt count.");
-               Throw(PasswordException::FStreamWriteError);
-       }
-
-       AttemptFile.flush();
-       if (::fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(AttemptFile)) != 0)
-               LogError("Failed to synchronize a file's state.");
-       AttemptFile.close();
-}
-
-bool PasswordFile::isPasswordActive() const
-{
-       return m_passwordActive;
-}
-
-unsigned int PasswordFile::getPasswordType() const
-{
-       return m_passwordType;
-}
-
-void PasswordFile::setMaxHistorySize(unsigned int history)
-{
-       // put current password in history
-       if (m_maxHistorySize == 0 && history > 0)
-               m_passwordHistory.push_front(m_passwordCurrent);
-
-       //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 " << m_user << " 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(m_user << " passwords match!");
-               return true;
-       }
-
-       LogSecureDebug("isPasswordReused: No passwords match, " << m_user <<
-                                  " password not reused.");
-       return false;
-}
-
-void PasswordFile::setPassword(unsigned int passwdType, const std::string &password)
-{
-       m_passwordType = passwdType;
-
-       //replace current password with new one
-       if (password.empty()) {
-               m_passwordCurrent.reset(new NoPassword());
-               m_passwordActive = false;
-       } else {
-               m_passwordCurrent.reset(new SHA256Password(password));
-               //put current password to history
-               m_passwordHistory.push_front(m_passwordCurrent);
-
-               //erase last password if we exceed max history size
-               if (m_passwordHistory.size() > getMaxHistorySize())
-                       m_passwordHistory.pop_back();
-
-               m_passwordActive = true;
-       }
-}
-
-bool PasswordFile::checkPassword(unsigned int passwdType, const std::string &password)
-{
-       if (passwdType != m_passwordType)
-               return false;
-
-       return m_passwordCurrent->match(password);
-}
-
-void PasswordFile::setExpireTime(unsigned int expireTime)
-{
-       m_expireTime = expireTime;
-}
-
-unsigned int PasswordFile::getExpireTime() const
-{
-       return m_expireTime;
-}
-
-void PasswordFile::setExpireTimeLeft(time_t expireTimeLeft)
-{
-       m_expireTimeLeft = expireTimeLeft;
-}
-
-unsigned int PasswordFile::getExpireTimeLeft() const
-{
-       if (m_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) {
-               time_t timeLeft = m_expireTimeLeft - 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_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) && (time(NULL) > m_expireTimeLeft));
-}
-
-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 SWBackend
-} //namespace AuthPasswd
diff --git a/src/server/plugin/sw-backend/password-file.h b/src/server/plugin/sw-backend/password-file.h
deleted file mode 100644 (file)
index 323b8ab..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Jooseong Lee <jooseong.lee@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)
- * @author      Jooseong Lee (jooseong.lee@samsung.com)
- * @version     1.0
- * @brief       Implementation of PasswordFile, used to manage password files.
- */
-#ifndef _SW_BACKEND_PASSWORD_FILE_H_
-#define _SW_BACKEND_PASSWORD_FILE_H_
-
-#include <string>
-#include <vector>
-#include <list>
-#include <chrono>
-#include <memory>
-
-#include <time.h>
-
-#include <dpl/serialization.h>
-
-#include <generic-backend/ipassword-file.h>
-
-namespace AuthPasswd {
-namespace SWBackend {
-
-class PasswordFile : public IPasswordFile {
-public:
-       PasswordFile(unsigned int user);
-       ~PasswordFile() = default;
-
-       PasswordFile(const PasswordFile&) = delete;
-       PasswordFile& operator=(const PasswordFile&) = delete;
-
-       PasswordFile(PasswordFile&&) = delete;
-       PasswordFile& operator=(PasswordFile&&) = delete;
-
-       void writeMemoryToFile() const override;
-       void writeAttemptToFile() const override;
-
-       void setPassword(unsigned int passwdType, const std::string &password) override;
-       bool checkPassword(unsigned int passwdType,
-                                          const std::string &password) override;
-
-       bool isPasswordActive() const override;
-
-       unsigned int getPasswordType() const override;
-
-       void setMaxHistorySize(unsigned int history) override;
-       unsigned int getMaxHistorySize() const override;
-
-       unsigned int getExpireTime() const override;
-       void setExpireTime(unsigned int expireTime) override;
-
-       unsigned int getExpireTimeLeft() const override;
-       void setExpireTimeLeft(time_t expireTimeLeft) override;
-
-       unsigned int getAttempt() const override;
-       void resetAttempt() override;
-       void incrementAttempt() override;
-       int getMaxAttempt() const override;
-       void setMaxAttempt(unsigned int maxAttempt) override;
-
-       bool isPasswordReused(const std::string &password) const override;
-
-       bool checkExpiration() const override;
-       bool checkIfAttemptsExceeded() const override;
-       bool isIgnorePeriod() const override;
-
-       bool isHistoryActive() const override;
-
-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;
-
-       bool loadMemoryFromFile(const std::string &passwdFilePath);
-       void writeMemoryToFile(const std::string &passwdFilePath) const;
-
-       void resetTimer();
-       void preparePwdFile();
-       void prepareAttemptFile();
-       void resetState();
-       bool fileExists(const std::string &filename) const;
-       bool dirExists(const std::string &dirpath) const;
-       std::string createDir(const std::string &dir, unsigned int user) const;
-
-       mutable TimePoint m_retryTimerStart;
-
-       const unsigned int m_user;
-
-       ::AuthPasswd::IPasswordPtr m_passwordCurrent;
-       ::AuthPasswd::PasswordList m_passwordHistory;
-       unsigned int m_maxAttempt;
-       unsigned int m_maxHistorySize;
-       unsigned int m_expireTime;
-       time_t       m_expireTimeLeft;
-       bool         m_passwordActive;
-       bool         m_passwordRcvActive;
-       unsigned int m_passwordType;
-
-       //attempt file data
-       unsigned int m_attempt;
-};
-
-} // namespace SWBackend
-} // namespace AuthPasswd
-
-#endif
diff --git a/src/server/plugin/tz-backend/password-file.cpp b/src/server/plugin/tz-backend/password-file.cpp
deleted file mode 100644 (file)
index 529c59b..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- *  Copyright (c) 2018 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
- */
-#include <tz-backend/password-file.h>
-
-#include <stdexcept>
-
-#include <generic-backend/password-file-buffer.h>
-
-extern "C" {
-
-AuthPasswd::IPasswordFile* PasswordFileFactory(unsigned int user)
-{
-       return new AuthPasswd::TZBackend::PasswordFile(user);
-}
-
-} // extern "C"
-
-namespace AuthPasswd {
-namespace TZBackend {
-
-PasswordFile::PasswordFile(unsigned int)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-void PasswordFile::writeMemoryToFile() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-void PasswordFile::writeAttemptToFile() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-void PasswordFile::setPassword(unsigned int, const std::string &)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-bool PasswordFile::checkPassword(unsigned int,
-                                                                const std::string &)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-unsigned int PasswordFile::getPasswordType() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-void PasswordFile::setMaxHistorySize(unsigned int)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-unsigned int PasswordFile::getMaxHistorySize() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-unsigned int PasswordFile::getExpireTime() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-void PasswordFile::setExpireTime(unsigned int)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-void PasswordFile::setExpireTimeLeft(time_t)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-unsigned int PasswordFile::getExpireTimeLeft() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-unsigned int PasswordFile::getAttempt() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-void PasswordFile::resetAttempt()
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-void PasswordFile::incrementAttempt()
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-int PasswordFile::getMaxAttempt() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return -1;
-}
-
-void PasswordFile::setMaxAttempt(unsigned int)
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-}
-
-bool PasswordFile::isPasswordActive() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-bool PasswordFile::isPasswordReused(const std::string &) const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-bool PasswordFile::checkExpiration() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-bool PasswordFile::checkIfAttemptsExceeded() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-bool PasswordFile::isIgnorePeriod() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-bool PasswordFile::isHistoryActive() const
-{
-       std::runtime_error("TZ-Backend is not implemented.");
-       return false;
-}
-
-} //namespace TZBackend
-} //namespace AuthPasswd
diff --git a/src/server/plugin/tz-backend/password-file.h b/src/server/plugin/tz-backend/password-file.h
deleted file mode 100644 (file)
index 48d62eb..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *  Copyright (c) 2018 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
- */
-#ifndef _TZ_BACKEND_PASSWORD_FILE_H_
-#define _TZ_BACKEND_PASSWORD_FILE_H_
-
-#include <string>
-#include <generic-backend/ipassword-file.h>
-
-namespace AuthPasswd {
-namespace TZBackend {
-
-class PasswordFile : public IPasswordFile {
-public:
-       PasswordFile(unsigned int user);
-
-       PasswordFile(const PasswordFile&) = delete;
-       PasswordFile& operator=(const PasswordFile&) = delete;
-
-       PasswordFile(PasswordFile&&) = delete;
-       PasswordFile& operator=(PasswordFile&&) = delete;
-
-       void writeMemoryToFile() const override;
-       void writeAttemptToFile() const override;
-
-       void setPassword(unsigned int passwdType, const std::string &password) override;
-       bool checkPassword(unsigned int passwdType,
-                                          const std::string &password) override;
-
-       unsigned int getPasswordType() const override;
-
-       void setMaxHistorySize(unsigned int history) override;
-       unsigned int getMaxHistorySize() const override;
-
-       unsigned int getExpireTime() const override;
-       void setExpireTime(unsigned int expireTime) override;
-
-       unsigned int getExpireTimeLeft() const override;
-       void setExpireTimeLeft(time_t expireTimeLeft) override;
-
-       unsigned int getAttempt() const override;
-       void resetAttempt() override;
-       void incrementAttempt() override;
-       int getMaxAttempt() const override;
-       void setMaxAttempt(unsigned int maxAttempt) override;
-
-       bool isPasswordActive() const override;
-       bool isPasswordReused(const std::string &password) const override;
-
-       bool checkExpiration() const override;
-       bool checkIfAttemptsExceeded() const override;
-       bool isIgnorePeriod() const override;
-
-       bool isHistoryActive() const override;
-};
-
-} // namespace TZBackend
-} // namespace AuthPasswd
-
-#endif
index c6a22cc145b4d6ca4aa779fd46de8a9db0a97f55..588bfe5f96f6adc41beb0618bf55d40412a5dde7 100644 (file)
 #include <map>
 #include <memory>
 
-#include <plugin-manager.h>
-
-#include <generic-backend/ipassword-file.h>
-
 namespace AuthPasswd {
 class PasswordManager final {
 public:
-       typedef std::map<unsigned int, IPasswordFile*> PasswordFileMap;
+       // typedef std::map<unsigned int, IPasswordFile*> PasswordFileMap;
 
        PasswordManager();
        ~PasswordManager();
 
        //checking functions
        //no const in checkPassword, attempts are update
-       int checkPassword(unsigned int passwdType, const std::string &challenge,
-                                         unsigned int currentUser, unsigned int &currentAttempt,
-                                         unsigned int &maxAttempt, unsigned int &expirationTime);
+       int checkPassword(unsigned int passwdType,const std::string &challenge, unsigned int currentUser,
+                                       unsigned int &currentAttempt, unsigned int &maxAttempt,
+                                       unsigned int &expirationTime);
        int isPwdValid(unsigned int passwdType, unsigned int currentUser,
-                                  unsigned int &currentAttempt, unsigned int &maxAttempt,
-                                  unsigned int &expirationTime);
+                                       unsigned int &currentAttempt, unsigned int &maxAttempt,
+                                       unsigned int &expirationTime);
        int isPwdReused(unsigned int passwdType, const std::string &passwd,
                                        unsigned int currentUser, bool &isReused);
 
@@ -58,26 +54,23 @@ public:
        int setPassword(unsigned int curPasswdType, const std::string &currentPassword,
                                        unsigned int newPasswdType, const std::string &newPassword, unsigned int currentUser);
 
+       int setPasswordWithTypeRestore(unsigned int initPasswdType, unsigned int curPasswdType,
+                                       const std::string &currentPassword, unsigned int newPasswdType,
+                                       const std::string &newPassword, unsigned int currentUser);
+
        //resetting functions
        int resetPassword(unsigned int passwdType, const std::string &newPassword,
                                          unsigned int receivedUser);
 
        //setting policy on the current passwd
-       void setPasswordMaxAttempts(unsigned int receivedUser,
+       void setPasswordMaxAttempts(unsigned int passwordType, unsigned int receivedUser,
                                                                unsigned int receivedAttempts);
-       void setPasswordValidity(unsigned int receivedUser, unsigned int receivedDays);
-       void setPasswordHistory(unsigned int receivedUser, unsigned int receivedHistory);
+       void setPasswordValidity(unsigned int passwordType, unsigned int receivedUser, unsigned int receivedDays);
+       void setPasswordHistory(unsigned int passwordType, unsigned int receivedUser, unsigned int receivedHistory);
 
 private:
        //managing functions
-       void addPassword(unsigned int user);
-       void removePassword(unsigned int user);
-       void existPassword(unsigned int user);
-
-       PasswordFileMap m_pwdFile;
-       PasswordFileFactory m_factory = nullptr;
-
-       PluginManager m_pluginManager;
+       void existPassword(unsigned int passwordType, unsigned int user, bool needRestore);
 };
 } //namespace AuthPasswd
 
diff --git a/src/server/service/include/plugin-loader.h b/src/server/service/include/plugin-loader.h
deleted file mode 100644 (file)
index d5f1491..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- *  Copyright (c) 2018 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        plugin-loader.h
- * @author      Sangwan Kwon(sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Plugin loader for loading backend.
- */
-#pragma once
-
-#include <string>
-#include <stdexcept>
-
-#include <dlfcn.h>
-
-namespace AuthPasswd {
-
-class PluginLoader final {
-public:
-       explicit PluginLoader(const std::string& path, int flag = RTLD_LAZY);
-       ~PluginLoader();
-
-       PluginLoader(const PluginLoader&) = delete;
-       PluginLoader& operator=(const PluginLoader&) = delete;
-
-       PluginLoader(PluginLoader&&) = delete;
-       PluginLoader& operator=(PluginLoader&&) = delete;
-
-       template<typename T>
-       void load(const std::string& name, T& symbol);
-
-private:
-       void* m_handle;
-};
-
-template<typename T>
-void PluginLoader::load(const std::string& name, T& symbol)
-{
-       symbol = reinterpret_cast<T>(::dlsym(m_handle, name.c_str()));
-       if (symbol == nullptr)
-               throw std::runtime_error("Failed to load: " + name);
-}
-
-} //namespace AuthPasswd
diff --git a/src/server/service/include/plugin-manager.h b/src/server/service/include/plugin-manager.h
deleted file mode 100644 (file)
index a0e59d9..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- *  Copyright (c) 2018 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        plugin-manager.h
- * @author      Sangwan Kwon(sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Plugin manager for binding backend.
- */
-#pragma once
-
-#include <string>
-#include <memory>
-
-#include <plugin-loader.h>
-
-namespace AuthPasswd {
-
-enum class BackendType {
-       SW,
-       TZ
-};
-
-class PluginManager final {
-public:
-       explicit PluginManager() noexcept = default;
-       ~PluginManager() = default;
-
-       PluginManager(const PluginManager&) = delete;
-       PluginManager& operator=(const PluginManager&) = delete;
-
-       PluginManager(PluginManager&&) = delete;
-       PluginManager& operator=(PluginManager&&) = delete;
-
-       bool isSupport(BackendType type) const noexcept;
-
-       void setBackend(BackendType type);
-
-       template<typename T>
-       void loadFactory(const std::string& name, T& factory);
-
-private:
-       std::string getPluginPath(BackendType type) const noexcept;
-
-       std::shared_ptr<PluginLoader> m_loader = nullptr;
-};
-
-template<typename T>
-void PluginManager::loadFactory(const std::string& name, T& factory)
-{
-       m_loader->load(name, factory);
-}
-
-} //namespace AuthPasswd
diff --git a/src/server/service/include/policy-file-buffer.h b/src/server/service/include/policy-file-buffer.h
new file mode 100644 (file)
index 0000000..6f4bc1b
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *  Copyright (c) 2000 - 2025 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Jooseong Lee <jooseong.lee@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        policy-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 _POLICY_FILE_BUFFER_H_
+#define _POLICY_FILE_BUFFER_H_
+
+#include <stddef.h>
+#include <vector>
+#include <string>
+
+#include <dpl/serialization.h>
+
+namespace AuthPasswd {
+class PolicyFileBuffer: public IStream {
+public:
+       PolicyFileBuffer();
+
+       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 AuthPasswd
+
+#endif
index 940cab0118bcfcb54648b097d3263aa7b7ae07bb..05393eea57af1e0e17eef7961e31096119b84748 100644 (file)
  * @brief       Implementation of password management functions
  */
 
+#include <limits>
 #include <password-manager.h>
 
 #include <iostream>
 #include <iterator>
 #include <algorithm>
-
+#include <time.h>
 #include <limits.h>
 
 #include <dpl/log/log.h>
 #include <auth-passwd-error.h>
 
 #include <policy.h>
+#include <hal/hal-security-auth.h>
 
 namespace {
 void calculateExpiredTime(unsigned int receivedDays, time_t &validSecs)
 {
-       validSecs = AuthPasswd::PASSWORD_INFINITE_EXPIRATION_TIME;
+       validSecs = std::numeric_limits<time_t>::max();
 
        //when receivedDays means infinite expiration, return default validSecs value.
        if (receivedDays == AuthPasswd::PASSWORD_INFINITE_EXPIRATION_DAYS)
@@ -52,62 +54,89 @@ void calculateExpiredTime(unsigned int receivedDays, time_t &validSecs)
        validSecs = (curTime + (receivedDays * 86400));
        return;
 }
-
-bool isValidPasswordType(unsigned int type)
+bool isValidPasswordType(unsigned int type, hal_security_auth_password_type_e &password_type)
 {
        switch(type) {
-       case AUTH_PWD_NORMAL:
-       case AUTH_PWD_PIN:
-       case AUTH_PWD_PATTERN:
-               return true;
+               case AUTH_PWD_NORMAL:
+                       password_type = hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_NORMAL;
+                       return true;
+               case AUTH_PWD_PIN:
+                       password_type = hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_PIN;
+                       return true;
+               case AUTH_PWD_PATTERN:
+                       password_type = hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_PATTERN;
+                       return true;
+               default:
+                       password_type = hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_NORMAL;
+                       return false;
        }
-       return false;
 }
-} //namespace
 
-namespace AuthPasswd {
-
-PasswordManager::PasswordManager()
+unsigned int getUnitType(hal_security_auth_password_type_e password_type)
 {
-       if (m_pluginManager.isSupport(BackendType::TZ)) {
-               m_pluginManager.setBackend(BackendType::TZ);
-               LogDebug("Success to set TZ-Backend.");
-       } else {
-               m_pluginManager.setBackend(BackendType::SW);
-               LogDebug("Success to set SW-Backend.");
+       switch(password_type) {
+               case hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_NORMAL:
+                       return AUTH_PWD_NORMAL;
+               case hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_PIN:
+                       return AUTH_PWD_PIN;
+               case hal_security_auth_password_type_e::HAL_SECURITY_AUTH_PASSWORD_PATTERN:
+                       return AUTH_PWD_PATTERN;
+               default:
+                       return AUTH_PWD_NORMAL;
        }
-
-       m_pluginManager.loadFactory("PasswordFileFactory", m_factory);
 }
-
-PasswordManager::~PasswordManager()
+bool isCurrentPasswordType(unsigned int user,unsigned int passwordType)
 {
-       PasswordFileMap::iterator iter;
-       for (iter = m_pwdFile.begin(); iter != m_pwdFile.end(); iter++) {
-               if (iter->second != nullptr)
-                       delete iter->second;
+       hal_security_auth_password_type_e currentPasswordType, req_password_type;
+       hal_security_auth_get_password_type(user, &currentPasswordType);
+       if (!isValidPasswordType(passwordType, req_password_type)) {
+               LogError("Not supported password type: " << req_password_type);
+               return false;
+       }
+       if (currentPasswordType != req_password_type) {
+               LogError("Password Type mismatch. provided=" << req_password_type
+                                                                       << ", stored=" << currentPasswordType);
+               return false;
        }
+       return true;
 }
+} //namespace
+
+namespace AuthPasswd {
 
-void PasswordManager::addPassword(unsigned int user)
+PasswordManager::PasswordManager()
 {
-       IPasswordFile* passwordFile = (*m_factory)(user);
-       m_pwdFile[user] = passwordFile;
+       int error = hal_security_auth_get_backend();
+       if (error) {
+               LogError("Can't get security_auth backend: " << error);
+               throw std::runtime_error("Can't get security_auth backend");
+       }
 }
 
-void PasswordManager::removePassword(unsigned int user)
+PasswordManager::~PasswordManager()
 {
-       m_pwdFile.erase(user);
+       hal_security_auth_put_backend();
 }
 
-void PasswordManager::existPassword(unsigned int user)
+void PasswordManager::existPassword(unsigned int passwordType, unsigned int user, bool needRestore)
 {
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(user);
-
-       if (itPwd != m_pwdFile.end())
+       hal_security_auth_password_type_e currentPasswordType, reqPasswordType;
+       hal_security_auth_get_password_type(user, &currentPasswordType);
+       if (!isValidPasswordType(passwordType, reqPasswordType)) {
+               LogError("Not supported password type: " << reqPasswordType);
                return;
+       }
+       if ((currentPasswordType != reqPasswordType) && !needRestore) {
+               LogError("Password Type mismatch. provided=" << reqPasswordType
+                                                                       << ", stored=" << currentPasswordType);
+               return;
+       }
+       int error = hal_security_auth_create_password_file(user,reqPasswordType);
 
-       addPassword(user);
+       if (error) {
+               LogError("Can't create password_file in security_auth backend: " << error);
+               throw std::runtime_error("Can't create password_file in security_auth backend");
+       }
        return;
 }
 
@@ -119,41 +148,44 @@ int PasswordManager::checkPassword(unsigned int passwdType,
                                                                   unsigned int &expirationTime)
 {
        LogSecureDebug("Inside checkPassword function.");
-       existPassword(currentUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+       existPassword(passwdType, currentUser, false);
 
-       if (itPwd->second->isIgnorePeriod()) {
+       if(hal_security_auth_is_ignore_period(currentUser) == AUTH_PASSWD_API_SUCCESS){
                LogError("Retry timeout occurred.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
        }
 
-       if (!itPwd->second->isPasswordActive() && !challenge.empty()) {
+       if ((hal_security_auth_is_password_active(currentUser) != AUTH_PASSWD_API_SUCCESS)
+                                                                                               && !challenge.empty()) {
                LogError("Password not active.");
                return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
        }
+       hal_security_auth_increment_attempt(currentUser);
+       hal_security_auth_write_attempt_to_file(currentUser);
+       hal_security_auth_get_attempt(currentUser,&currentAttempt);
+       hal_security_auth_get_max_attempt(currentUser, &maxAttempt);
+       hal_security_auth_get_expire_time_left(currentUser,&expirationTime);
 
-       itPwd->second->incrementAttempt();
-       itPwd->second->writeAttemptToFile();
-       currentAttempt = itPwd->second->getAttempt();
-       maxAttempt = itPwd->second->getMaxAttempt();
-       expirationTime = itPwd->second->getExpireTimeLeft();
-
-       if (itPwd->second->checkIfAttemptsExceeded()) {
+       if (hal_security_auth_check_attempt_exceeded(currentUser) != AUTH_PASSWD_API_SUCCESS) {
                LogError("Too many tries.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
        }
 
-       if (!itPwd->second->checkPassword(passwdType, challenge)) {
+       if(!isCurrentPasswordType(currentUser,passwdType))
+               return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+
+       const char* ch_challenge = challenge.data();
+       if (hal_security_auth_check_password(currentUser, ch_challenge) != AUTH_PASSWD_API_SUCCESS) {
                LogError("Wrong password.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
        }
 
        // Password maches and attempt number is fine - time to reset counter.
-       itPwd->second->resetAttempt();
-       itPwd->second->writeAttemptToFile();
+       hal_security_auth_reset_attempt(currentUser);
+       hal_security_auth_write_attempt_to_file(currentUser);
 
        // Password is too old. You must change it before login.
-       if (itPwd->second->checkExpiration()) {
+       if (hal_security_auth_check_expiration(currentUser) == AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED) {
                LogError("Password expired.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED;
        }
@@ -165,23 +197,19 @@ int PasswordManager::isPwdValid(unsigned int passwdType, unsigned int currentUse
                                                                unsigned int &currentAttempt, unsigned int &maxAttempt,
                                                                unsigned int &expirationTime)
 {
-       existPassword(currentUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
-       if (itPwd->second->getPasswordType() != passwdType) {
-               LogError("Password Type mismatch. provided=" << passwdType
-                                                                       << ", stored=" << itPwd->second->getPasswordType());
+       if(!isCurrentPasswordType(currentUser,passwdType)){
+               LogError("isPwdValid Not supported password type for currentUser: " << currentUser << " passwdType : " << passwdType);
                return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
        }
+       existPassword(passwdType, currentUser, false);
 
-       if (!itPwd->second->isPasswordActive()) {
+       if (hal_security_auth_is_password_active(currentUser) != AUTH_PASSWD_API_SUCCESS) {
                LogError("Current password not active.");
                return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
        }
-
-       currentAttempt = itPwd->second->getAttempt();
-       maxAttempt = itPwd->second->getMaxAttempt();
-       expirationTime = itPwd->second->getExpireTimeLeft();
+       hal_security_auth_get_attempt(currentUser,&currentAttempt);
+       hal_security_auth_get_max_attempt(currentUser,&maxAttempt);
+       hal_security_auth_get_expire_time_left(currentUser, &expirationTime);
 
        return AUTH_PASSWD_API_SUCCESS;
 }
@@ -189,90 +217,115 @@ int PasswordManager::isPwdValid(unsigned int passwdType, unsigned int currentUse
 int PasswordManager::isPwdReused(unsigned int passwdType, const std::string &passwd,
                                                                 unsigned int currentUser, bool &isReused)
 {
-       existPassword(currentUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
        isReused = false;
+       existPassword(passwdType, currentUser, false);
 
-       if (itPwd->second->getPasswordType() != passwdType) {
-               LogError("Password Type mismatch. provided=" << passwdType
-                                                                       << ", stored=" << itPwd->second->getPasswordType());
+       if(!isCurrentPasswordType(currentUser,passwdType)){
+               LogError("isPwdReused Not supported password type for currentUser: " << currentUser << " passwdType : " << passwdType);
                return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
        }
 
        // check history, however only if history is active and password is not empty
-       if (itPwd->second->isHistoryActive() && !passwd.empty())
-               isReused = itPwd->second->isPasswordReused(passwd);
+       if (hal_security_auth_is_history_active(currentUser) != AUTH_PASSWD_API_SUCCESS && !passwd.empty()){
+               const char* ch_passwd = passwd.data();
+               if(hal_security_auth_is_password_reused(currentUser, ch_passwd) == AUTH_PASSWD_API_SUCCESS){
+                       isReused = true;
+               }
+       }
 
        return AUTH_PASSWD_API_SUCCESS;
 }
-
-int PasswordManager::setPassword(unsigned int curPasswdType,
+int PasswordManager::setPasswordWithTypeRestore(unsigned int initTypeBackup, unsigned int curPasswdType,
                                                                 const std::string &currentPassword,
                                                                 unsigned int newPasswdType,
                                                                 const std::string &newPassword,
-                                                                unsigned int currentUser)
-{
+                                                                unsigned int currentUser){
        LogSecureDebug("curUser = " << currentUser
                                        << ", curPwdType = " << curPasswdType <<  ", curPwd = " << "****"
                                        << ", newPasswdType = " << newPasswdType << ", newPwd = " << "****");
        unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
        time_t valid_secs = 0;
-       existPassword(currentUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
-       if (!isValidPasswordType(newPasswdType)) {
-               LogError("Not supported new password type: " << newPasswdType);
+       hal_security_auth_password_type_e req_new_password_type;
+       if (!isValidPasswordType(newPasswdType, req_new_password_type)) {
+               LogError("setPassword Not supported new password type: " << newPasswdType);
                return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
        }
-
-       if (itPwd->second->isIgnorePeriod()) {
+       if (hal_security_auth_is_ignore_period(currentUser) == AUTH_PASSWD_API_SUCCESS) {
                LogError("Retry timeout occured.");
+
                return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
        }
 
        // check delivered currentPassword
        // when m_passwordActive flag is false, current password should be empty
-       if (!currentPassword.empty() && !itPwd->second->isPasswordActive()) {
+       if (!currentPassword.empty() && hal_security_auth_is_password_active(currentUser) != AUTH_PASSWD_API_SUCCESS) {
                LogError("Password not active.");
                return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
        }
 
        //increment attempt count before checking it against max attempt count
-       itPwd->second->incrementAttempt();
-       itPwd->second->writeAttemptToFile();
+       hal_security_auth_increment_attempt(currentUser);
+       hal_security_auth_write_attempt_to_file(currentUser);
 
-       if (itPwd->second->checkIfAttemptsExceeded()) {
+       if (hal_security_auth_check_attempt_exceeded(currentUser) == AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED) {
                LogError("Too many tries.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
        }
 
-       if (!itPwd->second->checkPassword(curPasswdType, currentPassword)) {
+       if(initTypeBackup != curPasswdType){
+               LogError("request Current Password type mismatch.");
+               return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+       }
+       const char* ch_currentPassword = currentPassword.data();
+       if (hal_security_auth_check_password(currentUser, ch_currentPassword) != AUTH_PASSWD_API_SUCCESS) {
                LogError("Wrong password.");
                return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
        }
 
        //here we are sure that user knows current password - we can reset attempt counter
-       itPwd->second->resetAttempt();
-       itPwd->second->writeAttemptToFile();
+       hal_security_auth_reset_attempt(currentUser);
+       hal_security_auth_write_attempt_to_file(currentUser);
 
        // check history, however only if history is active and new password is not empty
-       if (itPwd->second->isHistoryActive() && !newPassword.empty()) {
-               if (itPwd->second->isPasswordReused(newPassword)) {
+       if (hal_security_auth_is_history_active(currentUser) == AUTH_PASSWD_API_SUCCESS && !newPassword.empty()) {
+               const char* ch_newPassword = newPassword.data();
+               if (hal_security_auth_is_password_reused(currentUser, ch_newPassword) == AUTH_PASSWD_API_SUCCESS) {
                        LogError("Password reused.");
                        return AUTH_PASSWD_API_ERROR_PASSWORD_REUSED;
                }
        }
 
        if (!newPassword.empty())
-               receivedDays = itPwd->second->getExpireTime();
+               hal_security_auth_get_expire_time(currentUser, &receivedDays);
 
        calculateExpiredTime(receivedDays, valid_secs);
        //setting password
-       itPwd->second->setPassword(newPasswdType, newPassword);
-       itPwd->second->setExpireTimeLeft(valid_secs);
-       itPwd->second->writeMemoryToFile();
+       const char* ch_newPassword = newPassword.data();
+       hal_security_auth_set_password(currentUser, ch_newPassword);
+       hal_security_auth_set_expire_time_left(currentUser, valid_secs);
+       hal_security_auth_write_memory_to_file(currentUser);
 
        return AUTH_PASSWD_API_SUCCESS;
+
+}
+int PasswordManager::setPassword(unsigned int curPasswdType,
+                                                                const std::string &currentPassword,
+                                                                unsigned int newPasswdType,
+                                                                const std::string &newPassword,
+                                                                unsigned int currentUser)
+{
+       hal_security_auth_password_type_e passwdEnumType;
+
+       hal_security_auth_get_password_type(currentUser, &passwdEnumType);
+       unsigned int passwdUnitType = getUnitType(passwdEnumType);
+
+       existPassword(newPasswdType, currentUser, true);
+
+       int result = setPasswordWithTypeRestore(passwdUnitType, curPasswdType, currentPassword,newPasswdType, newPassword,currentUser);
+       if(result != AUTH_PASSWD_API_SUCCESS){
+               existPassword(passwdUnitType, currentUser, true);
+       }
+       return result;
 }
 
 int PasswordManager::resetPassword(unsigned int passwdType,
@@ -281,64 +334,66 @@ int PasswordManager::resetPassword(unsigned int passwdType,
 {
        unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
        time_t valid_secs = 0;
-       existPassword(receivedUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+       existPassword(passwdType, receivedUser, true);
+       hal_security_auth_password_type_e req_password_type;
 
-       if (!isValidPasswordType(passwdType)) {
-               LogError("Not supported password type: " << passwdType);
+       if (!isValidPasswordType(passwdType, req_password_type)) {
+               LogError("resetPassword Not supported password type: " << req_password_type);
                return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
        }
 
        if (!newPassword.empty())
-               receivedDays = itPwd->second->getExpireTime();
+               hal_security_auth_get_expire_time(receivedUser, &receivedDays);
+               // receivedDays = itPwd->second->getExpireTime();
 
        calculateExpiredTime(receivedDays, valid_secs);
-       itPwd->second->resetAttempt();
-       itPwd->second->writeAttemptToFile();
-       itPwd->second->setPassword(passwdType, newPassword);
-       itPwd->second->setExpireTimeLeft(valid_secs);
-       itPwd->second->writeMemoryToFile();
+       hal_security_auth_reset_attempt(receivedUser);
+       hal_security_auth_write_attempt_to_file(receivedUser);
+       const char* ch_newPassword = newPassword.data();
+       hal_security_auth_set_password(receivedUser, ch_newPassword);
+       hal_security_auth_set_expire_time_left(receivedUser, valid_secs);
+       hal_security_auth_write_memory_to_file(receivedUser);
+
 
        return AUTH_PASSWD_API_SUCCESS;
 }
 
-void PasswordManager::setPasswordMaxAttempts(unsigned int receivedUser,
+void PasswordManager::setPasswordMaxAttempts(unsigned int passwdType, unsigned int receivedUser,
                unsigned int receivedAttempts)
 {
        LogSecureDebug("received_attempts: " << receivedAttempts);
-       existPassword(receivedUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
-       itPwd->second->setMaxAttempt(receivedAttempts);
-       itPwd->second->writeMemoryToFile();
+       existPassword(passwdType, receivedUser, false);
+       hal_security_auth_set_max_attempt(receivedUser, receivedAttempts);
+       hal_security_auth_write_memory_to_file(receivedUser);
        // Do not reset current attempt when max attempt is reset.
        // It's a platform policy(2017.0327).
        //itPwd->second->resetAttempt();
        //itPwd->second->writeAttemptToFile();
 }
 
-void PasswordManager::setPasswordValidity(unsigned int receivedUser,
+void PasswordManager::setPasswordValidity(unsigned int passwdType, unsigned int receivedUser,
                unsigned int receivedDays)
 {
        LogSecureDebug("received_days: " << receivedDays);
        time_t valid_secs = 0;
-       existPassword(receivedUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+       existPassword(passwdType, receivedUser, false);
        calculateExpiredTime(receivedDays, valid_secs);
 
-       if (itPwd->second->isPasswordActive())
-               itPwd->second->setExpireTimeLeft(valid_secs);
-
-       itPwd->second->setExpireTime(receivedDays);
-       itPwd->second->writeMemoryToFile();
+       if (hal_security_auth_is_password_active(receivedUser) == AUTH_PASSWD_API_SUCCESS){
+               LogError("setPasswordValidity is not password active : " << receivedDays << " validSecs : " << valid_secs);
+               hal_security_auth_set_expire_time_left(receivedUser ,valid_secs);
+       }
+       LogError("setPasswordValidity exit received_days : " << receivedDays << " validSecs : " << valid_secs);
+       hal_security_auth_set_expire_time(receivedUser ,receivedDays);
+       hal_security_auth_write_memory_to_file(receivedUser);
 }
 
-void PasswordManager::setPasswordHistory(unsigned int receivedUser,
+void PasswordManager::setPasswordHistory(unsigned int passwdType, unsigned int receivedUser,
                unsigned int receivedHistory)
 {
        LogSecureDebug("received_historySize: " << receivedHistory);
-       existPassword(receivedUser);
-       PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
-       itPwd->second->setMaxHistorySize(receivedHistory);
-       itPwd->second->writeMemoryToFile();
+       existPassword(passwdType, receivedUser, false);
+       hal_security_auth_set_max_history_size(receivedUser ,receivedHistory);
+       hal_security_auth_write_memory_to_file(receivedUser);
 }
 } //namespace AuthPasswd
index 95470d1523607df382e156c6be2ddf47125aa35b..83119632236088d409b37e9b3c8c7bd8a23e91b2 100644 (file)
@@ -16,7 +16,7 @@
  *  limitations under the License
  */
 /*
- * @file        policy-manager.cpp
+ * @file        password-policy-manager.cpp
  * @author      Jooseong Lee (jooseong.lee@samsung.com)
  * @version     1.0
  * @brief       Implementation of password policy management functions
index 8016763ac6a5ecbb99f0f5082c14976d526304a0..446d3180cfc90f659dd9423849e7e181424a97e7 100644 (file)
@@ -235,13 +235,13 @@ int PasswordService::processPolicyFunctions(PasswordHdrs hdr, MessageBuffer &buf
 
                if (result == AUTH_PASSWD_API_SUCCESS) {
                        if (policy.isFlagOn(POLICY_MAX_ATTEMPTS))
-                               m_pwdManager.setPasswordMaxAttempts(policy.uid, policy.maxAttempts);
+                               m_pwdManager.setPasswordMaxAttempts(policy.passwordType, policy.uid, policy.maxAttempts);
 
                        if (policy.isFlagOn(POLICY_VALID_PERIOD))
-                               m_pwdManager.setPasswordValidity(policy.uid, policy.validPeriod);
+                               m_pwdManager.setPasswordValidity(policy.passwordType, policy.uid, policy.validPeriod);
 
                        if (policy.isFlagOn(POLICY_HISTORY_SIZE))
-                               m_pwdManager.setPasswordHistory(policy.uid, policy.historySize);
+                               m_pwdManager.setPasswordHistory(policy.passwordType, policy.uid, policy.historySize);
                }
 
                break;
@@ -255,9 +255,9 @@ int PasswordService::processPolicyFunctions(PasswordHdrs hdr, MessageBuffer &buf
                result = m_policyManager.disablePolicy(rec_user, rec_passwordType);
 
                if (result == AUTH_PASSWD_API_SUCCESS) {
-                       m_pwdManager.setPasswordMaxAttempts(rec_user, PASSWORD_INFINITE_ATTEMPT_COUNT);
-                       m_pwdManager.setPasswordValidity(rec_user, PASSWORD_INFINITE_EXPIRATION_DAYS);
-                       m_pwdManager.setPasswordHistory(rec_user, 0);
+                       m_pwdManager.setPasswordMaxAttempts(rec_passwordType, rec_user, PASSWORD_INFINITE_ATTEMPT_COUNT);
+                       m_pwdManager.setPasswordValidity(rec_passwordType, rec_user, PASSWORD_INFINITE_EXPIRATION_DAYS);
+                       m_pwdManager.setPasswordHistory(rec_passwordType, rec_user, 0);
                }
 
                break;
diff --git a/src/server/service/plugin-loader.cpp b/src/server/service/plugin-loader.cpp
deleted file mode 100644 (file)
index 8face74..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- *  Copyright (c) 2018 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        plugin-loader.cpp
- * @author      Sangwan Kwon(sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Implementation of plugin loader.
- */
-#include <plugin-loader.h>
-
-namespace AuthPasswd {
-
-PluginLoader::PluginLoader(const std::string& path, int flag)
-       : m_handle(::dlopen(path.c_str(), flag))
-{
-       if (m_handle == nullptr)
-               throw std::invalid_argument("Failed to open: " + path);
-}
-
-PluginLoader::~PluginLoader()
-{
-       ::dlclose(m_handle);
-}
-
-} // namespace AuthPasswd
diff --git a/src/server/service/plugin-manager.cpp b/src/server/service/plugin-manager.cpp
deleted file mode 100644 (file)
index 1a50fc5..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *  Copyright (c) 2018 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        plugin-manager.cpp
- * @author      Sangwan Kwon(sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Implementation of plugin manager.
- */
-#include <plugin-manager.h>
-
-#include <fstream>
-
-namespace AuthPasswd {
-
-bool PluginManager::isSupport(BackendType type) const noexcept
-{
-       if (std::ifstream(this->getPluginPath(type)))
-               return true;
-       else
-               return false;
-}
-
-void PluginManager::setBackend(BackendType type)
-{
-       m_loader = std::make_shared<PluginLoader>(this->getPluginPath(type));
-}
-
-std::string PluginManager::getPluginPath(BackendType type) const noexcept
-{
-       if (type == BackendType::SW)
-               return PLUGIN_SW_BACKEND_PATH;
-       else
-               return PLUGIN_TZ_BACKEND_PATH;
-}
-
-} //namespace AuthPasswd
diff --git a/src/server/service/policy-file-buffer.cpp b/src/server/service/policy-file-buffer.cpp
new file mode 100644 (file)
index 0000000..37646e2
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ *  Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Jooseong Lee <jooseong.lee@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.cpp
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of PasswordFileBuffer, used for serialization in PasswordFile class
+ */
+
+#include <policy-file-buffer.h>
+
+#include <fstream>
+#include <iterator>
+
+#include <dpl/log/log.h>
+#include <dpl/fstream_accessors.h>
+
+#include <auth-passwd-error.h>
+#include <password-exception.h>
+
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+namespace AuthPasswd {
+PolicyFileBuffer::PolicyFileBuffer(): m_bufferReadBytes(0) {}
+
+void PolicyFileBuffer::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);
+       }
+
+       void *ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
+
+       if (ret == 0) {
+               LogError("Failed to read " << num << " bytes.");
+               Throw(PasswordException::MemoryError);
+       }
+
+       m_bufferReadBytes += num;
+}
+
+void PolicyFileBuffer::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 PolicyFileBuffer::Save(const std::string &path)
+{
+       std::ofstream file(path, std::ofstream::trunc);
+
+       if (!file.good()) {
+               LogError("Error while opening file stream. file=" << path);
+               Throw(PasswordException::FStreamOpenError);
+       }
+
+       file.write(m_buffer.data(), m_buffer.size());
+
+       if (!file) {
+               LogError("Failed to write data. file=" << path);
+               Throw(PasswordException::FStreamWriteError);
+       }
+
+       file.flush();
+       if (::fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(file)) != 0)
+               LogError("Failed to synchronize a file's state. file=" << path);
+       file.close();
+}
+
+void PolicyFileBuffer::Load(const std::string &path)
+{
+       std::ifstream file(path, std::ifstream::binary);
+
+       if (!file.good()) {
+               LogError("Error while opening file stream. file=" << path);
+               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() << ", file=" << path);
+               Throw(PasswordException::FStreamReadError);
+       }
+}
+
+} //namespace AuthPasswd
index f596f3ca358c4dedcead9dc1c3ffd342ca831599..0a5d5485084f822de2b7eb515205d208f558c13e 100644 (file)
@@ -41,7 +41,7 @@
 
 #include <error-description.h>
 #include <password-exception.h>
-#include <generic-backend/password-file-buffer.h>
+#include <policy-file-buffer.h>
 
 namespace {
 const std::string POLICY_FILE = "policy";
@@ -148,7 +148,7 @@ std::string PolicyFile::getOldFilePath(const std::string &dir, unsigned int user
 
 void PolicyFile::writeMemoryToFile() const
 {
-       PasswordFileBuffer policyBuffer;
+       PolicyFileBuffer policyBuffer;
        LogSecureDebug("User: " << m_user << " Policy: " << m_policy.info());
        // serialize policy attributes
        Serialization::Serialize(policyBuffer, CURRENT_FILE_VERSION);
@@ -166,7 +166,7 @@ void PolicyFile::writeMemoryToFile() const
 
 void PolicyFile::loadMemoryFromFile()
 {
-       PasswordFileBuffer policyBuffer;
+       PolicyFileBuffer policyBuffer;
        bool loadedFromOld = false;
        std::string policyFile = getFilePath(RW_DATA_DIR, m_user, m_passwordType, POLICY_FILE);
        if (!fileExists(policyFile)) {
index c73805e7bfe9aafa7a31f308ea12d6f9276fe1f9..f99d197cf2b38e5ae10fd267fac06c22245c63cf 100644 (file)
@@ -21,11 +21,7 @@ SET(TEST_SRCS main.cpp
                          test-client.cpp
                          test-admin.cpp
                          test-pin.cpp
-                         test-pattern.cpp
-                         test-sw-backend.cpp
-
-                         ${SERVER_PATH}/service/plugin-loader.cpp
-                         ${SERVER_PATH}/service/plugin-manager.cpp)
+                         test-pattern.cpp)
 
 PKG_CHECK_MODULES(${TARGET_TEST}_DEP REQUIRED klay security-manager libtzplatform-config)
 
@@ -35,15 +31,13 @@ INCLUDE_DIRECTORIES(SYSTEM ${${TARGET_TEST}_DEP_INCLUDE_DIRS}
                                                   ${SERVER_PATH}/service/include
                                                   ${DPL_PATH}/core/include
                                                   ${DPL_PATH}/log/include
-                                                  ${COMMON_PATH}/include
-                                                  ${PLUGIN_PATH})
+                                                  ${COMMON_PATH}/include)
 
 ADD_EXECUTABLE(${TARGET_TEST} ${TEST_SRCS})
 
 TARGET_LINK_LIBRARIES(${TARGET_TEST} ${${TARGET_TEST}_DEP_LIBRARIES}
                                                                         ${TARGET_CLIENT}
                                                                         ${TARGET_CLIENT_ADMIN}
-                                                                        ${TARGET_SW_BACKEND}
                                                                         -ldl)
 
 SET_TARGET_PROPERTIES(${TARGET_TEST} PROPERTIES COMPILE_FLAGS "-fPIE")
diff --git a/tests/test-sw-backend.cpp b/tests/test-sw-backend.cpp
deleted file mode 100644 (file)
index 158473b..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *  Copyright (c) 2018 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        test-sw-backend.cpp
- * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Testcases of PasswordFile(SW-Backend)
- */
-
-#include <klay/testbench.h>
-
-#include <plugin-manager.h>
-
-#include <generic-backend/ipassword-file.h>
-#include <sw-backend/password-file.h>
-
-using namespace AuthPasswd;
-
-TESTCASE(T00500_is_support)
-{
-       PluginManager pm;
-
-       TEST_EXPECT(true, pm.isSupport(BackendType::SW));
-       TEST_EXPECT(false, pm.isSupport(BackendType::TZ));
-}
-
-TESTCASE(T00501_bind_backend)
-{
-       PluginManager pm;
-       pm.setBackend(BackendType::SW);
-
-       PasswordFileFactory factory = nullptr;
-       pm.loadFactory("PasswordFileFactory", factory);
-
-       TEST_EXPECT(true, factory != nullptr);
-
-       std::shared_ptr<IPasswordFile> passwdFile((*factory)(5001));
-       TEST_EXPECT(true, passwdFile != nullptr);
-}
index 0aaf190e8073f895873553abbc9e8edb1bcbb411..a63ead188b6b5c66f78b17fe1ce708b63502facf 100644 (file)
@@ -80,7 +80,6 @@ int check_passwd(password_type type, const char *token)
                        &policy.current_attempts,
                        &policy.max_attempts,
                        &policy.valid_secs);
-
        return ret;
 }