Rework get_base_path for buffer overflows 76/161676/6
authorIgor Kotrasinski <i.kotrasinsk@partner.samsung.com>
Fri, 24 Nov 2017 14:23:19 +0000 (15:23 +0100)
committerIgor Kotrasinski <i.kotrasinsk@partner.samsung.com>
Tue, 28 Nov 2017 14:06:57 +0000 (15:06 +0100)
Change-Id: I4c513d32eb22700d2c835d6e12f35234b3ffce0f
Signed-off-by: Igor Kotrasinski <i.kotrasinsk@partner.samsung.com>
ssflib/dep/swdss/include/file_op.h
ssflib/dep/swdss/source/file_op.cpp

index 71df044..8779f55 100644 (file)
@@ -110,9 +110,11 @@ public:
         *
         * Get base path of specific file.
         * @param[in] filename Full file path.
-        * @return base path
+        * @param[out] base_path Base path.
+        * @param[in] maxlen Size of base_path buffer.
+        * @return 0 if base path fit in base_path buffer, -1 if it did not.
         */
-       static void get_base_path(const char* filename, char* base_path);
+       static int get_base_path(const char* filename, char* base_path, int maxlen);
 };
 
 #endif
index 9b248d1..4024b2f 100644 (file)
@@ -50,7 +50,8 @@ int file_op::write_file(const char* filename, unsigned char* buffer,
 
        // create folder if not exist.
        char base_path[MAX_FILENAME_LEN] = {0};
-       get_base_path(filename, base_path);
+       if (get_base_path(filename, base_path, MAX_FILENAME_LEN))
+               return SS_RET_INTERNAL_ERROR;
        SLOGI("base_path %s.", base_path);
        if (!is_folder_exists(base_path)) {
                if (0 != create_folder(base_path)) {
@@ -176,7 +177,8 @@ int file_op::create_folder(const char* folder) {
        SLOGI("[%s][%d] START", __FUNCTION__, __LINE__);
 
        char base_p[MAX_FILENAME_LEN] = {0};
-       get_base_path(folder, base_p);
+       if (get_base_path(folder, base_p, MAX_FILENAME_LEN))
+               return SS_RET_INTERNAL_ERROR;
        if (!is_folder_exists(base_p)) {
                if (0 != create_folder(base_p)) {
                        SLOGE("Failed to create folder %s.", base_p);
@@ -226,13 +228,19 @@ bool file_op::is_file_exists(const char* file) {
        return (res != -1);
 }
 
-void file_op::get_base_path(const char* filename, char* base_path) {
-       for (int i = strlen(filename) - 1; i >= 0; --i) {
-               if ('/' == filename[i]) {
-                       memcpy(base_path, filename, i);
-                       base_path[i] = '\0';
+int file_op::get_base_path(const char* filename, char* base_path, int maxlen) {
+       int slashpos;
+       for (slashpos = strlen(filename) - 1; slashpos >= 0; --slashpos) {
+               if ('/' == filename[slashpos])
                        break;
-               }
        }
+       if (slashpos < 0)
+               return 0;
+       if (slashpos >= maxlen)
+               return -1;
+
+       memcpy(base_path, filename, slashpos);
+       base_path[slashpos] = '\0';
+       return 0;
 }