func_name
stringlengths
2
53
func_src_before
stringlengths
63
114k
func_src_after
stringlengths
86
114k
line_changes
dict
char_changes
dict
commit_link
stringlengths
66
117
file_name
stringlengths
5
72
vul_type
stringclasses
9 values
dd_get_item_size
long dd_get_item_size(struct dump_dir *dd, const char *name) { long size = -1; char *iname = concat_path_file(dd->dd_dirname, name); struct stat statbuf; if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) size = statbuf.st_size; else { if (errno == ENOENT) size = 0; else perror_msg("Can't get size of file '%s'", iname); } free(iname); return size; }
long dd_get_item_size(struct dump_dir *dd, const char *name) { if (!str_is_correct_filename(name)) error_msg_and_die("Cannot get item size. '%s' is not a valid file name", name); long size = -1; char *iname = concat_path_file(dd->dd_dirname, name); struct stat statbuf; if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) size = statbuf.st_size; else { if (errno == ENOENT) size = 0; else perror_msg("Can't get size of file '%s'", iname); } free(iname); return size; }
{ "deleted": [], "added": [ { "line_no": 3, "char_start": 63, "char_end": 103, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 4, "char_start": 103, "char_end": 191, "line": " error_msg_and_die(\"Cannot get item size. '%s' is not a valid file name\", name);\n" }, { "line_no": 5, "char_start": 191, "char_end": 192, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 67, "char_end": 196, "chars": "if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot get item size. '%s' is not a valid file name\", name);\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
zmi_page_request
def zmi_page_request(self, *args, **kwargs): request = self.REQUEST RESPONSE = request.RESPONSE SESSION = request.SESSION self._zmi_page_request() RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822()) RESPONSE.setHeader('Cache-Control', 'no-cache') RESPONSE.setHeader('Pragma', 'no-cache') RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET']) if not request.get( 'preview'): request.set( 'preview','preview') langs = self.getLanguages(request) if request.get('lang') not in langs: request.set('lang',langs[0]) if request.get('manage_lang') not in self.getLocale().get_manage_langs(): request.set('manage_lang',self.get_manage_lang()) if not request.get('manage_tabs_message'): request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message','')) # manage_system if request.form.has_key('zmi-manage-system'): request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system'))) # avoid declarative urls physical_path = self.getPhysicalPath() path_to_handle = request['URL0'][len(request['BASE0']):].split('/') path = path_to_handle[:-1] if len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0: for i in range(len(path)): if path[:-(i+1)] != physical_path[:-(i+1)]: path[:-(i+1)] = physical_path[:-(i+1)] new_path = path+[path_to_handle[-1]] if path_to_handle != new_path: request.RESPONSE.redirect('/'.join(new_path))
def zmi_page_request(self, *args, **kwargs): request = self.REQUEST RESPONSE = request.RESPONSE SESSION = request.SESSION self._zmi_page_request() RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822()) RESPONSE.setHeader('Cache-Control', 'no-cache') RESPONSE.setHeader('Pragma', 'no-cache') RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET']) if not request.get( 'preview'): request.set( 'preview','preview') langs = self.getLanguages(request) if request.get('lang') not in langs: request.set('lang',langs[0]) if request.get('manage_lang') not in self.getLocale().get_manage_langs(): request.set('manage_lang',self.get_manage_lang()) if not request.get('manage_tabs_message'): request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message','')) # manage_system if request.form.has_key('zmi-manage-system'): request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system'))) # avoid declarative urls physical_path = self.getPhysicalPath() path_to_handle = request['URL0'][len(request['BASE0']):].split('/') path = path_to_handle[:-1] if self.getDocumentElement().id in path and len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0: for i in range(len(path)): if path[:-(i+1)] != physical_path[:-(i+1)]: path[:-(i+1)] = physical_path[:-(i+1)] new_path = path+[path_to_handle[-1]] if path_to_handle != new_path: request.RESPONSE.redirect('/'.join(new_path))
{ "deleted": [ { "line_no": 26, "char_start": 1313, "char_end": 1395, "line": " if len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n" } ], "added": [ { "line_no": 26, "char_start": 1313, "char_end": 1436, "line": " if self.getDocumentElement().id in path and len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n" } ] }
{ "deleted": [], "added": [ { "char_start": 1322, "char_end": 1363, "chars": "self.getDocumentElement().id in path and " } ] }
github.com/zms-publishing/zms4/commit/3f28620d475220dfdb06f79787158ac50727c61a
ZMSItem.py
cwe-022
nntp_hcache_namer
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { return snprintf(dest, destlen, "%s.hcache", path); }
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { int count = snprintf(dest, destlen, "%s.hcache", path); /* Strip out any directories in the path */ char *first = strchr(dest, '/'); char *last = strrchr(dest, '/'); if (first && last && (last > first)) { memmove(first, last, strlen(last) + 1); count -= (last - first); } return count; }
{ "deleted": [ { "line_no": 3, "char_start": 77, "char_end": 130, "line": " return snprintf(dest, destlen, \"%s.hcache\", path);\n" } ], "added": [ { "line_no": 3, "char_start": 77, "char_end": 135, "line": " int count = snprintf(dest, destlen, \"%s.hcache\", path);\n" }, { "line_no": 4, "char_start": 135, "char_end": 136, "line": "\n" }, { "line_no": 5, "char_start": 136, "char_end": 182, "line": " /* Strip out any directories in the path */\n" }, { "line_no": 6, "char_start": 182, "char_end": 217, "line": " char *first = strchr(dest, '/');\n" }, { "line_no": 7, "char_start": 217, "char_end": 252, "line": " char *last = strrchr(dest, '/');\n" }, { "line_no": 8, "char_start": 252, "char_end": 291, "line": " if (first && last && (last > first))\n" }, { "line_no": 9, "char_start": 291, "char_end": 295, "line": " {\n" }, { "line_no": 10, "char_start": 295, "char_end": 339, "line": " memmove(first, last, strlen(last) + 1);\n" }, { "line_no": 11, "char_start": 339, "char_end": 368, "line": " count -= (last - first);\n" }, { "line_no": 12, "char_start": 368, "char_end": 372, "line": " }\n" }, { "line_no": 13, "char_start": 372, "char_end": 373, "line": "\n" }, { "line_no": 14, "char_start": 373, "char_end": 389, "line": " return count;\n" } ] }
{ "deleted": [ { "char_start": 79, "char_end": 81, "chars": "re" }, { "char_start": 83, "char_end": 84, "chars": "r" } ], "added": [ { "char_start": 79, "char_end": 81, "chars": "in" }, { "char_start": 82, "char_end": 85, "chars": " co" }, { "char_start": 87, "char_end": 90, "chars": "t =" }, { "char_start": 133, "char_end": 387, "chars": ";\n\n /* Strip out any directories in the path */\n char *first = strchr(dest, '/');\n char *last = strrchr(dest, '/');\n if (first && last && (last > first))\n {\n memmove(first, last, strlen(last) + 1);\n count -= (last - first);\n }\n\n return count" } ] }
github.com/neomutt/neomutt/commit/9bfab35522301794483f8f9ed60820bdec9be59e
newsrc.c
cwe-022
TarFileReader::extract
std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW("path cannot be empty"); if (!hasMore()) THROW("No more tar files"); string path = _path; if (SystemUtilities::isDirectory(path)) path += "/" + getFilename(); LOG_DEBUG(5, "Extracting: " << path); return extract(*SystemUtilities::oopen(path)); }
std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW("path cannot be empty"); if (!hasMore()) THROW("No more tar files"); string path = _path; if (SystemUtilities::isDirectory(path)) { path += "/" + getFilename(); // Check that path is under the target directory string a = SystemUtilities::getCanonicalPath(_path); string b = SystemUtilities::getCanonicalPath(path); if (!String::startsWith(b, a)) THROW("Tar path points outside of the extraction directory: " << path); } LOG_DEBUG(5, "Extracting: " << path); switch (getType()) { case NORMAL_FILE: case CONTIGUOUS_FILE: return extract(*SystemUtilities::oopen(path)); case DIRECTORY: SystemUtilities::ensureDirectory(path); break; default: THROW("Unsupported tar file type " << getType()); } return getFilename(); }
{ "deleted": [ { "line_no": 6, "char_start": 180, "char_end": 251, "line": " if (SystemUtilities::isDirectory(path)) path += \"/\" + getFilename();\n" }, { "line_no": 10, "char_start": 293, "char_end": 342, "line": " return extract(*SystemUtilities::oopen(path));\n" } ], "added": [ { "line_no": 6, "char_start": 180, "char_end": 224, "line": " if (SystemUtilities::isDirectory(path)) {\n" }, { "line_no": 7, "char_start": 224, "char_end": 257, "line": " path += \"/\" + getFilename();\n" }, { "line_no": 8, "char_start": 257, "char_end": 258, "line": "\n" }, { "line_no": 10, "char_start": 311, "char_end": 368, "line": " string a = SystemUtilities::getCanonicalPath(_path);\n" }, { "line_no": 11, "char_start": 368, "char_end": 424, "line": " string b = SystemUtilities::getCanonicalPath(path);\n" }, { "line_no": 12, "char_start": 424, "char_end": 459, "line": " if (!String::startsWith(b, a))\n" }, { "line_no": 13, "char_start": 459, "char_end": 537, "line": " THROW(\"Tar path points outside of the extraction directory: \" << path);\n" }, { "line_no": 14, "char_start": 537, "char_end": 541, "line": " }\n" }, { "line_no": 18, "char_start": 583, "char_end": 606, "line": " switch (getType()) {\n" }, { "line_no": 19, "char_start": 606, "char_end": 648, "line": " case NORMAL_FILE: case CONTIGUOUS_FILE:\n" }, { "line_no": 20, "char_start": 648, "char_end": 699, "line": " return extract(*SystemUtilities::oopen(path));\n" }, { "line_no": 21, "char_start": 699, "char_end": 764, "line": " case DIRECTORY: SystemUtilities::ensureDirectory(path); break;\n" }, { "line_no": 22, "char_start": 764, "char_end": 825, "line": " default: THROW(\"Unsupported tar file type \" << getType());\n" }, { "line_no": 23, "char_start": 825, "char_end": 829, "line": " }\n" }, { "line_no": 24, "char_start": 829, "char_end": 830, "line": "\n" }, { "line_no": 25, "char_start": 830, "char_end": 854, "line": " return getFilename();\n" } ] }
{ "deleted": [], "added": [ { "char_start": 222, "char_end": 228, "chars": "{\n " }, { "char_start": 260, "char_end": 544, "chars": " // Check that path is under the target directory\n string a = SystemUtilities::getCanonicalPath(_path);\n string b = SystemUtilities::getCanonicalPath(path);\n if (!String::startsWith(b, a))\n THROW(\"Tar path points outside of the extraction directory: \" << path);\n }\n\n " }, { "char_start": 585, "char_end": 652, "chars": "switch (getType()) {\n case NORMAL_FILE: case CONTIGUOUS_FILE:\n " }, { "char_start": 696, "char_end": 851, "chars": ");\n case DIRECTORY: SystemUtilities::ensureDirectory(path); break;\n default: THROW(\"Unsupported tar file type \" << getType());\n }\n\n return getFilename(" } ] }
github.com/CauldronDevelopmentLLC/cbang/commit/1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
src/cbang/tar/TarFileReader.cpp
cwe-022
handle_method_call
static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }
static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (!allowed_problem_dir(problem_id)) { return_InvalidProblemDir_error(invocation, problem_id); return; } if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); if (!allowed_problem_dir(problem_id)) { return_InvalidProblemDir_error(invocation, problem_id); return; } if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name", element); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }
{ "deleted": [], "added": [ { "line_no": 259, "char_start": 9073, "char_end": 9119, "line": " if (!allowed_problem_dir(problem_id))\n" }, { "line_no": 260, "char_start": 9119, "char_end": 9129, "line": " {\n" }, { "line_no": 261, "char_start": 9129, "char_end": 9197, "line": " return_InvalidProblemDir_error(invocation, problem_id);\n" }, { "line_no": 262, "char_start": 9197, "char_end": 9217, "line": " return;\n" }, { "line_no": 263, "char_start": 9217, "char_end": 9227, "line": " }\n" }, { "line_no": 264, "char_start": 9227, "char_end": 9228, "line": "\n" }, { "line_no": 324, "char_start": 11714, "char_end": 11760, "line": " if (!allowed_problem_dir(problem_id))\n" }, { "line_no": 325, "char_start": 11760, "char_end": 11770, "line": " {\n" }, { "line_no": 326, "char_start": 11770, "char_end": 11838, "line": " return_InvalidProblemDir_error(invocation, problem_id);\n" }, { "line_no": 327, "char_start": 11838, "char_end": 11858, "line": " return;\n" }, { "line_no": 328, "char_start": 11858, "char_end": 11868, "line": " }\n" }, { "line_no": 329, "char_start": 11868, "char_end": 11869, "line": "\n" }, { "line_no": 447, "char_start": 16070, "char_end": 16117, "line": " if (!str_is_correct_filename(element))\n" }, { "line_no": 448, "char_start": 16117, "char_end": 16127, "line": " {\n" }, { "line_no": 449, "char_start": 16127, "char_end": 16196, "line": " log_notice(\"'%s' is not a valid element name\", element);\n" }, { "line_no": 450, "char_start": 16196, "char_end": 16281, "line": " char *error = xasprintf(_(\"'%s' is not a valid element name\"), element);\n" }, { "line_no": 451, "char_start": 16281, "char_end": 16348, "line": " g_dbus_method_invocation_return_dbus_error(invocation,\n" }, { "line_no": 452, "char_start": 16348, "char_end": 16437, "line": " \"org.freedesktop.problems.InvalidElement\",\n" }, { "line_no": 453, "char_start": 16437, "char_end": 16491, "line": " error);\n" }, { "line_no": 454, "char_start": 16491, "char_end": 16492, "line": "\n" }, { "line_no": 455, "char_start": 16492, "char_end": 16517, "line": " free(error);\n" }, { "line_no": 456, "char_start": 16517, "char_end": 16537, "line": " return;\n" }, { "line_no": 457, "char_start": 16537, "char_end": 16547, "line": " }\n" }, { "line_no": 458, "char_start": 16547, "char_end": 16548, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 9086, "char_end": 9241, "chars": "allowed_problem_dir(problem_id))\n {\n return_InvalidProblemDir_error(invocation, problem_id);\n return;\n }\n\n if (!" }, { "char_start": 11712, "char_end": 11867, "chars": "\n\n if (!allowed_problem_dir(problem_id))\n {\n return_InvalidProblemDir_error(invocation, problem_id);\n return;\n }" }, { "char_start": 16068, "char_end": 16546, "chars": "\n\n if (!str_is_correct_filename(element))\n {\n log_notice(\"'%s' is not a valid element name\", element);\n char *error = xasprintf(_(\"'%s' is not a valid element name\"), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.InvalidElement\",\n error);\n\n free(error);\n return;\n }" } ] }
github.com/abrt/abrt/commit/7a47f57975be0d285a2f20758e4572dca6d9cdd3
src/dbus/abrt-dbus.c
cwe-022
_inject_file_into_fs
def _inject_file_into_fs(fs, path, contents): absolute_path = os.path.join(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) utils.execute('tee', absolute_path, process_input=contents, run_as_root=True)
def _inject_file_into_fs(fs, path, contents, append=False): absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) args = [] if append: args.append('-a') args.append(absolute_path) kwargs = dict(process_input=contents, run_as_root=True) utils.execute('tee', *args, **kwargs)
{ "deleted": [ { "line_no": 5, "char_start": 212, "char_end": 276, "line": " utils.execute('tee', absolute_path, process_input=contents,\n" }, { "line_no": 6, "char_start": 276, "char_end": 303, "line": " run_as_root=True)\n" } ], "added": [ { "line_no": 1, "char_start": 0, "char_end": 60, "line": "def _inject_file_into_fs(fs, path, contents, append=False):\n" }, { "line_no": 2, "char_start": 60, "char_end": 133, "line": " absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/'))\n" }, { "line_no": 3, "char_start": 133, "char_end": 134, "line": "\n" }, { "line_no": 6, "char_start": 245, "char_end": 246, "line": "\n" }, { "line_no": 7, "char_start": 246, "char_end": 260, "line": " args = []\n" }, { "line_no": 8, "char_start": 260, "char_end": 275, "line": " if append:\n" }, { "line_no": 9, "char_start": 275, "char_end": 301, "line": " args.append('-a')\n" }, { "line_no": 10, "char_start": 301, "char_end": 332, "line": " args.append(absolute_path)\n" }, { "line_no": 11, "char_start": 332, "char_end": 333, "line": "\n" }, { "line_no": 12, "char_start": 333, "char_end": 393, "line": " kwargs = dict(process_input=contents, run_as_root=True)\n" }, { "line_no": 13, "char_start": 393, "char_end": 394, "line": "\n" }, { "line_no": 14, "char_start": 394, "char_end": 435, "line": " utils.execute('tee', *args, **kwargs)\n" } ] }
{ "deleted": [ { "char_start": 67, "char_end": 69, "chars": "s." }, { "char_start": 73, "char_end": 76, "chars": ".jo" }, { "char_start": 216, "char_end": 218, "chars": "ut" }, { "char_start": 219, "char_end": 220, "chars": "l" }, { "char_start": 222, "char_end": 224, "chars": "ex" }, { "char_start": 225, "char_end": 229, "chars": "cute" }, { "char_start": 231, "char_end": 234, "chars": "tee" }, { "char_start": 235, "char_end": 236, "chars": "," }, { "char_start": 250, "char_end": 251, "chars": "," }, { "char_start": 275, "char_end": 285, "chars": "\n " } ], "added": [ { "char_start": 43, "char_end": 57, "chars": ", append=False" }, { "char_start": 80, "char_end": 82, "chars": "_j" }, { "char_start": 83, "char_end": 96, "chars": "in_and_check_" }, { "char_start": 100, "char_end": 105, "chars": "_with" }, { "char_start": 107, "char_end": 110, "chars": "_fs" }, { "char_start": 133, "char_end": 134, "chars": "\n" }, { "char_start": 245, "char_end": 246, "chars": "\n" }, { "char_start": 250, "char_end": 264, "chars": "args = []\n " }, { "char_start": 265, "char_end": 286, "chars": "f append:\n arg" }, { "char_start": 288, "char_end": 291, "chars": "app" }, { "char_start": 292, "char_end": 294, "chars": "nd" }, { "char_start": 296, "char_end": 298, "chars": "-a" }, { "char_start": 299, "char_end": 304, "chars": ")\n " }, { "char_start": 306, "char_end": 318, "chars": "rgs.append(a" }, { "char_start": 330, "char_end": 333, "chars": ")\n\n" }, { "char_start": 334, "char_end": 351, "chars": " kwargs = dict(" }, { "char_start": 392, "char_end": 435, "chars": "\n\n utils.execute('tee', *args, **kwargs)" } ] }
github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7
nova/virt/disk/api.py
cwe-022
set_interface_var
set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, "w"); if (!fp) { if (name) flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno)); return -1; } fprintf(fp, "%u", val); fclose(fp); return 0; }
set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; /* No path traversal */ if (strstr(name, "..") || strchr(name, '/')) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, "w"); if (!fp) { if (name) flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno)); return -1; } fprintf(fp, "%u", val); fclose(fp); return 0; }
{ "deleted": [], "added": [ { "line_no": 10, "char_start": 239, "char_end": 264, "line": "\t/* No path traversal */\n" }, { "line_no": 11, "char_start": 264, "char_end": 310, "line": "\tif (strstr(name, \"..\") || strchr(name, '/'))\n" }, { "line_no": 12, "char_start": 310, "char_end": 323, "line": "\t\treturn -1;\n" }, { "line_no": 13, "char_start": 323, "char_end": 324, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 240, "char_end": 325, "chars": "/* No path traversal */\n\tif (strstr(name, \"..\") || strchr(name, '/'))\n\t\treturn -1;\n\n\t" } ] }
github.com/reubenhwk/radvd/commit/92e22ca23e52066da2258df8c76a2dca8a428bcc
device-linux.c
cwe-022
cut
def cut(self, key): try: self.etcd.delete(os.path.join(self.namespace, key)) except etcd.EtcdKeyNotFound: return False except etcd.EtcdException as err: log_error("Error removing key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to cut key') return True
def cut(self, key): try: self.etcd.delete(self._absolute_key(key)) except etcd.EtcdKeyNotFound: return False except etcd.EtcdException as err: log_error("Error removing key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to cut key') return True
{ "deleted": [ { "line_no": 3, "char_start": 37, "char_end": 101, "line": " self.etcd.delete(os.path.join(self.namespace, key))\n" } ], "added": [ { "line_no": 3, "char_start": 37, "char_end": 91, "line": " self.etcd.delete(self._absolute_key(key))\n" } ] }
{ "deleted": [ { "char_start": 66, "char_end": 79, "chars": "os.path.join(" }, { "char_start": 84, "char_end": 85, "chars": "n" }, { "char_start": 86, "char_end": 88, "chars": "me" }, { "char_start": 89, "char_end": 92, "chars": "pac" }, { "char_start": 93, "char_end": 95, "chars": ", " } ], "added": [ { "char_start": 71, "char_end": 72, "chars": "_" }, { "char_start": 73, "char_end": 79, "chars": "bsolut" }, { "char_start": 80, "char_end": 82, "chars": "_k" }, { "char_start": 83, "char_end": 85, "chars": "y(" } ] }
github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4
custodia/store/etcdstore.py
cwe-022
wiki_handle_http_request
wiki_handle_http_request(HttpRequest *req) { HttpResponse *res = http_response_new(req); char *page = http_request_get_path_info(req); char *command = http_request_get_query_string(req); char *wikitext = ""; util_dehttpize(page); /* remove any encoding on the requested page name. */ if (!strcmp(page, "/")) { if (access("WikiHome", R_OK) != 0) wiki_redirect(res, "/WikiHome?create"); page = "/WikiHome"; } if (!strcmp(page, "/styles.css")) { /* Return CSS page */ http_response_set_content_type(res, "text/css"); http_response_printf(res, "%s", CssData); http_response_send(res); exit(0); } if (!strcmp(page, "/favicon.ico")) { /* Return favicon */ http_response_set_content_type(res, "image/ico"); http_response_set_data(res, FaviconData, FaviconDataLen); http_response_send(res); exit(0); } page = page + 1; /* skip slash */ if (!strncmp(page, "api/", 4)) { char *p; page += 4; for (p=page; *p != '\0'; p++) if (*p=='?') { *p ='\0'; break; } wiki_handle_rest_call(req, res, page); exit(0); } /* A little safety. issue a malformed request for any paths, * There shouldn't need to be any.. */ if (strchr(page, '/')) { http_response_set_status(res, 404, "Not Found"); http_response_printf(res, "<html><body>404 Not Found</body></html>\n"); http_response_send(res); exit(0); } if (!strcmp(page, "Changes")) { wiki_show_changes_page(res); } else if (!strcmp(page, "ChangesRss")) { wiki_show_changes_page_rss(res); } else if (!strcmp(page, "Search")) { wiki_show_search_results_page(res, http_request_param_get(req, "expr")); } else if (!strcmp(page, "Create")) { if ( (wikitext = http_request_param_get(req, "title")) != NULL) { /* create page and redirect */ wiki_redirect(res, http_request_param_get(req, "title")); } else { /* show create page form */ wiki_show_create_page(res); } } else { /* TODO: dont blindly write wikitext data to disk */ if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL) { file_write(page, wikitext); } if (access(page, R_OK) == 0) /* page exists */ { wikitext = file_read(page); if (!strcmp(command, "edit")) { /* print edit page */ wiki_show_edit_page(res, wikitext, page); } else { wiki_show_page(res, wikitext, page); } } else { if (!strcmp(command, "create")) { wiki_show_edit_page(res, NULL, page); } else { char buf[1024]; snprintf(buf, 1024, "%s?create", page); wiki_redirect(res, buf); } } } }
wiki_handle_http_request(HttpRequest *req) { HttpResponse *res = http_response_new(req); char *page = http_request_get_path_info(req); char *command = http_request_get_query_string(req); char *wikitext = ""; util_dehttpize(page); /* remove any encoding on the requested page name. */ if (!strcmp(page, "/")) { if (access("WikiHome", R_OK) != 0) wiki_redirect(res, "/WikiHome?create"); page = "/WikiHome"; } if (!strcmp(page, "/styles.css")) { /* Return CSS page */ http_response_set_content_type(res, "text/css"); http_response_printf(res, "%s", CssData); http_response_send(res); exit(0); } if (!strcmp(page, "/favicon.ico")) { /* Return favicon */ http_response_set_content_type(res, "image/ico"); http_response_set_data(res, FaviconData, FaviconDataLen); http_response_send(res); exit(0); } page = page + 1; /* skip slash */ if (!strncmp(page, "api/", 4)) { char *p; page += 4; for (p=page; *p != '\0'; p++) if (*p=='?') { *p ='\0'; break; } wiki_handle_rest_call(req, res, page); exit(0); } /* A little safety. issue a malformed request for any paths, * There shouldn't need to be any.. */ if (!page_name_is_good(page)) { http_response_set_status(res, 404, "Not Found"); http_response_printf(res, "<html><body>404 Not Found</body></html>\n"); http_response_send(res); exit(0); } if (!strcmp(page, "Changes")) { wiki_show_changes_page(res); } else if (!strcmp(page, "ChangesRss")) { wiki_show_changes_page_rss(res); } else if (!strcmp(page, "Search")) { wiki_show_search_results_page(res, http_request_param_get(req, "expr")); } else if (!strcmp(page, "Create")) { if ( (wikitext = http_request_param_get(req, "title")) != NULL) { /* create page and redirect */ wiki_redirect(res, http_request_param_get(req, "title")); } else { /* show create page form */ wiki_show_create_page(res); } } else { /* TODO: dont blindly write wikitext data to disk */ if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL) { file_write(page, wikitext); } if (access(page, R_OK) == 0) /* page exists */ { wikitext = file_read(page); if (!strcmp(command, "edit")) { /* print edit page */ wiki_show_edit_page(res, wikitext, page); } else { wiki_show_page(res, wikitext, page); } } else { if (!strcmp(command, "create")) { wiki_show_edit_page(res, NULL, page); } else { char buf[1024]; snprintf(buf, 1024, "%s?create", page); wiki_redirect(res, buf); } } } }
{ "deleted": [ { "line_no": 54, "char_start": 1350, "char_end": 1375, "line": " if (strchr(page, '/'))\n" } ], "added": [ { "line_no": 54, "char_start": 1350, "char_end": 1382, "line": " if (!page_name_is_good(page))\n" } ] }
{ "deleted": [ { "char_start": 1357, "char_end": 1362, "chars": "trchr" }, { "char_start": 1367, "char_end": 1372, "chars": ", '/'" } ], "added": [ { "char_start": 1356, "char_end": 1368, "chars": "!page_name_i" }, { "char_start": 1369, "char_end": 1374, "chars": "_good" } ] }
github.com/yarolig/didiwiki/commit/5e5c796617e1712905dc5462b94bd5e6c08d15ea
src/wiki.c
cwe-022
candidate_paths_for_url
def candidate_paths_for_url(self, url): for root, prefix in self.directories: if url.startswith(prefix): yield os.path.join(root, url[len(prefix):])
def candidate_paths_for_url(self, url): for root, prefix in self.directories: if url.startswith(prefix): path = os.path.join(root, url[len(prefix):]) if os.path.commonprefix((root, path)) == root: yield path
{ "deleted": [ { "line_no": 4, "char_start": 129, "char_end": 188, "line": " yield os.path.join(root, url[len(prefix):])\n" } ], "added": [ { "line_no": 4, "char_start": 129, "char_end": 190, "line": " path = os.path.join(root, url[len(prefix):])\n" }, { "line_no": 5, "char_start": 190, "char_end": 253, "line": " if os.path.commonprefix((root, path)) == root:\n" }, { "line_no": 6, "char_start": 253, "char_end": 283, "line": " yield path\n" } ] }
{ "deleted": [ { "char_start": 145, "char_end": 150, "chars": "yield" } ], "added": [ { "char_start": 145, "char_end": 151, "chars": "path =" }, { "char_start": 189, "char_end": 283, "chars": "\n if os.path.commonprefix((root, path)) == root:\n yield path" } ] }
github.com/evansd/whitenoise/commit/4d8a3ab1e97d7ddb18b3fa8b4909c92bad5529c6
whitenoise/base.py
cwe-022
updateKey
def updateKey(client): """Updates the contents of a key that already exists in our system. Returns an error if the specified key doesn't exist for the specified user. """ global NOT_FOUND global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) # Use 'w' flag to replace existing key file with the new key data if os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])): with open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f: f.write(token_data['key']) else: raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['name']) return 'Key successfully updated', CREATED
def updateKey(client): """Updates the contents of a key that already exists in our system. Returns an error if the specified key doesn't exist for the specified user. """ global NOT_FOUND global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) validateKeyName(token_data['name']) # Use 'w' flag to replace existing key file with the new key data if os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])): with open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f: f.write(token_data['key']) else: raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['name']) return 'Key successfully updated', CREATED
{ "deleted": [ { "line_no": 9, "char_start": 233, "char_end": 234, "line": "\n" } ], "added": [ { "line_no": 12, "char_start": 371, "char_end": 408, "line": "\tvalidateKeyName(token_data['name'])\n" } ] }
{ "deleted": [ { "char_start": 233, "char_end": 234, "chars": "\n" } ], "added": [ { "char_start": 369, "char_end": 406, "chars": ")\n\tvalidateKeyName(token_data['name']" } ] }
github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833
impl.py
cwe-022
create_basename_core
def create_basename_core(basename): try: basename = basename.casefold() except Exception: basename = basename.lower() basename = basename.replace(' ', '-') basename = re.sub(r'<[^>]*>', r'', basename) basename = re.sub(r'[^a-z0-9\-]', r'', basename) basename = re.sub(r'\-\-', r'-', basename) basename = urllib.parse.quote_plus(basename) return basename
def create_basename_core(basename): try: basename = basename.casefold() except Exception: basename = basename.lower() basename = re.sub(r'[ \./]', r'-', basename) basename = re.sub(r'<[^>]*>', r'', basename) basename = re.sub(r'[^a-z0-9\-]', r'', basename) basename = re.sub(r'\-\-', r'-', basename) basename = urllib.parse.quote_plus(basename) return basename
{ "deleted": [ { "line_no": 7, "char_start": 143, "char_end": 185, "line": " basename = basename.replace(' ', '-')\n" } ], "added": [ { "line_no": 7, "char_start": 143, "char_end": 192, "line": " basename = re.sub(r'[ \\./]', r'-', basename)\n" } ] }
{ "deleted": [ { "char_start": 158, "char_end": 165, "chars": "basenam" }, { "char_start": 168, "char_end": 175, "chars": "eplace(" } ], "added": [ { "char_start": 158, "char_end": 159, "chars": "r" }, { "char_start": 161, "char_end": 164, "chars": "sub" }, { "char_start": 165, "char_end": 166, "chars": "r" }, { "char_start": 167, "char_end": 168, "chars": "[" }, { "char_start": 169, "char_end": 173, "chars": "\\./]" }, { "char_start": 176, "char_end": 177, "chars": "r" }, { "char_start": 180, "char_end": 190, "chars": ", basename" } ] }
github.com/syegulalp/mercury/commit/3f7c7442fa49aec37577dbdb47ce11a848e7bd03
MeTal/core/utils.py
cwe-022
get
def get(self, key): try: result = self.etcd.get(os.path.join(self.namespace, key)) except etcd.EtcdException as err: log_error("Error fetching key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to get key') return result.value
def get(self, key): try: result = self.etcd.get(self._absolute_key(key)) except etcd.EtcdException as err: log_error("Error fetching key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to get key') return result.value
{ "deleted": [ { "line_no": 3, "char_start": 37, "char_end": 107, "line": " result = self.etcd.get(os.path.join(self.namespace, key))\n" } ], "added": [ { "line_no": 3, "char_start": 37, "char_end": 97, "line": " result = self.etcd.get(self._absolute_key(key))\n" } ] }
{ "deleted": [ { "char_start": 72, "char_end": 85, "chars": "os.path.join(" }, { "char_start": 90, "char_end": 91, "chars": "n" }, { "char_start": 92, "char_end": 94, "chars": "me" }, { "char_start": 95, "char_end": 98, "chars": "pac" }, { "char_start": 99, "char_end": 101, "chars": ", " } ], "added": [ { "char_start": 77, "char_end": 78, "chars": "_" }, { "char_start": 79, "char_end": 85, "chars": "bsolut" }, { "char_start": 86, "char_end": 88, "chars": "_k" }, { "char_start": 89, "char_end": 91, "chars": "y(" } ] }
github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4
custodia/store/etcdstore.py
cwe-022
PHYSICALPATH_FUNC
PHYSICALPATH_FUNC(mod_alias_physical_handler) { plugin_data *p = p_d; int uri_len, basedir_len; char *uri_ptr; size_t k; if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON; mod_alias_patch_connection(srv, con, p); /* not to include the tailing slash */ basedir_len = buffer_string_length(con->physical.basedir); if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len; uri_len = buffer_string_length(con->physical.path) - basedir_len; uri_ptr = con->physical.path->ptr + basedir_len; for (k = 0; k < p->conf.alias->used; k++) { data_string *ds = (data_string *)p->conf.alias->data[k]; int alias_len = buffer_string_length(ds->key); if (alias_len > uri_len) continue; if (buffer_is_empty(ds->key)) continue; if (0 == (con->conf.force_lowercase_filenames ? strncasecmp(uri_ptr, ds->key->ptr, alias_len) : strncmp(uri_ptr, ds->key->ptr, alias_len))) { /* matched */ buffer_copy_buffer(con->physical.basedir, ds->value); buffer_copy_buffer(srv->tmp_buf, ds->value); buffer_append_string(srv->tmp_buf, uri_ptr + alias_len); buffer_copy_buffer(con->physical.path, srv->tmp_buf); return HANDLER_GO_ON; } } /* not found */ return HANDLER_GO_ON; }
PHYSICALPATH_FUNC(mod_alias_physical_handler) { plugin_data *p = p_d; int uri_len, basedir_len; char *uri_ptr; size_t k; if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON; mod_alias_patch_connection(srv, con, p); /* not to include the tailing slash */ basedir_len = buffer_string_length(con->physical.basedir); if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len; uri_len = buffer_string_length(con->physical.path) - basedir_len; uri_ptr = con->physical.path->ptr + basedir_len; for (k = 0; k < p->conf.alias->used; k++) { data_string *ds = (data_string *)p->conf.alias->data[k]; int alias_len = buffer_string_length(ds->key); if (alias_len > uri_len) continue; if (buffer_is_empty(ds->key)) continue; if (0 == (con->conf.force_lowercase_filenames ? strncasecmp(uri_ptr, ds->key->ptr, alias_len) : strncmp(uri_ptr, ds->key->ptr, alias_len))) { /* matched */ /* check for path traversal in url-path following alias if key * does not end in slash, but replacement value ends in slash */ if (uri_ptr[alias_len] == '.') { char *s = uri_ptr + alias_len + 1; if (*s == '.') ++s; if (*s == '/' || *s == '\0') { size_t vlen = buffer_string_length(ds->value); if (0 != alias_len && ds->key->ptr[alias_len-1] != '/' && 0 != vlen && ds->value->ptr[vlen-1] == '/') { con->http_status = 403; return HANDLER_FINISHED; } } } buffer_copy_buffer(con->physical.basedir, ds->value); buffer_copy_buffer(srv->tmp_buf, ds->value); buffer_append_string(srv->tmp_buf, uri_ptr + alias_len); buffer_copy_buffer(con->physical.path, srv->tmp_buf); return HANDLER_GO_ON; } } /* not found */ return HANDLER_GO_ON; }
{ "deleted": [], "added": [ { "line_no": 29, "char_start": 928, "char_end": 994, "line": "\t\t\t/* check for path traversal in url-path following alias if key\n" }, { "line_no": 30, "char_start": 994, "char_end": 1062, "line": "\t\t\t * does not end in slash, but replacement value ends in slash */\n" }, { "line_no": 31, "char_start": 1062, "char_end": 1098, "line": "\t\t\tif (uri_ptr[alias_len] == '.') {\n" }, { "line_no": 32, "char_start": 1098, "char_end": 1137, "line": "\t\t\t\tchar *s = uri_ptr + alias_len + 1;\n" }, { "line_no": 33, "char_start": 1137, "char_end": 1161, "line": "\t\t\t\tif (*s == '.') ++s;\n" }, { "line_no": 34, "char_start": 1161, "char_end": 1196, "line": "\t\t\t\tif (*s == '/' || *s == '\\0') {\n" }, { "line_no": 35, "char_start": 1196, "char_end": 1248, "line": "\t\t\t\t\tsize_t vlen = buffer_string_length(ds->value);\n" }, { "line_no": 36, "char_start": 1248, "char_end": 1308, "line": "\t\t\t\t\tif (0 != alias_len && ds->key->ptr[alias_len-1] != '/'\n" }, { "line_no": 37, "char_start": 1308, "char_end": 1366, "line": "\t\t\t\t\t && 0 != vlen && ds->value->ptr[vlen-1] == '/') {\n" }, { "line_no": 38, "char_start": 1366, "char_end": 1396, "line": "\t\t\t\t\t\tcon->http_status = 403;\n" }, { "line_no": 39, "char_start": 1396, "char_end": 1427, "line": "\t\t\t\t\t\treturn HANDLER_FINISHED;\n" }, { "line_no": 40, "char_start": 1427, "char_end": 1434, "line": "\t\t\t\t\t}\n" }, { "line_no": 41, "char_start": 1434, "char_end": 1440, "line": "\t\t\t\t}\n" }, { "line_no": 42, "char_start": 1440, "char_end": 1445, "line": "\t\t\t}\n" }, { "line_no": 43, "char_start": 1445, "char_end": 1446, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 931, "char_end": 1449, "chars": "/* check for path traversal in url-path following alias if key\n\t\t\t * does not end in slash, but replacement value ends in slash */\n\t\t\tif (uri_ptr[alias_len] == '.') {\n\t\t\t\tchar *s = uri_ptr + alias_len + 1;\n\t\t\t\tif (*s == '.') ++s;\n\t\t\t\tif (*s == '/' || *s == '\\0') {\n\t\t\t\t\tsize_t vlen = buffer_string_length(ds->value);\n\t\t\t\t\tif (0 != alias_len && ds->key->ptr[alias_len-1] != '/'\n\t\t\t\t\t && 0 != vlen && ds->value->ptr[vlen-1] == '/') {\n\t\t\t\t\t\tcon->http_status = 403;\n\t\t\t\t\t\treturn HANDLER_FINISHED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t" } ] }
github.com/lighttpd/lighttpd1.4/commit/2105dae0f9d7a964375ce681e53cb165375f84c1
src/mod_alias.c
cwe-022
download_check_files
def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: if '/../' in f: return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e)
def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: # don't allow to traverse up in the file system if '/../' in f or f.startswith('../'): return 'invalid_file' # CVE-2015-8309: do not allow absolute file paths if os.path.isabs(f): return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e)
{ "deleted": [ { "line_no": 9, "char_start": 383, "char_end": 411, "line": " if '/../' in f:\n" } ], "added": [ { "line_no": 10, "char_start": 443, "char_end": 494, "line": " if '/../' in f or f.startswith('../'):\n" }, { "line_no": 11, "char_start": 494, "char_end": 532, "line": " return 'invalid_file'\n" }, { "line_no": 13, "char_start": 594, "char_end": 627, "line": " if os.path.isabs(f):\n" } ] }
{ "deleted": [], "added": [ { "char_start": 395, "char_end": 455, "chars": "# don't allow to traverse up in the file system\n " }, { "char_start": 469, "char_end": 625, "chars": " or f.startswith('../'):\n return 'invalid_file'\n # CVE-2015-8309: do not allow absolute file paths\n if os.path.isabs(f)" } ] }
github.com/devsnd/cherrymusic/commit/62dec34a1ea0741400dd6b6c660d303dcd651e86
cherrymusicserver/httphandler.py
cwe-022
get_files
def get_files(self, submit_id, password=None, astree=False): """ Returns files from a submitted analysis. @param password: The password to unlock container archives with @param astree: sflock option; determines the format in which the files are returned @return: A tree of files """ submit = Database().view_submit(submit_id) files, duplicates = [], [] for data in submit.data["data"]: if data["type"] == "file": filename = Storage.get_filename_from_path(data["data"]) filepath = os.path.join(submit.tmp_path, data["data"]) filedata = open(filepath, "rb").read() unpacked = sflock.unpack( filepath=filename, contents=filedata, password=password, duplicates=duplicates ) if astree: unpacked = unpacked.astree() files.append(unpacked) elif data["type"] == "url": files.append({ "filename": data["data"], "filepath": "", "relapath": "", "selected": True, "size": 0, "type": "url", "package": "ie", "extrpath": [], "duplicate": False, "children": [], "mime": "text/html", "finger": { "magic_human": "url", "magic": "url" } }) else: raise RuntimeError( "Unknown data entry type: %s" % data["type"] ) return { "files": files, "path": submit.tmp_path, }
def get_files(self, submit_id, password=None, astree=False): """ Returns files from a submitted analysis. @param password: The password to unlock container archives with @param astree: sflock option; determines the format in which the files are returned @return: A tree of files """ submit = Database().view_submit(submit_id) files, duplicates = [], [] for data in submit.data["data"]: if data["type"] == "file": filename = Storage.get_filename_from_path(data["data"]) filepath = os.path.join(submit.tmp_path, filename) unpacked = sflock.unpack( filepath=filepath, password=password, duplicates=duplicates ) if astree: unpacked = unpacked.astree(sanitize=True) files.append(unpacked) elif data["type"] == "url": files.append({ "filename": data["data"], "filepath": "", "relapath": "", "selected": True, "size": 0, "type": "url", "package": "ie", "extrpath": [], "duplicate": False, "children": [], "mime": "text/html", "finger": { "magic_human": "url", "magic": "url" } }) else: raise RuntimeError( "Unknown data entry type: %s" % data["type"] ) return files
{ "deleted": [ { "line_no": 14, "char_start": 574, "char_end": 645, "line": " filepath = os.path.join(submit.tmp_path, data[\"data\"])\n" }, { "line_no": 15, "char_start": 645, "char_end": 700, "line": " filedata = open(filepath, \"rb\").read()\n" }, { "line_no": 18, "char_start": 743, "char_end": 801, "line": " filepath=filename, contents=filedata,\n" }, { "line_no": 19, "char_start": 801, "char_end": 862, "line": " password=password, duplicates=duplicates\n" }, { "line_no": 23, "char_start": 908, "char_end": 957, "line": " unpacked = unpacked.astree()\n" }, { "line_no": 49, "char_start": 1776, "char_end": 1793, "line": " return {\n" }, { "line_no": 50, "char_start": 1793, "char_end": 1821, "line": " \"files\": files,\n" }, { "line_no": 51, "char_start": 1821, "char_end": 1858, "line": " \"path\": submit.tmp_path,\n" }, { "line_no": 52, "char_start": 1858, "char_end": 1867, "line": " }\n" } ], "added": [ { "line_no": 14, "char_start": 574, "char_end": 641, "line": " filepath = os.path.join(submit.tmp_path, filename)\n" }, { "line_no": 17, "char_start": 684, "char_end": 764, "line": " filepath=filepath, password=password, duplicates=duplicates\n" }, { "line_no": 21, "char_start": 810, "char_end": 872, "line": " unpacked = unpacked.astree(sanitize=True)\n" }, { "line_no": 47, "char_start": 1691, "char_end": 1711, "line": " return files\n" } ] }
{ "deleted": [ { "char_start": 631, "char_end": 661, "chars": "data[\"data\"])\n " }, { "char_start": 665, "char_end": 675, "chars": "data = ope" }, { "char_start": 676, "char_end": 682, "chars": "(filep" }, { "char_start": 683, "char_end": 694, "chars": "th, \"rb\").r" }, { "char_start": 695, "char_end": 698, "chars": "ad(" }, { "char_start": 776, "char_end": 796, "chars": "name, contents=filed" }, { "char_start": 798, "char_end": 799, "chars": "a" }, { "char_start": 800, "char_end": 820, "chars": "\n " }, { "char_start": 1791, "char_end": 1806, "chars": "{\n \"" }, { "char_start": 1811, "char_end": 1867, "chars": "\": files,\n \"path\": submit.tmp_path,\n }" } ], "added": [ { "char_start": 637, "char_end": 638, "chars": "m" }, { "char_start": 717, "char_end": 718, "chars": "p" }, { "char_start": 720, "char_end": 721, "chars": "h" }, { "char_start": 857, "char_end": 870, "chars": "sanitize=True" } ] }
github.com/cuckoosandbox/cuckoo/commit/168cabf86730d56b7fa319278bf0f0034052666a
cuckoo/core/submit.py
cwe-022
handle
def handle(self, keepalive=True, initial_timeout=None): # we are requested to skip processing and keep the previous values if self.skip: return self.response.handle() # default to no keepalive in case something happens while even trying ensure we have a request self.keepalive = False self.headers = HTTPHeaders() # if initial_timeout is set, only wait that long for the initial request line if initial_timeout: self.connection.settimeout(initial_timeout) else: self.connection.settimeout(self.timeout) # get request line try: # ignore empty lines waiting on request request = '\r\n' while request == '\r\n': request = self.rfile.readline(max_line_size + 1).decode(http_encoding) # if read hits timeout or has some other error, ignore the request except Exception: return True # ignore empty requests if not request: return True # we have a request, go back to normal timeout if initial_timeout: self.connection.settimeout(self.timeout) # remove \r\n from the end self.request_line = request[:-2] # set some reasonable defaults in case the worst happens and we need to tell the client self.method = '' self.resource = '/' try: # HTTP Status 414 if len(request) > max_line_size: raise HTTPError(414) # HTTP Status 400 if request[-2:] != '\r\n': raise HTTPError(400) # try the request line and error out if can't parse it try: self.method, self.resource, self.request_http = self.request_line.split() # HTTP Status 400 except ValueError: raise HTTPError(400) # HTTP Status 505 if self.request_http != http_version: raise HTTPError(505) # read and parse request headers while True: line = self.rfile.readline(max_line_size + 1).decode(http_encoding) # hit end of headers if line == '\r\n': break self.headers.add(line) # if we are requested to close the connection after we finish, do so if self.headers.get('Connection') == 'close': self.keepalive = False # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed) else: self.keepalive = keepalive # find a matching regex to handle the request with for regex, handler in self.server.routes.items(): match = regex.match(self.resource) if match: # create a dictionary of groups groups = match.groupdict() values = groups.values() for idx, group in enumerate(match.groups()): if group not in values: groups[idx] = group # create handler self.handler = handler(self, self.response, groups) break # HTTP Status 404 # if loop is not broken (handler is not found), raise a 404 else: raise HTTPError(404) # use DummyHandler so the error is raised again when ready for response except Exception as error: self.handler = DummyHandler(self, self.response, (), error) finally: # we finished listening and handling early errors and so let a response class now finish up the job of talking return self.response.handle()
def handle(self, keepalive=True, initial_timeout=None): # we are requested to skip processing and keep the previous values if self.skip: return self.response.handle() # default to no keepalive in case something happens while even trying ensure we have a request self.keepalive = False self.headers = HTTPHeaders() # if initial_timeout is set, only wait that long for the initial request line if initial_timeout: self.connection.settimeout(initial_timeout) else: self.connection.settimeout(self.timeout) # get request line try: # ignore empty lines waiting on request request = '\r\n' while request == '\r\n': request = self.rfile.readline(max_line_size + 1).decode(http_encoding) # if read hits timeout or has some other error, ignore the request except Exception: return True # ignore empty requests if not request: return True # we have a request, go back to normal timeout if initial_timeout: self.connection.settimeout(self.timeout) # remove \r\n from the end self.request_line = request[:-2] # set some reasonable defaults in case the worst happens and we need to tell the client self.method = '' self.resource = '/' try: # HTTP Status 414 if len(request) > max_line_size: raise HTTPError(414) # HTTP Status 400 if request[-2:] != '\r\n': raise HTTPError(400) # try the request line and error out if can't parse it try: self.method, resource, self.request_http = self.request_line.split() self.resource = urllib.parse.unquote(resource) # HTTP Status 400 except ValueError: raise HTTPError(400) # HTTP Status 505 if self.request_http != http_version: raise HTTPError(505) # read and parse request headers while True: line = self.rfile.readline(max_line_size + 1).decode(http_encoding) # hit end of headers if line == '\r\n': break self.headers.add(line) # if we are requested to close the connection after we finish, do so if self.headers.get('Connection') == 'close': self.keepalive = False # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed) else: self.keepalive = keepalive # find a matching regex to handle the request with for regex, handler in self.server.routes.items(): match = regex.match(self.resource) if match: # create a dictionary of groups groups = match.groupdict() values = groups.values() for idx, group in enumerate(match.groups()): if group not in values: groups[idx] = group # create handler self.handler = handler(self, self.response, groups) break # HTTP Status 404 # if loop is not broken (handler is not found), raise a 404 else: raise HTTPError(404) # use DummyHandler so the error is raised again when ready for response except Exception as error: self.handler = DummyHandler(self, self.response, (), error) finally: # we finished listening and handling early errors and so let a response class now finish up the job of talking return self.response.handle()
{ "deleted": [ { "line_no": 53, "char_start": 1744, "char_end": 1834, "line": " self.method, self.resource, self.request_http = self.request_line.split()\n" } ], "added": [ { "line_no": 53, "char_start": 1744, "char_end": 1829, "line": " self.method, resource, self.request_http = self.request_line.split()\n" }, { "line_no": 54, "char_start": 1829, "char_end": 1892, "line": " self.resource = urllib.parse.unquote(resource)\n" } ] }
{ "deleted": [ { "char_start": 1773, "char_end": 1778, "chars": "self." } ], "added": [ { "char_start": 1827, "char_end": 1890, "chars": ")\n self.resource = urllib.parse.unquote(resource" } ] }
github.com/fkmclane/python-fooster-web/commit/80202a6d3788ad1212a162d19785c600025e6aa4
fooster/web/web.py
cwe-022
dd_delete_item
int dd_delete_item(struct dump_dir *dd, const char *name) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ char *path = concat_path_file(dd->dd_dirname, name); int res = unlink(path); if (res < 0) { if (errno == ENOENT) errno = res = 0; else perror_msg("Can't delete file '%s'", path); } free(path); return res; }
int dd_delete_item(struct dump_dir *dd, const char *name) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name); char *path = concat_path_file(dd->dd_dirname, name); int res = unlink(path); if (res < 0) { if (errno == ENOENT) errno = res = 0; else perror_msg("Can't delete file '%s'", path); } free(path); return res; }
{ "deleted": [], "added": [ { "line_no": 6, "char_start": 145, "char_end": 185, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 7, "char_start": 185, "char_end": 271, "line": " error_msg_and_die(\"Cannot delete item. '%s' is not a valid file name\", name);\n" }, { "line_no": 8, "char_start": 271, "char_end": 272, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 149, "char_end": 276, "chars": "if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot delete item. '%s' is not a valid file name\", name);\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
render
def render(self, request): action = "download" if "action" in request.args: action = request.args["action"][0] if "file" in request.args: filename = request.args["file"][0].decode('utf-8', 'ignore').encode('utf-8') filename = re.sub("^/+", "/", os.path.realpath(filename)) if not os.path.exists(filename): return "File '%s' not found" % (filename) if action == "stream": name = "stream" if "name" in request.args: name = request.args["name"][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name) request.setHeader("Content-Type", "application/x-mpegurl") return response elif action == "delete": request.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (filename) elif action == "download": request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = "application/octet-stream") return rfile.render(request) else: return "wrong action parameter" if "dir" in request.args: path = request.args["dir"][0] pattern = '*' data = [] if "pattern" in request.args: pattern = request.args["pattern"][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({"result": True,"dirs": directories,"files": files}) else: data.append({"result": False,"message": "path %s not exits" % (path)}) request.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(data, indent=2)
def render(self, request): action = "download" if "action" in request.args: action = request.args["action"][0] if "file" in request.args: filename = lenient_force_utf_8(request.args["file"][0]) filename = sanitise_filename_slashes(os.path.realpath(filename)) if not os.path.exists(filename): return "File '%s' not found" % (filename) if action == "stream": name = "stream" if "name" in request.args: name = request.args["name"][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name) request.setHeader("Content-Type", "application/x-mpegurl") return response elif action == "delete": request.setResponseCode(http.OK) return "TODO: DELETE FILE: %s" % (filename) elif action == "download": request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = "application/octet-stream") return rfile.render(request) else: return "wrong action parameter" if "dir" in request.args: path = request.args["dir"][0] pattern = '*' data = [] if "pattern" in request.args: pattern = request.args["pattern"][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({"result": True,"dirs": directories,"files": files}) else: data.append({"result": False,"message": "path %s not exits" % (path)}) request.setHeader("content-type", "application/json; charset=utf-8") return json.dumps(data, indent=2)
{ "deleted": [ { "line_no": 7, "char_start": 149, "char_end": 229, "line": "\t\t\tfilename = request.args[\"file\"][0].decode('utf-8', 'ignore').encode('utf-8')\n" }, { "line_no": 8, "char_start": 229, "char_end": 290, "line": "\t\t\tfilename = re.sub(\"^/+\", \"/\", os.path.realpath(filename))\n" } ], "added": [ { "line_no": 7, "char_start": 149, "char_end": 208, "line": "\t\t\tfilename = lenient_force_utf_8(request.args[\"file\"][0])\n" }, { "line_no": 8, "char_start": 208, "char_end": 276, "line": "\t\t\tfilename = sanitise_filename_slashes(os.path.realpath(filename))\n" } ] }
{ "deleted": [ { "char_start": 186, "char_end": 227, "chars": ".decode('utf-8', 'ignore').encode('utf-8'" }, { "char_start": 243, "char_end": 244, "chars": "r" }, { "char_start": 245, "char_end": 246, "chars": "." }, { "char_start": 247, "char_end": 249, "chars": "ub" }, { "char_start": 250, "char_end": 262, "chars": "\"^/+\", \"/\", " } ], "added": [ { "char_start": 163, "char_end": 183, "chars": "lenient_force_utf_8(" }, { "char_start": 222, "char_end": 238, "chars": "sanitise_filenam" }, { "char_start": 239, "char_end": 240, "chars": "_" }, { "char_start": 241, "char_end": 247, "chars": "lashes" } ] }
github.com/E2OpenPlugins/e2openplugin-OpenWebif/commit/a846b7664eda3a4c51a452e00638cf7337dc2013
plugin/controllers/file.py
cwe-022
_inject_net_into_fs
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join(netdir, 'interfaces') utils.execute('tee', netfile, process_input=net, run_as_root=True)
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = _join_and_check_path_within_fs(fs, 'etc', 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join('etc', 'network', 'interfaces') _inject_file_into_fs(fs, netfile, net)
{ "deleted": [ { "line_no": 6, "char_start": 181, "char_end": 243, "line": " netdir = os.path.join(os.path.join(fs, 'etc'), 'network')\n" }, { "line_no": 10, "char_start": 426, "char_end": 475, "line": " netfile = os.path.join(netdir, 'interfaces')\n" }, { "line_no": 11, "char_start": 475, "char_end": 545, "line": " utils.execute('tee', netfile, process_input=net, run_as_root=True)\n" } ], "added": [ { "line_no": 6, "char_start": 181, "char_end": 247, "line": " netdir = _join_and_check_path_within_fs(fs, 'etc', 'network')\n" }, { "line_no": 10, "char_start": 430, "char_end": 431, "line": "\n" }, { "line_no": 11, "char_start": 431, "char_end": 490, "line": " netfile = os.path.join('etc', 'network', 'interfaces')\n" }, { "line_no": 12, "char_start": 490, "char_end": 532, "line": " _inject_file_into_fs(fs, netfile, net)\n" } ] }
{ "deleted": [ { "char_start": 194, "char_end": 202, "chars": "os.path." }, { "char_start": 206, "char_end": 210, "chars": "(os." }, { "char_start": 214, "char_end": 217, "chars": ".jo" }, { "char_start": 229, "char_end": 230, "chars": ")" }, { "char_start": 456, "char_end": 458, "chars": "di" }, { "char_start": 479, "char_end": 480, "chars": "u" }, { "char_start": 483, "char_end": 485, "chars": "s." }, { "char_start": 486, "char_end": 490, "chars": "xecu" }, { "char_start": 491, "char_end": 492, "chars": "e" }, { "char_start": 493, "char_end": 498, "chars": "'tee'" }, { "char_start": 509, "char_end": 523, "chars": "process_input=" }, { "char_start": 526, "char_end": 544, "chars": ", run_as_root=True" } ], "added": [ { "char_start": 194, "char_end": 196, "chars": "_j" }, { "char_start": 197, "char_end": 210, "chars": "in_and_check_" }, { "char_start": 214, "char_end": 216, "chars": "_w" }, { "char_start": 221, "char_end": 224, "chars": "_fs" }, { "char_start": 430, "char_end": 431, "chars": "\n" }, { "char_start": 458, "char_end": 466, "chars": "'etc', '" }, { "char_start": 469, "char_end": 471, "chars": "wo" }, { "char_start": 472, "char_end": 474, "chars": "k'" }, { "char_start": 494, "char_end": 495, "chars": "_" }, { "char_start": 496, "char_end": 498, "chars": "nj" }, { "char_start": 501, "char_end": 505, "chars": "_fil" }, { "char_start": 506, "char_end": 509, "chars": "_in" }, { "char_start": 510, "char_end": 517, "chars": "o_fs(fs" } ] }
github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7
nova/virt/disk/api.py
cwe-022
canonicalize
def canonicalize(self): """:: path = path.canonicalize() Canonicalize path. :: # "/foo/baz" Pyjo.Path.new('/foo/./bar/../baz').canonicalize() # "/../baz" Pyjo.Path.new('/foo/../bar/../../baz').canonicalize() """ parts = self.parts i = 0 while i < len(parts): if parts[i] == '.' or parts[i] == '': parts.pop(i) elif i < 1 or parts[i] != '..' or parts[i - 1] == '..': i += 1 else: i -= 1 parts.pop(i) parts.pop(i) if not parts: self.trailing_slash = False return self
def canonicalize(self): """:: path = path.canonicalize() Canonicalize path by resolving ``.`` and ``..``, in addition ``...`` will be treated as ``.`` to protect from path traversal attacks. # "/foo/baz" Pyjo.Path.new('/foo/./bar/../baz').canonicalize() # "/../baz" Pyjo.Path.new('/foo/../bar/../../baz').canonicalize() # "/foo/bar" Pyjo.Path.new('/foo/.../bar').canonicalize() """ parts = self.parts i = 0 while i < len(parts): if parts[i] == '' or parts[i] == '.' or parts[i] == '...': parts.pop(i) elif i < 1 or parts[i] != '..' or parts[i - 1] == '..': i += 1 else: i -= 1 parts.pop(i) parts.pop(i) if not parts: self.trailing_slash = False return self
{ "deleted": [ { "line_no": 6, "char_start": 83, "char_end": 113, "line": " Canonicalize path. ::\n" }, { "line_no": 17, "char_start": 375, "char_end": 425, "line": " if parts[i] == '.' or parts[i] == '':\n" } ], "added": [ { "line_no": 6, "char_start": 83, "char_end": 168, "line": " Canonicalize path by resolving ``.`` and ``..``, in addition ``...`` will be\n" }, { "line_no": 7, "char_start": 168, "char_end": 233, "line": " treated as ``.`` to protect from path traversal attacks.\n" }, { "line_no": 14, "char_start": 412, "char_end": 413, "line": "\n" }, { "line_no": 16, "char_start": 438, "char_end": 495, "line": " Pyjo.Path.new('/foo/.../bar').canonicalize()\n" }, { "line_no": 21, "char_start": 578, "char_end": 649, "line": " if parts[i] == '' or parts[i] == '.' or parts[i] == '...':\n" } ] }
{ "deleted": [ { "char_start": 110, "char_end": 112, "chars": "::" } ], "added": [ { "char_start": 108, "char_end": 124, "chars": " by resolving ``" }, { "char_start": 125, "char_end": 171, "chars": "`` and ``..``, in addition ``...`` will be\n " }, { "char_start": 172, "char_end": 232, "chars": " treated as ``.`` to protect from path traversal attacks." }, { "char_start": 411, "char_end": 494, "chars": "\n\n # \"/foo/bar\"\n Pyjo.Path.new('/foo/.../bar').canonicalize()" }, { "char_start": 606, "char_end": 624, "chars": "' or parts[i] == '" }, { "char_start": 643, "char_end": 646, "chars": "..." } ] }
github.com/dex4er/Pyjoyment/commit/e4b115bc80c41615b2133091af3a74ee5d995c2e
Pyjo/Path.py
cwe-022
CWebSock::GetSkinPath
CString CWebSock::GetSkinPath(const CString& sSkinName) { CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkinName; if (!CFile::IsDir(sRet)) { sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkinName; if (!CFile::IsDir(sRet)) { sRet = CString(_SKINDIR_) + "/" + sSkinName; } } return sRet + "/"; }
CString CWebSock::GetSkinPath(const CString& sSkinName) { const CString sSkin = sSkinName.Replace_n("/", "_").Replace_n(".", "_"); CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkin; if (!CFile::IsDir(sRet)) { sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkin; if (!CFile::IsDir(sRet)) { sRet = CString(_SKINDIR_) + "/" + sSkin; } } return sRet + "/"; }
{ "deleted": [ { "line_no": 2, "char_start": 58, "char_end": 130, "line": " CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkinName;\n" }, { "line_no": 5, "char_start": 162, "char_end": 230, "line": " sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkinName;\n" }, { "line_no": 8, "char_start": 266, "char_end": 323, "line": " sRet = CString(_SKINDIR_) + \"/\" + sSkinName;\n" } ], "added": [ { "line_no": 2, "char_start": 58, "char_end": 135, "line": " const CString sSkin = sSkinName.Replace_n(\"/\", \"_\").Replace_n(\".\", \"_\");\n" }, { "line_no": 3, "char_start": 135, "char_end": 136, "line": "\n" }, { "line_no": 4, "char_start": 136, "char_end": 204, "line": " CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkin;\n" }, { "line_no": 7, "char_start": 236, "char_end": 300, "line": " sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkin;\n" }, { "line_no": 10, "char_start": 336, "char_end": 389, "line": " sRet = CString(_SKINDIR_) + \"/\" + sSkin;\n" } ] }
{ "deleted": [ { "char_start": 124, "char_end": 128, "chars": "Name" }, { "char_start": 224, "char_end": 228, "chars": "Name" }, { "char_start": 317, "char_end": 321, "chars": "Name" } ], "added": [ { "char_start": 62, "char_end": 140, "chars": "const CString sSkin = sSkinName.Replace_n(\"/\", \"_\").Replace_n(\".\", \"_\");\n\n " } ] }
github.com/znc/znc/commit/a4a5aeeb17d32937d8c7d743dae9a4cc755ce773
src/WebModules.cpp
cwe-022
addKey
def addKey(client): """Adds a new key with the specified name and contents. Returns an error if a key with the specified name already exists. """ global BAD_REQUEST global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) # Use 'x' flag so we can throw an error if a key with this name already exists try: with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f: f.write(token_data['key']) except FileExistsError: raise FoxlockError(BAD_REQUEST, "Key '%s' already exists" % token_data['name']) return 'Key successfully created', CREATED
def addKey(client): """Adds a new key with the specified name and contents. Returns an error if a key with the specified name already exists. """ global BAD_REQUEST global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) validateKeyName(token_data['name']) # Use 'x' flag so we can throw an error if a key with this name already exists try: with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f: f.write(token_data['key']) except FileExistsError: raise FoxlockError(BAD_REQUEST, "Key '%s' already exists" % token_data['name']) return 'Key successfully created', CREATED
{ "deleted": [ { "line_no": 9, "char_start": 210, "char_end": 211, "line": "\n" } ], "added": [ { "line_no": 12, "char_start": 348, "char_end": 385, "line": "\tvalidateKeyName(token_data['name'])\n" } ] }
{ "deleted": [ { "char_start": 210, "char_end": 211, "chars": "\n" } ], "added": [ { "char_start": 346, "char_end": 383, "chars": ")\n\tvalidateKeyName(token_data['name']" } ] }
github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833
impl.py
cwe-022
dd_save_text
void dd_save_text(struct dump_dir *dd, const char *name, const char *data) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }
void dd_save_text(struct dump_dir *dd, const char *name, const char *data) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die("Cannot save text. '%s' is not a valid file name", name); char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }
{ "deleted": [], "added": [ { "line_no": 6, "char_start": 162, "char_end": 202, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 7, "char_start": 202, "char_end": 286, "line": " error_msg_and_die(\"Cannot save text. '%s' is not a valid file name\", name);\n" }, { "line_no": 8, "char_start": 286, "char_end": 287, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 166, "char_end": 291, "chars": "if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot save text. '%s' is not a valid file name\", name);\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
misc_file_checks
def misc_file_checks(self): print_header("MISC FILE CHECKS") # # Check for recommended and mandatory files # filenames = ("manifest.json", "LICENSE", "README.md", "scripts/install", "scripts/remove", "scripts/upgrade", "scripts/backup", "scripts/restore") non_mandatory = ("script/backup", "script/restore") for filename in filenames: if file_exists(self.path + "/" + filename): continue elif filename in non_mandatory: print_warning("Consider adding a file %s" % filename) else: print_error("File %s is mandatory" % filename) # # Deprecated php-fpm.ini thing # if file_exists(self.path + "/conf/php-fpm.ini"): print_warning( "Using a separate php-fpm.ini file is deprecated. " "Please merge your php-fpm directives directly in the pool file. " "(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )" ) # # Deprecated usage of 'add_header' in nginx conf # for filename in os.listdir(self.path + "/conf"): if not os.path.isfile(self.path + "/conf/" + filename): continue content = open(self.path + "/conf/" + filename).read() if "location" in content and "add_header" in content: print_warning( "Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. " "(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx " "and https://github.com/openresty/headers-more-nginx-module#more_set_headers )" )
def misc_file_checks(self): print_header("MISC FILE CHECKS") # # Check for recommended and mandatory files # filenames = ("manifest.json", "LICENSE", "README.md", "scripts/install", "scripts/remove", "scripts/upgrade", "scripts/backup", "scripts/restore") non_mandatory = ("script/backup", "script/restore") for filename in filenames: if file_exists(self.path + "/" + filename): continue elif filename in non_mandatory: print_warning("Consider adding a file %s" % filename) else: print_error("File %s is mandatory" % filename) # # Deprecated php-fpm.ini thing # if file_exists(self.path + "/conf/php-fpm.ini"): print_warning( "Using a separate php-fpm.ini file is deprecated. " "Please merge your php-fpm directives directly in the pool file. " "(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )" ) # # Analyze nginx conf # - Deprecated usage of 'add_header' in nginx conf # - Spot path traversal issue vulnerability # for filename in os.listdir(self.path + "/conf"): # Ignore subdirs or filename not containing nginx in the name if not os.path.isfile(self.path + "/conf/" + filename) or "nginx" not in filename: continue # # 'add_header' usage # content = open(self.path + "/conf/" + filename).read() if "location" in content and "add_header" in content: print_warning( "Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. " "(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx " "and https://github.com/openresty/headers-more-nginx-module#more_set_headers )" ) # # Path traversal issues # lines = open(self.path + "/conf/" + filename).readlines() lines = [line.strip() for line in lines if not line.strip().startswith("#")] # Let's find the first location line location_line = None path_traversal_vulnerable = False lines_iter = lines.__iter__() for line in lines_iter: if line.startswith("location"): location_line = line break # Look at the next lines for an 'alias' directive if location_line is not None: for line in lines_iter: if line.startswith("location"): # Entering a new location block ... abort here # and assume there's no alias block later... break if line.startswith("alias"): # We should definitely check for path traversal issue # Does the location target ends with / ? target = location_line.split()[-2] if not target.endswith("/"): path_traversal_vulnerable = True break if path_traversal_vulnerable: print_warning( "The nginx configuration appears vulnerable to path traversal as explained in " "https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/\n" "To fix it, look at the first lines of the nginx conf of the example app : " "https://github.com/YunoHost/example_ynh/blob/master/conf/nginx.conf" )
{ "deleted": [ { "line_no": 39, "char_start": 1268, "char_end": 1336, "line": " if not os.path.isfile(self.path + \"/conf/\" + filename):\n" } ], "added": [ { "line_no": 42, "char_start": 1425, "char_end": 1520, "line": " if not os.path.isfile(self.path + \"/conf/\" + filename) or \"nginx\" not in filename:\n" }, { "line_no": 44, "char_start": 1545, "char_end": 1546, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 1153, "char_end": 1184, "chars": "Analyze nginx conf\n # - " }, { "char_start": 1240, "char_end": 1292, "chars": " - Spot path traversal issue vulnerability\n #" }, { "char_start": 1363, "char_end": 1437, "chars": "# Ignore subdirs or filename not containing nginx in the name\n " }, { "char_start": 1491, "char_end": 1518, "chars": " or \"nginx\" not in filename" }, { "char_start": 1544, "char_end": 1606, "chars": "\n\n #\n # 'add_header' usage\n #" }, { "char_start": 2089, "char_end": 3888, "chars": "\n\n #\n # Path traversal issues\n #\n lines = open(self.path + \"/conf/\" + filename).readlines()\n lines = [line.strip() for line in lines if not line.strip().startswith(\"#\")]\n # Let's find the first location line\n location_line = None\n path_traversal_vulnerable = False\n lines_iter = lines.__iter__()\n for line in lines_iter:\n if line.startswith(\"location\"):\n location_line = line\n break\n # Look at the next lines for an 'alias' directive\n if location_line is not None:\n for line in lines_iter:\n if line.startswith(\"location\"):\n # Entering a new location block ... abort here\n # and assume there's no alias block later...\n break\n if line.startswith(\"alias\"):\n # We should definitely check for path traversal issue\n # Does the location target ends with / ?\n target = location_line.split()[-2]\n if not target.endswith(\"/\"):\n path_traversal_vulnerable = True\n break\n if path_traversal_vulnerable:\n print_warning(\n \"The nginx configuration appears vulnerable to path traversal as explained in \"\n \"https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/\\n\"\n \"To fix it, look at the first lines of the nginx conf of the example app : \"\n \"https://github.com/YunoHost/example_ynh/blob/master/conf/nginx.conf\"\n )" } ] }
github.com/YunoHost/package_linter/commit/f6e98894cfe841aedaa7efd590937f0255193913
package_linter.py
cwe-022
dd_save_binary
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size) { if (!dd->locked) error_msg_and_die("dump_dir is not opened"); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die("Cannot save binary. '%s' is not a valid file name", name); char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }
{ "deleted": [], "added": [ { "line_no": 6, "char_start": 179, "char_end": 219, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 7, "char_start": 219, "char_end": 305, "line": " error_msg_and_die(\"Cannot save binary. '%s' is not a valid file name\", name);\n" }, { "line_no": 8, "char_start": 305, "char_end": 306, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 183, "char_end": 310, "chars": "if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot save binary. '%s' is not a valid file name\", name);\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
pascal_case
def pascal_case(value: str) -> str: return stringcase.pascalcase(value)
def pascal_case(value: str) -> str: return stringcase.pascalcase(_sanitize(value))
{ "deleted": [ { "line_no": 2, "char_start": 36, "char_end": 75, "line": " return stringcase.pascalcase(value)\n" } ], "added": [ { "line_no": 2, "char_start": 36, "char_end": 86, "line": " return stringcase.pascalcase(_sanitize(value))\n" } ] }
{ "deleted": [], "added": [ { "char_start": 69, "char_end": 79, "chars": "_sanitize(" }, { "char_start": 85, "char_end": 86, "chars": ")" } ] }
github.com/openapi-generators/openapi-python-client/commit/3e7dfae5d0b3685abf1ede1bc6c086a116ac4746
openapi_python_client/utils.py
cwe-022
cleanup_pathname
cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
{ "deleted": [ { "line_no": 17, "char_start": 336, "char_end": 354, "line": "\tif (*src == '/')\n" } ], "added": [ { "line_no": 17, "char_start": 336, "char_end": 356, "line": "\tif (*src == '/') {\n" }, { "line_no": 18, "char_start": 356, "char_end": 415, "line": "\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n" }, { "line_no": 19, "char_start": 415, "char_end": 469, "line": "\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n" }, { "line_no": 20, "char_start": 469, "char_end": 511, "line": "\t\t\t \"Path is absolute\");\n" }, { "line_no": 21, "char_start": 511, "char_end": 539, "line": "\t\t\treturn (ARCHIVE_FAILED);\n" }, { "line_no": 22, "char_start": 539, "char_end": 543, "line": "\t\t}\n" }, { "line_no": 23, "char_start": 543, "char_end": 544, "line": "\n" }, { "line_no": 25, "char_start": 566, "char_end": 569, "line": "\t}\n" } ] }
{ "deleted": [], "added": [ { "char_start": 353, "char_end": 543, "chars": " {\n\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Path is absolute\");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n" }, { "char_start": 565, "char_end": 568, "chars": "\n\t}" } ] }
github.com/libarchive/libarchive/commit/59357157706d47c365b2227739e17daba3607526
libarchive/archive_write_disk_posix.c
cwe-022
create_dump_dir_from_problem_data
struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name) { INITIALIZE_LIBREPORT(); char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER); if (!type) { error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER); return NULL; } uid_t uid = (uid_t)-1L; char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID); if (uid_str) { char *endptr; errno = 0; long val = strtol(uid_str, &endptr, 10); if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val) { error_msg(_("uid value is not valid: '%s'"), uid_str); return NULL; } uid = (uid_t)val; } struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { perror_msg("gettimeofday()"); return NULL; } char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid()); log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid); struct dump_dir *dd; if (base_dir_name) dd = try_dd_create(base_dir_name, problem_id, uid); else { /* Try /var/run/abrt */ dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid); /* Try $HOME/tmp */ if (!dd) { char *home = getenv("HOME"); if (home && home[0]) { home = concat_path_file(home, "tmp"); /*mkdir(home, 0777); - do we want this? */ dd = try_dd_create(home, problem_id, uid); free(home); } } //TODO: try user's home dir obtained by getpwuid(getuid())? /* Try system temporary directory */ if (!dd) dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid); } if (!dd) /* try_dd_create() already emitted the error message */ goto ret; GHashTableIter iter; char *name; struct problem_item *value; g_hash_table_iter_init(&iter, problem_data); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value)) { if (value->flags & CD_FLAG_BIN) { char *dest = concat_path_file(dd->dd_dirname, name); log_info("copying '%s' to '%s'", value->content, dest); off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH); if (copied < 0) error_msg("Can't copy %s to %s", value->content, dest); else log_info("copied %li bytes", (unsigned long)copied); free(dest); continue; } /* only files should contain '/' and those are handled earlier */ if (name[0] == '.' || strchr(name, '/')) { error_msg("Problem data field name contains disallowed chars: '%s'", name); continue; } dd_save_text(dd, name, value->content); } /* need to create basic files AFTER we save the pd to dump_dir * otherwise we can't skip already created files like in case when * reporting from anaconda where we can't read /etc/{system,redhat}-release * and os_release is taken from anaconda */ dd_create_basic_files(dd, uid, NULL); problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0'; char* new_path = concat_path_file(base_dir_name, problem_id); log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path); dd_rename(dd, new_path); ret: free(problem_id); return dd; }
struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name) { INITIALIZE_LIBREPORT(); char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER); if (!type) { error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER); return NULL; } if (!str_is_correct_filename(type)) { error_msg(_("'%s' is not correct file name"), FILENAME_ANALYZER); return NULL; } uid_t uid = (uid_t)-1L; char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID); if (uid_str) { char *endptr; errno = 0; long val = strtol(uid_str, &endptr, 10); if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val) { error_msg(_("uid value is not valid: '%s'"), uid_str); return NULL; } uid = (uid_t)val; } struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { perror_msg("gettimeofday()"); return NULL; } char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid()); log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid); struct dump_dir *dd; if (base_dir_name) dd = try_dd_create(base_dir_name, problem_id, uid); else { /* Try /var/run/abrt */ dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid); /* Try $HOME/tmp */ if (!dd) { char *home = getenv("HOME"); if (home && home[0]) { home = concat_path_file(home, "tmp"); /*mkdir(home, 0777); - do we want this? */ dd = try_dd_create(home, problem_id, uid); free(home); } } //TODO: try user's home dir obtained by getpwuid(getuid())? /* Try system temporary directory */ if (!dd) dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid); } if (!dd) /* try_dd_create() already emitted the error message */ goto ret; GHashTableIter iter; char *name; struct problem_item *value; g_hash_table_iter_init(&iter, problem_data); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value)) { if (!str_is_correct_filename(name)) { error_msg("Problem data field name contains disallowed chars: '%s'", name); continue; } if (value->flags & CD_FLAG_BIN) { char *dest = concat_path_file(dd->dd_dirname, name); log_info("copying '%s' to '%s'", value->content, dest); off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH); if (copied < 0) error_msg("Can't copy %s to %s", value->content, dest); else log_info("copied %li bytes", (unsigned long)copied); free(dest); continue; } dd_save_text(dd, name, value->content); } /* need to create basic files AFTER we save the pd to dump_dir * otherwise we can't skip already created files like in case when * reporting from anaconda where we can't read /etc/{system,redhat}-release * and os_release is taken from anaconda */ dd_create_basic_files(dd, uid, NULL); problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0'; char* new_path = concat_path_file(base_dir_name, problem_id); log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path); dd_rename(dd, new_path); ret: free(problem_id); return dd; }
{ "deleted": [ { "line_no": 90, "char_start": 2743, "char_end": 2817, "line": " /* only files should contain '/' and those are handled earlier */\n" }, { "line_no": 91, "char_start": 2817, "char_end": 2866, "line": " if (name[0] == '.' || strchr(name, '/'))\n" }, { "line_no": 92, "char_start": 2866, "char_end": 2876, "line": " {\n" }, { "line_no": 93, "char_start": 2876, "char_end": 2964, "line": " error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n" }, { "line_no": 94, "char_start": 2964, "char_end": 2986, "line": " continue;\n" }, { "line_no": 95, "char_start": 2986, "char_end": 2996, "line": " }\n" }, { "line_no": 96, "char_start": 2996, "char_end": 2997, "line": "\n" } ], "added": [ { "line_no": 13, "char_start": 345, "char_end": 385, "line": " if (!str_is_correct_filename(type))\n" }, { "line_no": 14, "char_start": 385, "char_end": 391, "line": " {\n" }, { "line_no": 15, "char_start": 391, "char_end": 465, "line": " error_msg(_(\"'%s' is not correct file name\"), FILENAME_ANALYZER);\n" }, { "line_no": 16, "char_start": 465, "char_end": 486, "line": " return NULL;\n" }, { "line_no": 17, "char_start": 486, "char_end": 492, "line": " }\n" }, { "line_no": 18, "char_start": 492, "char_end": 493, "line": "\n" }, { "line_no": 82, "char_start": 2371, "char_end": 2415, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 83, "char_start": 2415, "char_end": 2425, "line": " {\n" }, { "line_no": 84, "char_start": 2425, "char_end": 2513, "line": " error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n" }, { "line_no": 85, "char_start": 2513, "char_end": 2535, "line": " continue;\n" }, { "line_no": 86, "char_start": 2535, "char_end": 2545, "line": " }\n" }, { "line_no": 87, "char_start": 2545, "char_end": 2546, "line": "\n" } ] }
{ "deleted": [ { "char_start": 2709, "char_end": 2963, "chars": "\n continue;\n }\n\n /* only files should contain '/' and those are handled earlier */\n if (name[0] == '.' || strchr(name, '/'))\n {\n error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);" } ], "added": [ { "char_start": 349, "char_end": 497, "chars": "if (!str_is_correct_filename(type))\n {\n error_msg(_(\"'%s' is not correct file name\"), FILENAME_ANALYZER);\n return NULL;\n }\n\n " }, { "char_start": 2383, "char_end": 2558, "chars": "!str_is_correct_filename(name))\n {\n error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n continue;\n }\n\n if (" } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/create_dump_dir.c
cwe-022
list
def list(self, keyfilter='/'): path = os.path.join(self.namespace, keyfilter) if path != '/': path = path.rstrip('/') try: result = self.etcd.read(path, recursive=True) except etcd.EtcdKeyNotFound: return None except etcd.EtcdException as err: log_error("Error listing %s: [%r]" % (keyfilter, repr(err))) raise CSStoreError('Error occurred while trying to list keys') value = set() for entry in result.get_subtree(): if entry.key == path: continue name = entry.key[len(path):] if entry.dir and not name.endswith('/'): name += '/' value.add(name.lstrip('/')) return sorted(value)
def list(self, keyfilter='/'): path = self._absolute_key(keyfilter) if path != '/': path = path.rstrip('/') try: result = self.etcd.read(path, recursive=True) except etcd.EtcdKeyNotFound: return None except etcd.EtcdException as err: log_error("Error listing %s: [%r]" % (keyfilter, repr(err))) raise CSStoreError('Error occurred while trying to list keys') value = set() for entry in result.get_subtree(): if entry.key == path: continue name = entry.key[len(path):] if entry.dir and not name.endswith('/'): name += '/' value.add(name.lstrip('/')) return sorted(value)
{ "deleted": [ { "line_no": 2, "char_start": 35, "char_end": 90, "line": " path = os.path.join(self.namespace, keyfilter)\n" } ], "added": [ { "line_no": 2, "char_start": 35, "char_end": 80, "line": " path = self._absolute_key(keyfilter)\n" } ] }
{ "deleted": [ { "char_start": 50, "char_end": 63, "chars": "os.path.join(" }, { "char_start": 68, "char_end": 69, "chars": "n" }, { "char_start": 70, "char_end": 72, "chars": "me" }, { "char_start": 73, "char_end": 76, "chars": "pac" }, { "char_start": 77, "char_end": 79, "chars": ", " } ], "added": [ { "char_start": 55, "char_end": 56, "chars": "_" }, { "char_start": 57, "char_end": 63, "chars": "bsolut" }, { "char_start": 64, "char_end": 66, "chars": "_k" }, { "char_start": 67, "char_end": 69, "chars": "y(" } ] }
github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4
custodia/store/etcdstore.py
cwe-022
process
local void process(char *path) { int method = -1; /* get_header() return value */ size_t len; /* length of base name (minus suffix) */ struct stat st; /* to get file type and mod time */ /* all compressed suffixes for decoding search, in length order */ static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz", ".zip", ".ZIP", ".tgz", NULL}; /* open input file with name in, descriptor ind -- set name and mtime */ if (path == NULL) { strcpy(g.inf, "<stdin>"); g.ind = 0; g.name = NULL; g.mtime = g.headis & 2 ? (fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0; len = 0; } else { /* set input file name (already set if recursed here) */ if (path != g.inf) { strncpy(g.inf, path, sizeof(g.inf)); if (g.inf[sizeof(g.inf) - 1]) bail("name too long: ", path); } len = strlen(g.inf); /* try to stat input file -- if not there and decoding, look for that name with compressed suffixes */ if (lstat(g.inf, &st)) { if (errno == ENOENT && (g.list || g.decode)) { char **try = sufs; do { if (*try == NULL || len + strlen(*try) >= sizeof(g.inf)) break; strcpy(g.inf + len, *try++); errno = 0; } while (lstat(g.inf, &st) && errno == ENOENT); } #ifdef EOVERFLOW if (errno == EOVERFLOW || errno == EFBIG) bail(g.inf, " too large -- not compiled with large file support"); #endif if (errno) { g.inf[len] = 0; complain("%s does not exist -- skipping", g.inf); return; } len = strlen(g.inf); } /* only process regular files, but allow symbolic links if -f, recurse into directory if -r */ if ((st.st_mode & S_IFMT) != S_IFREG && (st.st_mode & S_IFMT) != S_IFLNK && (st.st_mode & S_IFMT) != S_IFDIR) { complain("%s is a special file or device -- skipping", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) { complain("%s is a symbolic link -- skipping", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) { complain("%s is a directory -- skipping", g.inf); return; } /* recurse into directory (assumes Unix) */ if ((st.st_mode & S_IFMT) == S_IFDIR) { char *roll, *item, *cut, *base, *bigger; size_t len, hold; DIR *here; struct dirent *next; /* accumulate list of entries (need to do this, since readdir() behavior not defined if directory modified between calls) */ here = opendir(g.inf); if (here == NULL) return; hold = 512; roll = MALLOC(hold); if (roll == NULL) bail("not enough memory", ""); *roll = 0; item = roll; while ((next = readdir(here)) != NULL) { if (next->d_name[0] == 0 || (next->d_name[0] == '.' && (next->d_name[1] == 0 || (next->d_name[1] == '.' && next->d_name[2] == 0)))) continue; len = strlen(next->d_name) + 1; if (item + len + 1 > roll + hold) { do { /* make roll bigger */ hold <<= 1; } while (item + len + 1 > roll + hold); bigger = REALLOC(roll, hold); if (bigger == NULL) { FREE(roll); bail("not enough memory", ""); } item = bigger + (item - roll); roll = bigger; } strcpy(item, next->d_name); item += len; *item = 0; } closedir(here); /* run process() for each entry in the directory */ cut = base = g.inf + strlen(g.inf); if (base > g.inf && base[-1] != (unsigned char)'/') { if ((size_t)(base - g.inf) >= sizeof(g.inf)) bail("path too long", g.inf); *base++ = '/'; } item = roll; while (*item) { strncpy(base, item, sizeof(g.inf) - (base - g.inf)); if (g.inf[sizeof(g.inf) - 1]) { strcpy(g.inf + (sizeof(g.inf) - 4), "..."); bail("path too long: ", g.inf); } process(g.inf); item += strlen(item) + 1; } *cut = 0; /* release list of entries */ FREE(roll); return; } /* don't compress .gz (or provided suffix) files, unless -f */ if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) && strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) { complain("%s ends with %s -- skipping", g.inf, g.sufx); return; } /* create output file only if input file has compressed suffix */ if (g.decode == 1 && !g.pipeout && !g.list) { int suf = compressed_suffix(g.inf); if (suf == 0) { complain("%s does not have compressed suffix -- skipping", g.inf); return; } len -= suf; } /* open input file */ g.ind = open(g.inf, O_RDONLY, 0); if (g.ind < 0) bail("read error on ", g.inf); /* prepare gzip header information for compression */ g.name = g.headis & 1 ? justname(g.inf) : NULL; g.mtime = g.headis & 2 ? st.st_mtime : 0; } SET_BINARY_MODE(g.ind); /* if decoding or testing, try to read gzip header */ g.hname = NULL; if (g.decode) { in_init(); method = get_header(1); if (method != 8 && method != 257 && /* gzip -cdf acts like cat on uncompressed input */ !(method == -2 && g.force && g.pipeout && g.decode != 2 && !g.list)) { RELEASE(g.hname); if (g.ind != 0) close(g.ind); if (method != -1) complain(method < 0 ? "%s is not compressed -- skipping" : "%s has unknown compression method -- skipping", g.inf); return; } /* if requested, test input file (possibly a special list) */ if (g.decode == 2) { if (method == 8) infchk(); else { unlzw(); if (g.list) { g.in_tot -= 3; show_info(method, 0, g.out_tot, 0); } } RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } } /* if requested, just list information about input file */ if (g.list) { list_info(); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* create output file out, descriptor outd */ if (path == NULL || g.pipeout) { /* write to stdout */ g.outf = MALLOC(strlen("<stdout>") + 1); if (g.outf == NULL) bail("not enough memory", ""); strcpy(g.outf, "<stdout>"); g.outd = 1; if (!g.decode && !g.force && isatty(g.outd)) bail("trying to write compressed data to a terminal", " (use -f to force)"); } else { char *to, *repl; /* use header name for output when decompressing with -N */ to = g.inf; if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) { to = g.hname; len = strlen(g.hname); } /* replace .tgz with .tar when decoding */ repl = g.decode && strcmp(to + len, ".tgz") ? "" : ".tar"; /* create output file and open to write */ g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1); if (g.outf == NULL) bail("not enough memory", ""); memcpy(g.outf, to, len); strcpy(g.outf + len, g.decode ? repl : g.sufx); g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY | (g.force ? 0 : O_EXCL), 0600); /* if exists and not -f, give user a chance to overwrite */ if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) { int ch, reply; fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf); fflush(stderr); reply = -1; do { ch = getchar(); if (reply < 0 && ch != ' ' && ch != '\t') reply = ch == 'y' || ch == 'Y' ? 1 : 0; } while (ch != EOF && ch != '\n' && ch != '\r'); if (reply == 1) g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY, 0600); } /* if exists and no overwrite, report and go on to next */ if (g.outd < 0 && errno == EEXIST) { complain("%s exists -- skipping", g.outf); RELEASE(g.outf); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* if some other error, give up */ if (g.outd < 0) bail("write error on ", g.outf); } SET_BINARY_MODE(g.outd); RELEASE(g.hname); /* process ind to outd */ if (g.verbosity > 1) fprintf(stderr, "%s to %s ", g.inf, g.outf); if (g.decode) { if (method == 8) infchk(); else if (method == 257) unlzw(); else cat(); } #ifndef NOTHREAD else if (g.procs > 1) parallel_compress(); #endif else single_compress(0); if (g.verbosity > 1) { putc('\n', stderr); fflush(stderr); } /* finish up, copy attributes, set times, delete original */ if (g.ind != 0) close(g.ind); if (g.outd != 1) { if (close(g.outd)) bail("write error on ", g.outf); g.outd = -1; /* now prevent deletion on interrupt */ if (g.ind != 0) { copymeta(g.inf, g.outf); if (!g.keep) unlink(g.inf); } if (g.decode && (g.headis & 2) != 0 && g.stamp) touch(g.outf, g.stamp); } RELEASE(g.outf); }
local void process(char *path) { int method = -1; /* get_header() return value */ size_t len; /* length of base name (minus suffix) */ struct stat st; /* to get file type and mod time */ /* all compressed suffixes for decoding search, in length order */ static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz", ".zip", ".ZIP", ".tgz", NULL}; /* open input file with name in, descriptor ind -- set name and mtime */ if (path == NULL) { strcpy(g.inf, "<stdin>"); g.ind = 0; g.name = NULL; g.mtime = g.headis & 2 ? (fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0; len = 0; } else { /* set input file name (already set if recursed here) */ if (path != g.inf) { strncpy(g.inf, path, sizeof(g.inf)); if (g.inf[sizeof(g.inf) - 1]) bail("name too long: ", path); } len = strlen(g.inf); /* try to stat input file -- if not there and decoding, look for that name with compressed suffixes */ if (lstat(g.inf, &st)) { if (errno == ENOENT && (g.list || g.decode)) { char **try = sufs; do { if (*try == NULL || len + strlen(*try) >= sizeof(g.inf)) break; strcpy(g.inf + len, *try++); errno = 0; } while (lstat(g.inf, &st) && errno == ENOENT); } #ifdef EOVERFLOW if (errno == EOVERFLOW || errno == EFBIG) bail(g.inf, " too large -- not compiled with large file support"); #endif if (errno) { g.inf[len] = 0; complain("%s does not exist -- skipping", g.inf); return; } len = strlen(g.inf); } /* only process regular files, but allow symbolic links if -f, recurse into directory if -r */ if ((st.st_mode & S_IFMT) != S_IFREG && (st.st_mode & S_IFMT) != S_IFLNK && (st.st_mode & S_IFMT) != S_IFDIR) { complain("%s is a special file or device -- skipping", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) { complain("%s is a symbolic link -- skipping", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) { complain("%s is a directory -- skipping", g.inf); return; } /* recurse into directory (assumes Unix) */ if ((st.st_mode & S_IFMT) == S_IFDIR) { char *roll, *item, *cut, *base, *bigger; size_t len, hold; DIR *here; struct dirent *next; /* accumulate list of entries (need to do this, since readdir() behavior not defined if directory modified between calls) */ here = opendir(g.inf); if (here == NULL) return; hold = 512; roll = MALLOC(hold); if (roll == NULL) bail("not enough memory", ""); *roll = 0; item = roll; while ((next = readdir(here)) != NULL) { if (next->d_name[0] == 0 || (next->d_name[0] == '.' && (next->d_name[1] == 0 || (next->d_name[1] == '.' && next->d_name[2] == 0)))) continue; len = strlen(next->d_name) + 1; if (item + len + 1 > roll + hold) { do { /* make roll bigger */ hold <<= 1; } while (item + len + 1 > roll + hold); bigger = REALLOC(roll, hold); if (bigger == NULL) { FREE(roll); bail("not enough memory", ""); } item = bigger + (item - roll); roll = bigger; } strcpy(item, next->d_name); item += len; *item = 0; } closedir(here); /* run process() for each entry in the directory */ cut = base = g.inf + strlen(g.inf); if (base > g.inf && base[-1] != (unsigned char)'/') { if ((size_t)(base - g.inf) >= sizeof(g.inf)) bail("path too long", g.inf); *base++ = '/'; } item = roll; while (*item) { strncpy(base, item, sizeof(g.inf) - (base - g.inf)); if (g.inf[sizeof(g.inf) - 1]) { strcpy(g.inf + (sizeof(g.inf) - 4), "..."); bail("path too long: ", g.inf); } process(g.inf); item += strlen(item) + 1; } *cut = 0; /* release list of entries */ FREE(roll); return; } /* don't compress .gz (or provided suffix) files, unless -f */ if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) && strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) { complain("%s ends with %s -- skipping", g.inf, g.sufx); return; } /* create output file only if input file has compressed suffix */ if (g.decode == 1 && !g.pipeout && !g.list) { int suf = compressed_suffix(g.inf); if (suf == 0) { complain("%s does not have compressed suffix -- skipping", g.inf); return; } len -= suf; } /* open input file */ g.ind = open(g.inf, O_RDONLY, 0); if (g.ind < 0) bail("read error on ", g.inf); /* prepare gzip header information for compression */ g.name = g.headis & 1 ? justname(g.inf) : NULL; g.mtime = g.headis & 2 ? st.st_mtime : 0; } SET_BINARY_MODE(g.ind); /* if decoding or testing, try to read gzip header */ g.hname = NULL; if (g.decode) { in_init(); method = get_header(1); if (method != 8 && method != 257 && /* gzip -cdf acts like cat on uncompressed input */ !(method == -2 && g.force && g.pipeout && g.decode != 2 && !g.list)) { RELEASE(g.hname); if (g.ind != 0) close(g.ind); if (method != -1) complain(method < 0 ? "%s is not compressed -- skipping" : "%s has unknown compression method -- skipping", g.inf); return; } /* if requested, test input file (possibly a special list) */ if (g.decode == 2) { if (method == 8) infchk(); else { unlzw(); if (g.list) { g.in_tot -= 3; show_info(method, 0, g.out_tot, 0); } } RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } } /* if requested, just list information about input file */ if (g.list) { list_info(); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* create output file out, descriptor outd */ if (path == NULL || g.pipeout) { /* write to stdout */ g.outf = MALLOC(strlen("<stdout>") + 1); if (g.outf == NULL) bail("not enough memory", ""); strcpy(g.outf, "<stdout>"); g.outd = 1; if (!g.decode && !g.force && isatty(g.outd)) bail("trying to write compressed data to a terminal", " (use -f to force)"); } else { char *to = g.inf, *sufx = ""; size_t pre = 0; /* select parts of the output file name */ if (g.decode) { /* for -dN or -dNT, use the path from the input file and the name from the header, stripping any path in the header name */ if ((g.headis & 1) != 0 && g.hname != NULL) { pre = justname(g.inf) - g.inf; to = justname(g.hname); len = strlen(to); } /* for -d or -dNn, replace abbreviated suffixes */ else if (strcmp(to + len, ".tgz") == 0) sufx = ".tar"; } else /* add appropriate suffix when compressing */ sufx = g.sufx; /* create output file and open to write */ g.outf = MALLOC(pre + len + strlen(sufx) + 1); if (g.outf == NULL) bail("not enough memory", ""); memcpy(g.outf, g.inf, pre); memcpy(g.outf + pre, to, len); strcpy(g.outf + pre + len, sufx); g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY | (g.force ? 0 : O_EXCL), 0600); /* if exists and not -f, give user a chance to overwrite */ if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) { int ch, reply; fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf); fflush(stderr); reply = -1; do { ch = getchar(); if (reply < 0 && ch != ' ' && ch != '\t') reply = ch == 'y' || ch == 'Y' ? 1 : 0; } while (ch != EOF && ch != '\n' && ch != '\r'); if (reply == 1) g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY, 0600); } /* if exists and no overwrite, report and go on to next */ if (g.outd < 0 && errno == EEXIST) { complain("%s exists -- skipping", g.outf); RELEASE(g.outf); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* if some other error, give up */ if (g.outd < 0) bail("write error on ", g.outf); } SET_BINARY_MODE(g.outd); RELEASE(g.hname); /* process ind to outd */ if (g.verbosity > 1) fprintf(stderr, "%s to %s ", g.inf, g.outf); if (g.decode) { if (method == 8) infchk(); else if (method == 257) unlzw(); else cat(); } #ifndef NOTHREAD else if (g.procs > 1) parallel_compress(); #endif else single_compress(0); if (g.verbosity > 1) { putc('\n', stderr); fflush(stderr); } /* finish up, copy attributes, set times, delete original */ if (g.ind != 0) close(g.ind); if (g.outd != 1) { if (close(g.outd)) bail("write error on ", g.outf); g.outd = -1; /* now prevent deletion on interrupt */ if (g.ind != 0) { copymeta(g.inf, g.outf); if (!g.keep) unlink(g.inf); } if (g.decode && (g.headis & 2) != 0 && g.stamp) touch(g.outf, g.stamp); } RELEASE(g.outf); }
{ "deleted": [ { "line_no": 224, "char_start": 8033, "char_end": 8058, "line": " char *to, *repl;\n" }, { "line_no": 225, "char_start": 8058, "char_end": 8059, "line": "\n" }, { "line_no": 226, "char_start": 8059, "char_end": 8127, "line": " /* use header name for output when decompressing with -N */\n" }, { "line_no": 227, "char_start": 8127, "char_end": 8147, "line": " to = g.inf;\n" }, { "line_no": 228, "char_start": 8147, "char_end": 8213, "line": " if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {\n" }, { "line_no": 229, "char_start": 8213, "char_end": 8239, "line": " to = g.hname;\n" }, { "line_no": 230, "char_start": 8239, "char_end": 8274, "line": " len = strlen(g.hname);\n" }, { "line_no": 232, "char_start": 8284, "char_end": 8285, "line": "\n" }, { "line_no": 233, "char_start": 8285, "char_end": 8336, "line": " /* replace .tgz with .tar when decoding */\n" }, { "line_no": 234, "char_start": 8336, "char_end": 8403, "line": " repl = g.decode && strcmp(to + len, \".tgz\") ? \"\" : \".tar\";\n" }, { "line_no": 237, "char_start": 8455, "char_end": 8534, "line": " g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);\n" }, { "line_no": 240, "char_start": 8605, "char_end": 8638, "line": " memcpy(g.outf, to, len);\n" }, { "line_no": 241, "char_start": 8638, "char_end": 8694, "line": " strcpy(g.outf + len, g.decode ? repl : g.sufx);\n" }, { "line_no": 243, "char_start": 8755, "char_end": 8815, "line": " (g.force ? 0 : O_EXCL), 0600);\n" } ], "added": [ { "line_no": 224, "char_start": 8033, "char_end": 8071, "line": " char *to = g.inf, *sufx = \"\";\n" }, { "line_no": 225, "char_start": 8071, "char_end": 8095, "line": " size_t pre = 0;\n" }, { "line_no": 226, "char_start": 8095, "char_end": 8096, "line": "\n" }, { "line_no": 227, "char_start": 8096, "char_end": 8147, "line": " /* select parts of the output file name */\n" }, { "line_no": 228, "char_start": 8147, "char_end": 8171, "line": " if (g.decode) {\n" }, { "line_no": 229, "char_start": 8171, "char_end": 8249, "line": " /* for -dN or -dNT, use the path from the input file and the name\n" }, { "line_no": 230, "char_start": 8249, "char_end": 8322, "line": " from the header, stripping any path in the header name */\n" }, { "line_no": 231, "char_start": 8322, "char_end": 8380, "line": " if ((g.headis & 1) != 0 && g.hname != NULL) {\n" }, { "line_no": 232, "char_start": 8380, "char_end": 8427, "line": " pre = justname(g.inf) - g.inf;\n" }, { "line_no": 233, "char_start": 8427, "char_end": 8467, "line": " to = justname(g.hname);\n" }, { "line_no": 234, "char_start": 8467, "char_end": 8501, "line": " len = strlen(to);\n" }, { "line_no": 235, "char_start": 8501, "char_end": 8515, "line": " }\n" }, { "line_no": 236, "char_start": 8515, "char_end": 8578, "line": " /* for -d or -dNn, replace abbreviated suffixes */\n" }, { "line_no": 237, "char_start": 8578, "char_end": 8630, "line": " else if (strcmp(to + len, \".tgz\") == 0)\n" }, { "line_no": 238, "char_start": 8630, "char_end": 8661, "line": " sufx = \".tar\";\n" }, { "line_no": 240, "char_start": 8671, "char_end": 8684, "line": " else\n" }, { "line_no": 241, "char_start": 8684, "char_end": 8742, "line": " /* add appropriate suffix when compressing */\n" }, { "line_no": 242, "char_start": 8742, "char_end": 8769, "line": " sufx = g.sufx;\n" }, { "line_no": 245, "char_start": 8821, "char_end": 8876, "line": " g.outf = MALLOC(pre + len + strlen(sufx) + 1);\n" }, { "line_no": 248, "char_start": 8947, "char_end": 8983, "line": " memcpy(g.outf, g.inf, pre);\n" }, { "line_no": 249, "char_start": 8983, "char_end": 9022, "line": " memcpy(g.outf + pre, to, len);\n" }, { "line_no": 250, "char_start": 9022, "char_end": 9064, "line": " strcpy(g.outf + pre + len, sufx);\n" }, { "line_no": 252, "char_start": 9125, "char_end": 9186, "line": " (g.force ? 0 : O_EXCL), 0600);\n" } ] }
{ "deleted": [ { "char_start": 8052, "char_end": 8053, "chars": "r" }, { "char_start": 8055, "char_end": 8056, "chars": "l" }, { "char_start": 8070, "char_end": 8071, "chars": "u" }, { "char_start": 8076, "char_end": 8078, "chars": "ad" }, { "char_start": 8079, "char_end": 8080, "chars": "r" }, { "char_start": 8094, "char_end": 8095, "chars": "u" }, { "char_start": 8096, "char_end": 8098, "chars": " w" }, { "char_start": 8099, "char_end": 8101, "chars": "en" }, { "char_start": 8102, "char_end": 8105, "chars": "dec" }, { "char_start": 8107, "char_end": 8109, "chars": "pr" }, { "char_start": 8110, "char_end": 8112, "chars": "ss" }, { "char_start": 8114, "char_end": 8115, "chars": "g" }, { "char_start": 8116, "char_end": 8117, "chars": "w" }, { "char_start": 8120, "char_end": 8123, "chars": " -N" }, { "char_start": 8124, "char_end": 8126, "chars": "*/" }, { "char_start": 8135, "char_end": 8136, "chars": "t" }, { "char_start": 8138, "char_end": 8139, "chars": "=" }, { "char_start": 8141, "char_end": 8142, "chars": "." }, { "char_start": 8144, "char_end": 8146, "chars": "f;" }, { "char_start": 8159, "char_end": 8171, "chars": "g.decode && " }, { "char_start": 8264, "char_end": 8271, "chars": "g.hname" }, { "char_start": 8283, "char_end": 8284, "chars": "\n" }, { "char_start": 8304, "char_end": 8316, "chars": ".tgz with .t" }, { "char_start": 8318, "char_end": 8321, "chars": " wh" }, { "char_start": 8322, "char_end": 8325, "chars": "n d" }, { "char_start": 8326, "char_end": 8328, "chars": "co" }, { "char_start": 8330, "char_end": 8332, "chars": "ng" }, { "char_start": 8344, "char_end": 8348, "chars": "repl" }, { "char_start": 8349, "char_end": 8350, "chars": "=" }, { "char_start": 8351, "char_end": 8354, "chars": "g.d" }, { "char_start": 8355, "char_end": 8358, "chars": "cod" }, { "char_start": 8360, "char_end": 8362, "chars": "&&" }, { "char_start": 8388, "char_end": 8389, "chars": "?" }, { "char_start": 8390, "char_end": 8392, "chars": "\"\"" }, { "char_start": 8393, "char_end": 8394, "chars": ":" }, { "char_start": 8479, "char_end": 8480, "chars": "l" }, { "char_start": 8481, "char_end": 8482, "chars": "n" }, { "char_start": 8485, "char_end": 8500, "chars": "(g.decode ? str" }, { "char_start": 8503, "char_end": 8509, "chars": "(repl)" }, { "char_start": 8510, "char_end": 8511, "chars": ":" }, { "char_start": 8519, "char_end": 8521, "chars": "g." }, { "char_start": 8525, "char_end": 8526, "chars": ")" }, { "char_start": 8628, "char_end": 8630, "chars": "to" }, { "char_start": 8632, "char_end": 8633, "chars": "l" }, { "char_start": 8634, "char_end": 8635, "chars": "n" }, { "char_start": 8646, "char_end": 8649, "chars": "str" }, { "char_start": 8665, "char_end": 8666, "chars": "," }, { "char_start": 8669, "char_end": 8672, "chars": "dec" }, { "char_start": 8673, "char_end": 8675, "chars": "de" }, { "char_start": 8676, "char_end": 8677, "chars": "?" }, { "char_start": 8680, "char_end": 8682, "chars": "pl" }, { "char_start": 8683, "char_end": 8684, "chars": ":" }, { "char_start": 8685, "char_end": 8687, "chars": "g." } ], "added": [ { "char_start": 8049, "char_end": 8057, "chars": " = g.inf" }, { "char_start": 8060, "char_end": 8087, "chars": "sufx = \"\";\n size_t p" }, { "char_start": 8089, "char_end": 8093, "chars": " = 0" }, { "char_start": 8109, "char_end": 8113, "chars": "lect" }, { "char_start": 8114, "char_end": 8124, "chars": "parts of t" }, { "char_start": 8126, "char_end": 8137, "chars": " output fil" }, { "char_start": 8144, "char_end": 8186, "chars": "*/\n if (g.decode) {\n /* " }, { "char_start": 8190, "char_end": 8194, "chars": "-dN " }, { "char_start": 8195, "char_end": 8203, "chars": "r -dNT, " }, { "char_start": 8204, "char_end": 8207, "chars": "se " }, { "char_start": 8208, "char_end": 8211, "chars": "he " }, { "char_start": 8212, "char_end": 8213, "chars": "a" }, { "char_start": 8216, "char_end": 8218, "chars": "fr" }, { "char_start": 8220, "char_end": 8223, "chars": " th" }, { "char_start": 8224, "char_end": 8225, "chars": " " }, { "char_start": 8227, "char_end": 8230, "chars": "put" }, { "char_start": 8231, "char_end": 8232, "chars": "f" }, { "char_start": 8233, "char_end": 8240, "chars": "le and " }, { "char_start": 8242, "char_end": 8250, "chars": "e name\n " }, { "char_start": 8259, "char_end": 8269, "chars": " from " }, { "char_start": 8270, "char_end": 8272, "chars": "he" }, { "char_start": 8273, "char_end": 8280, "chars": "header," }, { "char_start": 8281, "char_end": 8289, "chars": "strippin" }, { "char_start": 8290, "char_end": 8300, "chars": " any path " }, { "char_start": 8302, "char_end": 8321, "chars": " the header name */" }, { "char_start": 8322, "char_end": 8326, "chars": " " }, { "char_start": 8392, "char_end": 8443, "chars": " pre = justname(g.inf) - g.inf;\n " }, { "char_start": 8448, "char_end": 8457, "chars": "justname(" }, { "char_start": 8464, "char_end": 8465, "chars": ")" }, { "char_start": 8467, "char_end": 8471, "chars": " " }, { "char_start": 8496, "char_end": 8498, "chars": "to" }, { "char_start": 8509, "char_end": 8513, "chars": " " }, { "char_start": 8515, "char_end": 8519, "chars": " " }, { "char_start": 8530, "char_end": 8546, "chars": "for -d or -dNn, " }, { "char_start": 8555, "char_end": 8557, "chars": "bb" }, { "char_start": 8559, "char_end": 8563, "chars": "viat" }, { "char_start": 8565, "char_end": 8570, "chars": " suff" }, { "char_start": 8571, "char_end": 8574, "chars": "xes" }, { "char_start": 8586, "char_end": 8588, "chars": " " }, { "char_start": 8591, "char_end": 8593, "chars": "ls" }, { "char_start": 8595, "char_end": 8597, "chars": "if" }, { "char_start": 8598, "char_end": 8599, "chars": "(" }, { "char_start": 8624, "char_end": 8645, "chars": "== 0)\n " }, { "char_start": 8646, "char_end": 8650, "chars": "sufx" }, { "char_start": 8651, "char_end": 8652, "chars": "=" }, { "char_start": 8661, "char_end": 8769, "chars": " }\n else\n /* add appropriate suffix when compressing */\n sufx = g.sufx;\n" }, { "char_start": 8845, "char_end": 8847, "chars": "pr" }, { "char_start": 8855, "char_end": 8856, "chars": "+" }, { "char_start": 8970, "char_end": 8975, "chars": "g.inf" }, { "char_start": 8977, "char_end": 8979, "chars": "pr" }, { "char_start": 8991, "char_end": 8994, "chars": "mem" }, { "char_start": 9006, "char_end": 9015, "chars": " pre, to," }, { "char_start": 9019, "char_end": 9029, "chars": ");\n " }, { "char_start": 9030, "char_end": 9037, "chars": "strcpy(" }, { "char_start": 9040, "char_end": 9043, "chars": "utf" }, { "char_start": 9044, "char_end": 9045, "chars": "+" }, { "char_start": 9046, "char_end": 9047, "chars": "p" }, { "char_start": 9049, "char_end": 9052, "chars": " + " }, { "char_start": 9053, "char_end": 9056, "chars": "en," }, { "char_start": 9125, "char_end": 9126, "chars": " " } ] }
github.com/madler/pigz/commit/fdad1406b3ec809f4954ff7cdf9e99eb18c2458f
pigz.c
cwe-022
imap_hcache_open
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); }
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } if (strstr(mbox, "/../") || (strcmp(mbox, "..") == 0) || (strncmp(mbox, "../", 3) == 0)) return NULL; size_t len = strlen(mbox); if ((len > 3) && (strcmp(mbox + len - 3, "/..") == 0)) return NULL; mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); }
{ "deleted": [], "added": [ { "line_no": 19, "char_start": 413, "char_end": 504, "line": " if (strstr(mbox, \"/../\") || (strcmp(mbox, \"..\") == 0) || (strncmp(mbox, \"../\", 3) == 0))\n" }, { "line_no": 20, "char_start": 504, "char_end": 521, "line": " return NULL;\n" }, { "line_no": 21, "char_start": 521, "char_end": 550, "line": " size_t len = strlen(mbox);\n" }, { "line_no": 22, "char_start": 550, "char_end": 607, "line": " if ((len > 3) && (strcmp(mbox + len - 3, \"/..\") == 0))\n" }, { "line_no": 23, "char_start": 607, "char_end": 624, "line": " return NULL;\n" }, { "line_no": 24, "char_start": 624, "char_end": 625, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 415, "char_end": 627, "chars": "if (strstr(mbox, \"/../\") || (strcmp(mbox, \"..\") == 0) || (strncmp(mbox, \"../\", 3) == 0))\n return NULL;\n size_t len = strlen(mbox);\n if ((len > 3) && (strcmp(mbox + len - 3, \"/..\") == 0))\n return NULL;\n\n " } ] }
github.com/neomutt/neomutt/commit/57971dba06346b2d7179294f4528b8d4427a7c5d
imap/util.c
cwe-022
_normalize
def _normalize(self, metaerrors): """Normalize output format to be usable by Anaconda's linting frontend """ errors = [] for error in metaerrors: if self.filepath not in error.get('path', ''): continue error_type = error.get('severity', 'X').capitalize()[0] if error_type == 'X': continue if error_type not in ['E', 'W']: error_type = 'V' errors.append({ 'underline_range': True, 'lineno': error.get('line', 0), 'offset': error.get('col', 0), 'raw_message': error.get('message', ''), 'code': 0, 'level': error_type, 'message': '[{0}] {1} ({2}): {3}'.format( error_type, error.get('linter', 'none'), error.get('severity', 'none'), error.get('message') ) }) return errors
def _normalize(self, metaerrors): """Normalize output format to be usable by Anaconda's linting frontend """ errors = [] for error in metaerrors: last_path = os.path.join( os.path.basename(os.path.dirname(self.filepath)), os.path.basename(self.filepath) ) if last_path not in error.get('path', ''): continue error_type = error.get('severity', 'X').capitalize()[0] if error_type == 'X': continue if error_type not in ['E', 'W']: error_type = 'V' errors.append({ 'underline_range': True, 'lineno': error.get('line', 0), 'offset': error.get('col', 0), 'raw_message': error.get('message', ''), 'code': 0, 'level': error_type, 'message': '[{0}] {1} ({2}): {3}'.format( error_type, error.get('linter', 'none'), error.get('severity', 'none'), error.get('message') ) }) return errors
{ "deleted": [ { "line_no": 7, "char_start": 183, "char_end": 242, "line": " if self.filepath not in error.get('path', ''):\n" } ], "added": [ { "line_no": 7, "char_start": 183, "char_end": 221, "line": " last_path = os.path.join(\n" }, { "line_no": 8, "char_start": 221, "char_end": 287, "line": " os.path.basename(os.path.dirname(self.filepath)),\n" }, { "line_no": 9, "char_start": 287, "char_end": 335, "line": " os.path.basename(self.filepath)\n" }, { "line_no": 10, "char_start": 335, "char_end": 349, "line": " )\n" }, { "line_no": 11, "char_start": 349, "char_end": 404, "line": " if last_path not in error.get('path', ''):\n" } ] }
{ "deleted": [], "added": [ { "char_start": 195, "char_end": 217, "chars": "last_path = os.path.jo" }, { "char_start": 218, "char_end": 273, "chars": "n(\n os.path.basename(os.path.dirname(sel" }, { "char_start": 274, "char_end": 287, "chars": ".filepath)),\n" }, { "char_start": 288, "char_end": 320, "chars": " os.path.basename(" }, { "char_start": 329, "char_end": 369, "chars": "path)\n )\n if last_" } ] }
github.com/DamnWidget/anaconda_go/commit/d3db90bb8853d832927818699591b91f56f6413c
plugin/handlers_go/anagonda/context/gometalinter.py
cwe-022
dd_load_text_ext
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags) { // if (!dd->locked) // error_msg_and_die("dump_dir is not opened"); /* bug */ /* Compat with old abrt dumps. Remove in abrt-2.1 */ if (strcmp(name, "release") == 0) name = FILENAME_OS_RELEASE; char *full_path = concat_path_file(dd->dd_dirname, name); char *ret = load_text_file(full_path, flags); free(full_path); return ret; }
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags) { // if (!dd->locked) // error_msg_and_die("dump_dir is not opened"); /* bug */ if (!str_is_correct_filename(name)) { error_msg("Cannot load text. '%s' is not a valid file name", name); if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE)) xfunc_die(); } /* Compat with old abrt dumps. Remove in abrt-2.1 */ if (strcmp(name, "release") == 0) name = FILENAME_OS_RELEASE; char *full_path = concat_path_file(dd->dd_dirname, name); char *ret = load_text_file(full_path, flags); free(full_path); return ret; }
{ "deleted": [], "added": [ { "line_no": 6, "char_start": 175, "char_end": 215, "line": " if (!str_is_correct_filename(name))\n" }, { "line_no": 7, "char_start": 215, "char_end": 221, "line": " {\n" }, { "line_no": 8, "char_start": 221, "char_end": 297, "line": " error_msg(\"Cannot load text. '%s' is not a valid file name\", name);\n" }, { "line_no": 9, "char_start": 297, "char_end": 357, "line": " if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))\n" }, { "line_no": 10, "char_start": 357, "char_end": 382, "line": " xfunc_die();\n" }, { "line_no": 11, "char_start": 382, "char_end": 388, "line": " }\n" }, { "line_no": 12, "char_start": 388, "char_end": 389, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 179, "char_end": 393, "chars": "if (!str_is_correct_filename(name))\n {\n error_msg(\"Cannot load text. '%s' is not a valid file name\", name);\n if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))\n xfunc_die();\n }\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
_download_file
@staticmethod def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, filename) key.get_contents_to_filename(local_filename) return local_filename
@staticmethod def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, os.path.basename(filename)) key.get_contents_to_filename(local_filename) return local_filename
{ "deleted": [ { "line_no": 4, "char_start": 110, "char_end": 169, "line": " local_filename = os.path.join(local_dir, filename)\n" } ], "added": [ { "line_no": 4, "char_start": 110, "char_end": 187, "line": " local_filename = os.path.join(local_dir, os.path.basename(filename))\n" } ] }
{ "deleted": [], "added": [ { "char_start": 159, "char_end": 176, "chars": "os.path.basename(" }, { "char_start": 184, "char_end": 185, "chars": ")" } ] }
github.com/openstack/nova/commit/76363226bd8533256f7795bba358d7f4b8a6c9e6
nova/image/s3.py
cwe-022
Utility::UnZip
bool Utility::UnZip(const QString &zippath, const QString &destpath) { int res = 0; QDir dir(destpath); if (!cp437) { cp437 = new QCodePage437Codec(); } #ifdef Q_OS_WIN32 zlib_filefunc64_def ffunc; fill_win32_filefunc64W(&ffunc); unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc); #else unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData()); #endif if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) { return false; } res = unzGoToFirstFile(zfile); if (res == UNZ_OK) { do { // Get the name of the file in the archive. char file_name[MAX_PATH] = {0}; unz_file_info64 file_info; unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); QString qfile_name; QString cp437_file_name; qfile_name = QString::fromUtf8(file_name); if (!(file_info.flag & (1<<11))) { // General purpose bit 11 says the filename is utf-8 encoded. If not set then // IBM 437 encoding might be used. cp437_file_name = cp437->toUnicode(file_name); } // If there is no file name then we can't do anything with it. if (!qfile_name.isEmpty()) { // We use the dir object to create the path in the temporary directory. // Unfortunately, we need a dir ojbect to do this as it's not a static function. // Full file path in the temporary directory. QString file_path = destpath + "/" + qfile_name; QFileInfo qfile_info(file_path); // Is this entry a directory? if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { dir.mkpath(qfile_name); continue; } else { dir.mkpath(qfile_info.path()); } // Open the file entry in the archive for reading. if (unzOpenCurrentFile(zfile) != UNZ_OK) { unzClose(zfile); return false; } // Open the file on disk to write the entry in the archive to. QFile entry(file_path); if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // Buffered reading and writing. char buff[BUFF_SIZE] = {0}; int read = 0; while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { entry.write(buff, read); } entry.close(); // Read errors are marked by a negative read amount. if (read < 0) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // The file was read but the CRC did not match. // We don't check the read file size vs the uncompressed file size // because if they're different there should be a CRC error. if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { unzClose(zfile); return false; } if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { QString cp437_file_path = destpath + "/" + cp437_file_name; QFile::copy(file_path, cp437_file_path); } } } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); } if (res != UNZ_END_OF_LIST_OF_FILE) { unzClose(zfile); return false; } unzClose(zfile); return true; }
bool Utility::UnZip(const QString &zippath, const QString &destpath) { int res = 0; QDir dir(destpath); if (!cp437) { cp437 = new QCodePage437Codec(); } #ifdef Q_OS_WIN32 zlib_filefunc64_def ffunc; fill_win32_filefunc64W(&ffunc); unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc); #else unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData()); #endif if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) { return false; } res = unzGoToFirstFile(zfile); if (res == UNZ_OK) { do { // Get the name of the file in the archive. char file_name[MAX_PATH] = {0}; unz_file_info64 file_info; unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); QString qfile_name; QString cp437_file_name; qfile_name = QString::fromUtf8(file_name); if (!(file_info.flag & (1<<11))) { // General purpose bit 11 says the filename is utf-8 encoded. If not set then // IBM 437 encoding might be used. cp437_file_name = cp437->toUnicode(file_name); } // If there is no file name then we can't do anything with it. if (!qfile_name.isEmpty()) { // for security reasons against maliciously crafted zip archives // we need the file path to always be inside the target folder // and not outside, so we will remove all illegal backslashes // and all relative upward paths segments "/../" from the zip's local // file name/path before prepending the target folder to create // the final path QString original_path = qfile_name; bool evil_or_corrupt_epub = false; if (qfile_name.contains("\\")) evil_or_corrupt_epub = true; qfile_name = "/" + qfile_name.replace("\\",""); if (qfile_name.contains("/../")) evil_or_corrupt_epub = true; qfile_name = qfile_name.replace("/../","/"); while(qfile_name.startsWith("/")) { qfile_name = qfile_name.remove(0,1); } if (cp437_file_name.contains("\\")) evil_or_corrupt_epub = true; cp437_file_name = "/" + cp437_file_name.replace("\\",""); if (cp437_file_name.contains("/../")) evil_or_corrupt_epub = true; cp437_file_name = cp437_file_name.replace("/../","/"); while(cp437_file_name.startsWith("/")) { cp437_file_name = cp437_file_name.remove(0,1); } if (evil_or_corrupt_epub) { unzCloseCurrentFile(zfile); unzClose(zfile); // throw (UNZIPLoadParseError(QString(QObject::tr("Possible evil or corrupt zip file name: %1")).arg(original_path).toStdString())); return false; } // We use the dir object to create the path in the temporary directory. // Unfortunately, we need a dir ojbect to do this as it's not a static function. // Full file path in the temporary directory. QString file_path = destpath + "/" + qfile_name; QFileInfo qfile_info(file_path); // Is this entry a directory? if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { dir.mkpath(qfile_name); continue; } else { dir.mkpath(qfile_info.path()); } // Open the file entry in the archive for reading. if (unzOpenCurrentFile(zfile) != UNZ_OK) { unzClose(zfile); return false; } // Open the file on disk to write the entry in the archive to. QFile entry(file_path); if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // Buffered reading and writing. char buff[BUFF_SIZE] = {0}; int read = 0; while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { entry.write(buff, read); } entry.close(); // Read errors are marked by a negative read amount. if (read < 0) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // The file was read but the CRC did not match. // We don't check the read file size vs the uncompressed file size // because if they're different there should be a CRC error. if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { unzClose(zfile); return false; } if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { QString cp437_file_path = destpath + "/" + cp437_file_name; QFile::copy(file_path, cp437_file_path); } } } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); } if (res != UNZ_END_OF_LIST_OF_FILE) { unzClose(zfile); return false; } unzClose(zfile); return true; }
{ "deleted": [], "added": [ { "line_no": 39, "char_start": 1400, "char_end": 1401, "line": "\n" }, { "line_no": 46, "char_start": 1800, "char_end": 1801, "line": "\n" }, { "line_no": 47, "char_start": 1801, "char_end": 1846, "line": "\t QString original_path = qfile_name;\n" }, { "line_no": 48, "char_start": 1846, "char_end": 1890, "line": "\t bool evil_or_corrupt_epub = false;\n" }, { "line_no": 49, "char_start": 1890, "char_end": 1891, "line": "\n" }, { "line_no": 50, "char_start": 1891, "char_end": 1961, "line": "\t if (qfile_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n" }, { "line_no": 51, "char_start": 1961, "char_end": 2018, "line": "\t qfile_name = \"/\" + qfile_name.replace(\"\\\\\",\"\");\n" }, { "line_no": 52, "char_start": 2018, "char_end": 2019, "line": "\n" }, { "line_no": 53, "char_start": 2019, "char_end": 2090, "line": "\t if (qfile_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n" }, { "line_no": 54, "char_start": 2090, "char_end": 2144, "line": "\t qfile_name = qfile_name.replace(\"/../\",\"/\");\n" }, { "line_no": 55, "char_start": 2144, "char_end": 2145, "line": "\n" }, { "line_no": 56, "char_start": 2145, "char_end": 2191, "line": "\t while(qfile_name.startsWith(\"/\")) { \n" }, { "line_no": 57, "char_start": 2191, "char_end": 2232, "line": "\t\t qfile_name = qfile_name.remove(0,1);\n" }, { "line_no": 58, "char_start": 2232, "char_end": 2243, "line": "\t }\n" }, { "line_no": 59, "char_start": 2243, "char_end": 2260, "line": " \n" }, { "line_no": 60, "char_start": 2260, "char_end": 2335, "line": "\t if (cp437_file_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n" }, { "line_no": 61, "char_start": 2335, "char_end": 2402, "line": "\t cp437_file_name = \"/\" + cp437_file_name.replace(\"\\\\\",\"\");\n" }, { "line_no": 62, "char_start": 2402, "char_end": 2403, "line": "\n" }, { "line_no": 63, "char_start": 2403, "char_end": 2479, "line": "\t if (cp437_file_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n" }, { "line_no": 64, "char_start": 2479, "char_end": 2543, "line": "\t cp437_file_name = cp437_file_name.replace(\"/../\",\"/\");\n" }, { "line_no": 65, "char_start": 2543, "char_end": 2544, "line": "\n" }, { "line_no": 66, "char_start": 2544, "char_end": 2595, "line": "\t while(cp437_file_name.startsWith(\"/\")) { \n" }, { "line_no": 67, "char_start": 2595, "char_end": 2646, "line": "\t\t cp437_file_name = cp437_file_name.remove(0,1);\n" }, { "line_no": 68, "char_start": 2646, "char_end": 2657, "line": "\t }\n" }, { "line_no": 69, "char_start": 2657, "char_end": 2658, "line": "\n" }, { "line_no": 70, "char_start": 2658, "char_end": 2695, "line": "\t if (evil_or_corrupt_epub) {\n" }, { "line_no": 71, "char_start": 2695, "char_end": 2729, "line": "\t\t unzCloseCurrentFile(zfile);\n" }, { "line_no": 72, "char_start": 2729, "char_end": 2752, "line": "\t\t unzClose(zfile);\n" }, { "line_no": 74, "char_start": 2891, "char_end": 2925, "line": " return false;\n" }, { "line_no": 75, "char_start": 2925, "char_end": 2936, "line": "\t }\n" }, { "line_no": 76, "char_start": 2936, "char_end": 2937, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 1400, "char_end": 2937, "chars": "\n\t // for security reasons against maliciously crafted zip archives\n\t // we need the file path to always be inside the target folder \n\t // and not outside, so we will remove all illegal backslashes\n\t // and all relative upward paths segments \"/../\" from the zip's local \n\t // file name/path before prepending the target folder to create \n\t // the final path\n\n\t QString original_path = qfile_name;\n\t bool evil_or_corrupt_epub = false;\n\n\t if (qfile_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n\t qfile_name = \"/\" + qfile_name.replace(\"\\\\\",\"\");\n\n\t if (qfile_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n\t qfile_name = qfile_name.replace(\"/../\",\"/\");\n\n\t while(qfile_name.startsWith(\"/\")) { \n\t\t qfile_name = qfile_name.remove(0,1);\n\t }\n \n\t if (cp437_file_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n\t cp437_file_name = \"/\" + cp437_file_name.replace(\"\\\\\",\"\");\n\n\t if (cp437_file_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n\t cp437_file_name = cp437_file_name.replace(\"/../\",\"/\");\n\n\t while(cp437_file_name.startsWith(\"/\")) { \n\t\t cp437_file_name = cp437_file_name.remove(0,1);\n\t }\n\n\t if (evil_or_corrupt_epub) {\n\t\t unzCloseCurrentFile(zfile);\n\t\t unzClose(zfile);\n\t\t // throw (UNZIPLoadParseError(QString(QObject::tr(\"Possible evil or corrupt zip file name: %1\")).arg(original_path).toStdString()));\n return false;\n\t }\n\n" } ] }
github.com/Sigil-Ebook/Sigil/commit/0979ba8d10c96ebca330715bfd4494ea0e019a8f
src/Misc/Utility.cpp
cwe-022
save
async def save(request): # TODO csrf data = await request.post() item = Item(data['src']) # Update name new_src = data.get('new_src') if new_src and new_src != data['src']: # don't need to worry about html unquote shutil.move(item.abspath, settings.STORAGE_DIR + new_src) old_backup_abspath = item.backup_abspath item = Item(new_src) if os.path.isfile(old_backup_abspath): shutil.move(old_backup_abspath, item.backup_abspath) # Update meta for field in item.FORM: # TODO handle .repeatable (keywords) item.meta[field] = [data.get(field, '')] if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath): shutil.copyfile(item.abspath, item.backup_abspath) # WISHLIST don't write() if nothing changed item.meta.write() return web.Response( status=200, body=json.dumps(item.get_form_fields()).encode('utf8'), content_type='application/json', )
async def save(request): # TODO csrf data = await request.post() item = Item(data['src']) # Update name new_src = data.get('new_src') if new_src: new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src) if not new_abspath.startswith(settings.STORAGE_DIR): return web.Response(status=400, body=b'Invalid Request') if new_abspath != item.abspath: shutil.move(item.abspath, new_abspath) old_backup_abspath = item.backup_abspath item = Item(new_src) if os.path.isfile(old_backup_abspath): shutil.move(old_backup_abspath, item.backup_abspath) # Update meta for field in item.FORM: # TODO handle .repeatable (keywords) item.meta[field] = [data.get(field, '')] if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath): shutil.copyfile(item.abspath, item.backup_abspath) # WISHLIST don't write() if nothing changed item.meta.write() return web.Response( status=200, body=json.dumps(item.get_form_fields()).encode('utf8'), content_type='application/json', )
{ "deleted": [ { "line_no": 8, "char_start": 155, "char_end": 198, "line": " if new_src and new_src != data['src']:\n" }, { "line_no": 10, "char_start": 247, "char_end": 313, "line": " shutil.move(item.abspath, settings.STORAGE_DIR + new_src)\n" }, { "line_no": 11, "char_start": 313, "char_end": 362, "line": " old_backup_abspath = item.backup_abspath\n" }, { "line_no": 12, "char_start": 362, "char_end": 391, "line": " item = Item(new_src)\n" }, { "line_no": 13, "char_start": 391, "char_end": 438, "line": " if os.path.isfile(old_backup_abspath):\n" }, { "line_no": 14, "char_start": 438, "char_end": 503, "line": " shutil.move(old_backup_abspath, item.backup_abspath)\n" } ], "added": [ { "line_no": 8, "char_start": 155, "char_end": 171, "line": " if new_src:\n" }, { "line_no": 9, "char_start": 171, "char_end": 241, "line": " new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src)\n" }, { "line_no": 10, "char_start": 241, "char_end": 302, "line": " if not new_abspath.startswith(settings.STORAGE_DIR):\n" }, { "line_no": 11, "char_start": 302, "char_end": 371, "line": " return web.Response(status=400, body=b'Invalid Request')\n" }, { "line_no": 12, "char_start": 371, "char_end": 372, "line": "\n" }, { "line_no": 13, "char_start": 372, "char_end": 412, "line": " if new_abspath != item.abspath:\n" }, { "line_no": 14, "char_start": 412, "char_end": 463, "line": " shutil.move(item.abspath, new_abspath)\n" }, { "line_no": 15, "char_start": 463, "char_end": 516, "line": " old_backup_abspath = item.backup_abspath\n" }, { "line_no": 16, "char_start": 516, "char_end": 549, "line": " item = Item(new_src)\n" }, { "line_no": 17, "char_start": 549, "char_end": 600, "line": " if os.path.isfile(old_backup_abspath):\n" }, { "line_no": 18, "char_start": 600, "char_end": 669, "line": " shutil.move(old_backup_abspath, item.backup_abspath)\n" } ] }
{ "deleted": [ { "char_start": 170, "char_end": 173, "chars": "and" }, { "char_start": 179, "char_end": 181, "chars": "rc" }, { "char_start": 182, "char_end": 183, "chars": "!" }, { "char_start": 185, "char_end": 186, "chars": "d" }, { "char_start": 189, "char_end": 191, "chars": "['" }, { "char_start": 194, "char_end": 197, "chars": "']:" }, { "char_start": 206, "char_end": 207, "chars": "#" }, { "char_start": 208, "char_end": 209, "chars": "d" }, { "char_start": 210, "char_end": 212, "chars": "n'" }, { "char_start": 217, "char_end": 218, "chars": "d" }, { "char_start": 219, "char_end": 221, "chars": "to" }, { "char_start": 222, "char_end": 224, "chars": "wo" }, { "char_start": 226, "char_end": 227, "chars": "y" }, { "char_start": 228, "char_end": 229, "chars": "a" }, { "char_start": 232, "char_end": 233, "chars": "t" }, { "char_start": 234, "char_end": 237, "chars": "htm" }, { "char_start": 239, "char_end": 241, "chars": "un" }, { "char_start": 243, "char_end": 244, "chars": "o" }, { "char_start": 281, "char_end": 304, "chars": "settings.STORAGE_DIR + " }, { "char_start": 309, "char_end": 311, "chars": "rc" } ], "added": [ { "char_start": 169, "char_end": 171, "chars": ":\n" }, { "char_start": 172, "char_end": 178, "chars": " " }, { "char_start": 183, "char_end": 185, "chars": "ab" }, { "char_start": 186, "char_end": 190, "chars": "path" }, { "char_start": 193, "char_end": 197, "chars": "os.p" }, { "char_start": 199, "char_end": 201, "chars": "h." }, { "char_start": 202, "char_end": 236, "chars": "bspath(settings.STORAGE_DIR + new_" }, { "char_start": 239, "char_end": 240, "chars": ")" }, { "char_start": 249, "char_end": 251, "chars": "if" }, { "char_start": 253, "char_end": 254, "chars": "o" }, { "char_start": 258, "char_end": 280, "chars": "w_abspath.startswith(s" }, { "char_start": 281, "char_end": 305, "chars": "ttings.STORAGE_DIR):\n " }, { "char_start": 306, "char_end": 316, "chars": " re" }, { "char_start": 317, "char_end": 320, "chars": "urn" }, { "char_start": 322, "char_end": 329, "chars": "eb.Resp" }, { "char_start": 330, "char_end": 336, "chars": "nse(st" }, { "char_start": 337, "char_end": 346, "chars": "tus=400, " }, { "char_start": 348, "char_end": 364, "chars": "dy=b'Invalid Req" }, { "char_start": 365, "char_end": 367, "chars": "es" }, { "char_start": 368, "char_end": 379, "chars": "')\n\n " }, { "char_start": 380, "char_end": 393, "chars": "if new_abspat" }, { "char_start": 394, "char_end": 399, "chars": " != i" }, { "char_start": 400, "char_end": 401, "chars": "e" }, { "char_start": 402, "char_end": 408, "chars": ".abspa" }, { "char_start": 409, "char_end": 411, "chars": "h:" }, { "char_start": 412, "char_end": 416, "chars": " " }, { "char_start": 454, "char_end": 456, "chars": "ab" }, { "char_start": 457, "char_end": 461, "chars": "path" }, { "char_start": 463, "char_end": 467, "chars": " " }, { "char_start": 516, "char_end": 520, "chars": " " }, { "char_start": 557, "char_end": 561, "chars": " " }, { "char_start": 600, "char_end": 604, "chars": " " } ] }
github.com/crccheck/gallery-cms/commit/60dec5c580a779ae27824ed54cb113eca25afdc0
gallery/gallery.py
cwe-022
wiki_handle_rest_call
wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\0') { if (!strcmp(func, "page/get")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, "%s", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, "page/set")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, "text")) != NULL) && ( (page = http_request_param_get(req, "page")) != NULL)) { file_write(page, wikitext); http_response_printf(res, "success"); http_response_send(res); return; } } else if (!strcmp(func, "page/delete")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && (unlink(page) > 0)) { http_response_printf(res, "success"); http_response_send(res); return; } } else if (!strcmp(func, "page/exists")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, "success"); http_response_send(res); return; } } else if (!strcmp(func, "pages") || !strcmp(func, "search")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, "expr"); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; i<n_pages; i++) { struct tm *pTm; char datebuf[64]; pTm = localtime(&pages[i]->mtime); strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm); http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, "Error"); http_response_printf(res, "<html><body>Failed</body></html>\n"); http_response_send(res); return; }
wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\0') { if (!strcmp(func, "page/get")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, "%s", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, "page/set")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, "text")) != NULL) && ( (page = http_request_param_get(req, "page")) != NULL)) { if (page_name_is_good(page)) { file_write(page, wikitext); http_response_printf(res, "success"); http_response_send(res); return; } } } else if (!strcmp(func, "page/delete")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (unlink(page) > 0)) { http_response_printf(res, "success"); http_response_send(res); return; } } else if (!strcmp(func, "page/exists")) { char *page = http_request_param_get(req, "page"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, "success"); http_response_send(res); return; } } else if (!strcmp(func, "pages") || !strcmp(func, "search")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, "expr"); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; i<n_pages; i++) { struct tm *pTm; char datebuf[64]; pTm = localtime(&pages[i]->mtime); strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm); http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, "Error"); http_response_printf(res, "<html><body>Failed</body></html>\n"); http_response_send(res); return; }
{ "deleted": [ { "line_no": 15, "char_start": 307, "char_end": 350, "line": "\t if (page && (access(page, R_OK) == 0)) \n" }, { "line_no": 28, "char_start": 699, "char_end": 741, "line": "\t file_write(page, wikitext);\t \n" }, { "line_no": 41, "char_start": 1015, "char_end": 1050, "line": "\t if (page && (unlink(page) > 0))\n" }, { "line_no": 55, "char_start": 1333, "char_end": 1376, "line": "\t if (page && (access(page, R_OK) == 0)) \n" } ], "added": [ { "line_no": 15, "char_start": 307, "char_end": 376, "line": "\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n" }, { "line_no": 28, "char_start": 725, "char_end": 757, "line": "\t if (page_name_is_good(page))\n" }, { "line_no": 29, "char_start": 757, "char_end": 764, "line": "\t {\n" }, { "line_no": 30, "char_start": 764, "char_end": 799, "line": "\t file_write(page, wikitext);\n" }, { "line_no": 35, "char_start": 898, "char_end": 905, "line": "\t }\n" }, { "line_no": 44, "char_start": 1080, "char_end": 1142, "line": "\t if (page && page_name_is_good(page) && (unlink(page) > 0))\n" }, { "line_no": 58, "char_start": 1425, "char_end": 1494, "line": "\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n" } ] }
{ "deleted": [ { "char_start": 348, "char_end": 349, "chars": " " }, { "char_start": 733, "char_end": 740, "chars": "\t " }, { "char_start": 1374, "char_end": 1375, "chars": " " } ], "added": [ { "char_start": 322, "char_end": 349, "chars": "page_name_is_good(page) && " }, { "char_start": 725, "char_end": 764, "chars": "\t if (page_name_is_good(page))\n\t {\n" }, { "char_start": 898, "char_end": 905, "chars": "\t }\n" }, { "char_start": 1095, "char_end": 1122, "chars": "page_name_is_good(page) && " }, { "char_start": 1440, "char_end": 1467, "chars": "page_name_is_good(page) && " } ] }
github.com/yarolig/didiwiki/commit/5e5c796617e1712905dc5462b94bd5e6c08d15ea
src/wiki.c
cwe-022
handle_method_call
static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (element == NULL || element[0] == '\0' || strlen(element) > 64) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }
static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }
{ "deleted": [ { "line_no": 259, "char_start": 9073, "char_end": 9148, "line": " if (element == NULL || element[0] == '\\0' || strlen(element) > 64)\n" } ], "added": [ { "line_no": 259, "char_start": 9073, "char_end": 9120, "line": " if (!str_is_correct_filename(element))\n" }, { "line_no": 318, "char_start": 11559, "char_end": 11606, "line": " if (!str_is_correct_filename(element))\n" }, { "line_no": 319, "char_start": 11606, "char_end": 11616, "line": " {\n" }, { "line_no": 320, "char_start": 11616, "char_end": 11705, "line": " log_notice(\"'%s' is not a valid element name of '%s'\", element, problem_id);\n" }, { "line_no": 321, "char_start": 11705, "char_end": 11790, "line": " char *error = xasprintf(_(\"'%s' is not a valid element name\"), element);\n" }, { "line_no": 322, "char_start": 11790, "char_end": 11857, "line": " g_dbus_method_invocation_return_dbus_error(invocation,\n" }, { "line_no": 323, "char_start": 11857, "char_end": 11946, "line": " \"org.freedesktop.problems.InvalidElement\",\n" }, { "line_no": 324, "char_start": 11946, "char_end": 12000, "line": " error);\n" }, { "line_no": 325, "char_start": 12000, "char_end": 12001, "line": "\n" }, { "line_no": 326, "char_start": 12001, "char_end": 12026, "line": " free(error);\n" }, { "line_no": 327, "char_start": 12026, "char_end": 12046, "line": " return;\n" }, { "line_no": 328, "char_start": 12046, "char_end": 12056, "line": " }\n" }, { "line_no": 329, "char_start": 12056, "char_end": 12057, "line": "\n" } ] }
{ "deleted": [ { "char_start": 9085, "char_end": 9126, "chars": "element == NULL || element[0] == '\\0' || " }, { "char_start": 9141, "char_end": 9146, "chars": " > 64" } ], "added": [ { "char_start": 9085, "char_end": 9097, "chars": "!str_is_corr" }, { "char_start": 9098, "char_end": 9103, "chars": "ct_fi" }, { "char_start": 9106, "char_end": 9107, "chars": "a" }, { "char_start": 11557, "char_end": 12055, "chars": "\n\n if (!str_is_correct_filename(element))\n {\n log_notice(\"'%s' is not a valid element name of '%s'\", element, problem_id);\n char *error = xasprintf(_(\"'%s' is not a valid element name\"), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n \"org.freedesktop.problems.InvalidElement\",\n error);\n\n free(error);\n return;\n }" } ] }
github.com/abrt/abrt/commit/f3c2a6af3455b2882e28570e8a04f1c2d4500d5b
src/dbus/abrt-dbus.c
cwe-022
HPHP::extractFileTo
static bool extractFileTo(zip* zip, const std::string &file, std::string& to, char* buf, size_t len) { auto sep = file.rfind('/'); if (sep != std::string::npos) { auto path = to + file.substr(0, sep); if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) { return false; } if (sep == file.length() - 1) { return true; } } to.append(file); struct zip_stat zipStat; if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) { return false; } auto zipFile = zip_fopen_index(zip, zipStat.index, 0); FAIL_IF_INVALID_PTR(zipFile); auto outFile = fopen(to.c_str(), "wb"); if (outFile == nullptr) { zip_fclose(zipFile); return false; } for (auto n = zip_fread(zipFile, buf, len); n != 0; n = zip_fread(zipFile, buf, len)) { if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) { zip_fclose(zipFile); fclose(outFile); remove(to.c_str()); return false; } } zip_fclose(zipFile); if (fclose(outFile) != 0) { return false; } return true; }
static bool extractFileTo(zip* zip, const std::string &file, std::string& to, char* buf, size_t len) { struct zip_stat zipStat; // Verify the file to be extracted is actually in the zip file if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) { return false; } auto clean_file = file; auto sep = std::string::npos; // Normally would just use std::string::rfind here, but if we want to be // consistent between Windows and Linux, even if techincally Linux won't use // backslash for a separator, we are checking for both types. int idx = file.length() - 1; while (idx >= 0) { if (FileUtil::isDirSeparator(file[idx])) { sep = idx; break; } idx--; } if (sep != std::string::npos) { // make_relative_path so we do not try to put files or dirs in bad // places. This securely "cleans" the file. clean_file = make_relative_path(file); std::string path = to + clean_file; bool is_dir_only = true; if (sep < file.length() - 1) { // not just a directory auto clean_file_dir = HHVM_FN(dirname)(clean_file); path = to + clean_file_dir.toCppString(); is_dir_only = false; } // Make sure the directory path to extract to exists or can be created if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) { return false; } // If we have a good directory to extract to above, we now check whether // the "file" parameter passed in is a directory or actually a file. if (is_dir_only) { // directory, like /usr/bin/ return true; } // otherwise file is actually a file, so we actually extract. } // We have ensured that clean_file will be added to a relative path by the // time we get here. to.append(clean_file); auto zipFile = zip_fopen_index(zip, zipStat.index, 0); FAIL_IF_INVALID_PTR(zipFile); auto outFile = fopen(to.c_str(), "wb"); if (outFile == nullptr) { zip_fclose(zipFile); return false; } for (auto n = zip_fread(zipFile, buf, len); n != 0; n = zip_fread(zipFile, buf, len)) { if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) { zip_fclose(zipFile); fclose(outFile); remove(to.c_str()); return false; } } zip_fclose(zipFile); if (fclose(outFile) != 0) { return false; } return true; }
{ "deleted": [ { "line_no": 3, "char_start": 129, "char_end": 159, "line": " auto sep = file.rfind('/');\n" }, { "line_no": 5, "char_start": 193, "char_end": 235, "line": " auto path = to + file.substr(0, sep);\n" }, { "line_no": 10, "char_start": 333, "char_end": 369, "line": " if (sep == file.length() - 1) {\n" }, { "line_no": 15, "char_start": 399, "char_end": 418, "line": " to.append(file);\n" }, { "line_no": 16, "char_start": 418, "char_end": 445, "line": " struct zip_stat zipStat;\n" }, { "line_no": 17, "char_start": 445, "char_end": 500, "line": " if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n" }, { "line_no": 18, "char_start": 500, "char_end": 518, "line": " return false;\n" }, { "line_no": 19, "char_start": 518, "char_end": 522, "line": " }\n" } ], "added": [ { "line_no": 3, "char_start": 129, "char_end": 130, "line": "\n" }, { "line_no": 4, "char_start": 130, "char_end": 157, "line": " struct zip_stat zipStat;\n" }, { "line_no": 6, "char_start": 222, "char_end": 277, "line": " if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n" }, { "line_no": 7, "char_start": 277, "char_end": 295, "line": " return false;\n" }, { "line_no": 8, "char_start": 295, "char_end": 299, "line": " }\n" }, { "line_no": 9, "char_start": 299, "char_end": 300, "line": "\n" }, { "line_no": 10, "char_start": 300, "char_end": 326, "line": " auto clean_file = file;\n" }, { "line_no": 11, "char_start": 326, "char_end": 358, "line": " auto sep = std::string::npos;\n" }, { "line_no": 15, "char_start": 576, "char_end": 607, "line": " int idx = file.length() - 1;\n" }, { "line_no": 16, "char_start": 607, "char_end": 628, "line": " while (idx >= 0) {\n" }, { "line_no": 17, "char_start": 628, "char_end": 675, "line": " if (FileUtil::isDirSeparator(file[idx])) {\n" }, { "line_no": 18, "char_start": 675, "char_end": 692, "line": " sep = idx;\n" }, { "line_no": 19, "char_start": 692, "char_end": 705, "line": " break;\n" }, { "line_no": 20, "char_start": 705, "char_end": 711, "line": " }\n" }, { "line_no": 21, "char_start": 711, "char_end": 722, "line": " idx--;\n" }, { "line_no": 22, "char_start": 722, "char_end": 726, "line": " }\n" }, { "line_no": 26, "char_start": 879, "char_end": 922, "line": " clean_file = make_relative_path(file);\n" }, { "line_no": 27, "char_start": 922, "char_end": 962, "line": " std::string path = to + clean_file;\n" }, { "line_no": 28, "char_start": 962, "char_end": 991, "line": " bool is_dir_only = true;\n" }, { "line_no": 29, "char_start": 991, "char_end": 1050, "line": " if (sep < file.length() - 1) { // not just a directory\n" }, { "line_no": 30, "char_start": 1050, "char_end": 1108, "line": " auto clean_file_dir = HHVM_FN(dirname)(clean_file);\n" }, { "line_no": 31, "char_start": 1108, "char_end": 1156, "line": " path = to + clean_file_dir.toCppString();\n" }, { "line_no": 32, "char_start": 1156, "char_end": 1183, "line": " is_dir_only = false;\n" }, { "line_no": 33, "char_start": 1183, "char_end": 1189, "line": " }\n" }, { "line_no": 34, "char_start": 1189, "char_end": 1190, "line": "\n" }, { "line_no": 42, "char_start": 1513, "char_end": 1565, "line": " if (is_dir_only) { // directory, like /usr/bin/\n" }, { "line_no": 50, "char_start": 1761, "char_end": 1786, "line": " to.append(clean_file);\n" } ] }
{ "deleted": [ { "char_start": 132, "char_end": 133, "chars": "u" }, { "char_start": 140, "char_end": 141, "chars": "=" }, { "char_start": 152, "char_end": 154, "chars": "('" }, { "char_start": 218, "char_end": 219, "chars": "." }, { "char_start": 221, "char_end": 222, "chars": "b" }, { "char_start": 224, "char_end": 225, "chars": "r" }, { "char_start": 226, "char_end": 228, "chars": "0," }, { "char_start": 337, "char_end": 338, "chars": "i" }, { "char_start": 340, "char_end": 342, "chars": "(s" }, { "char_start": 343, "char_end": 344, "chars": "p" }, { "char_start": 345, "char_end": 347, "chars": "==" }, { "char_start": 352, "char_end": 354, "chars": ".l" }, { "char_start": 356, "char_end": 357, "chars": "g" }, { "char_start": 358, "char_end": 359, "chars": "h" }, { "char_start": 362, "char_end": 363, "chars": "-" }, { "char_start": 364, "char_end": 366, "chars": "1)" }, { "char_start": 367, "char_end": 368, "chars": "{" }, { "char_start": 396, "char_end": 399, "chars": "}\n\n" }, { "char_start": 402, "char_end": 407, "chars": "o.app" }, { "char_start": 408, "char_end": 411, "chars": "nd(" }, { "char_start": 415, "char_end": 418, "chars": ");\n" }, { "char_start": 420, "char_end": 421, "chars": "s" }, { "char_start": 422, "char_end": 423, "chars": "r" }, { "char_start": 424, "char_end": 426, "chars": "ct" }, { "char_start": 427, "char_end": 428, "chars": "z" }, { "char_start": 429, "char_end": 431, "chars": "p_" }, { "char_start": 432, "char_end": 433, "chars": "t" }, { "char_start": 436, "char_end": 440, "chars": "zipS" }, { "char_start": 443, "char_end": 444, "chars": ";" }, { "char_start": 447, "char_end": 449, "chars": "if" }, { "char_start": 450, "char_end": 455, "chars": "(zip_" }, { "char_start": 459, "char_end": 464, "chars": "(zip," }, { "char_start": 469, "char_end": 473, "chars": ".c_s" }, { "char_start": 474, "char_end": 478, "chars": "r()," }, { "char_start": 479, "char_end": 481, "chars": "0," }, { "char_start": 482, "char_end": 484, "chars": "&z" }, { "char_start": 486, "char_end": 488, "chars": "St" }, { "char_start": 490, "char_end": 491, "chars": ")" }, { "char_start": 492, "char_end": 494, "chars": "!=" }, { "char_start": 495, "char_end": 499, "chars": "0) {" }, { "char_start": 507, "char_end": 509, "chars": "ur" }, { "char_start": 510, "char_end": 512, "chars": " f" }, { "char_start": 514, "char_end": 515, "chars": "s" }, { "char_start": 517, "char_end": 521, "chars": "\n }" } ], "added": [ { "char_start": 129, "char_end": 326, "chars": "\n struct zip_stat zipStat;\n // Verify the file to be extracted is actually in the zip file\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto clean_file = file;\n" }, { "char_start": 339, "char_end": 401, "chars": "std::string::npos;\n // Normally would just use std::string::r" }, { "char_start": 403, "char_end": 492, "chars": "nd here, but if we want to be\n // consistent between Windows and Linux, even if techinca" }, { "char_start": 493, "char_end": 510, "chars": "ly Linux won't us" }, { "char_start": 511, "char_end": 541, "chars": "\n // backslash for a separato" }, { "char_start": 542, "char_end": 560, "chars": ", we are checking " }, { "char_start": 561, "char_end": 578, "chars": "or both types.\n " }, { "char_start": 580, "char_end": 583, "chars": "t i" }, { "char_start": 584, "char_end": 599, "chars": "x = file.length" }, { "char_start": 601, "char_end": 605, "chars": " - 1" }, { "char_start": 609, "char_end": 728, "chars": "while (idx >= 0) {\n if (FileUtil::isDirSeparator(file[idx])) {\n sep = idx;\n break;\n }\n idx--;\n }\n " }, { "char_start": 764, "char_end": 768, "chars": "// m" }, { "char_start": 769, "char_end": 807, "chars": "ke_relative_path so we do not try to p" }, { "char_start": 809, "char_end": 816, "chars": " files " }, { "char_start": 817, "char_end": 937, "chars": "r dirs in bad\n // places. This securely \"cleans\" the file.\n clean_file = make_relative_path(file);\n std::string" }, { "char_start": 950, "char_end": 956, "chars": "clean_" }, { "char_start": 960, "char_end": 972, "chars": ";\n bool i" }, { "char_start": 973, "char_end": 987, "chars": "_dir_only = tr" }, { "char_start": 988, "char_end": 999, "chars": "e;\n if (" }, { "char_start": 1000, "char_end": 1014, "chars": "ep < file.leng" }, { "char_start": 1015, "char_end": 1042, "chars": "h() - 1) { // not just a di" }, { "char_start": 1043, "char_end": 1085, "chars": "ectory\n auto clean_file_dir = HHVM_FN" }, { "char_start": 1086, "char_end": 1125, "chars": "dirname)(clean_file);\n path = to +" }, { "char_start": 1126, "char_end": 1128, "chars": "cl" }, { "char_start": 1129, "char_end": 1144, "chars": "an_file_dir.toC" }, { "char_start": 1145, "char_end": 1153, "chars": "pString(" }, { "char_start": 1156, "char_end": 1265, "chars": " is_dir_only = false;\n }\n\n // Make sure the directory path to extract to exists or can be created\n" }, { "char_start": 1367, "char_end": 1389, "chars": "// If we have a good d" }, { "char_start": 1390, "char_end": 1431, "chars": "rectory to extract to above, we now check" }, { "char_start": 1432, "char_end": 1437, "chars": "wheth" }, { "char_start": 1438, "char_end": 1442, "chars": "r\n " }, { "char_start": 1444, "char_end": 1452, "chars": "// the \"" }, { "char_start": 1456, "char_end": 1463, "chars": "\" param" }, { "char_start": 1464, "char_end": 1476, "chars": "ter passed i" }, { "char_start": 1477, "char_end": 1488, "chars": " is a direc" }, { "char_start": 1489, "char_end": 1492, "chars": "ory" }, { "char_start": 1493, "char_end": 1495, "chars": "or" }, { "char_start": 1496, "char_end": 1532, "chars": "actually a file.\n if (is_dir_only" }, { "char_start": 1535, "char_end": 1564, "chars": " // directory, like /usr/bin/" }, { "char_start": 1594, "char_end": 1598, "chars": "// o" }, { "char_start": 1599, "char_end": 1605, "chars": "herwis" }, { "char_start": 1606, "char_end": 1607, "chars": " " }, { "char_start": 1612, "char_end": 1614, "chars": "is" }, { "char_start": 1615, "char_end": 1617, "chars": "ac" }, { "char_start": 1619, "char_end": 1623, "chars": "ally" }, { "char_start": 1624, "char_end": 1627, "chars": "a f" }, { "char_start": 1628, "char_end": 1632, "chars": "le, " }, { "char_start": 1633, "char_end": 1640, "chars": "o we ac" }, { "char_start": 1641, "char_end": 1642, "chars": "u" }, { "char_start": 1643, "char_end": 1646, "chars": "lly" }, { "char_start": 1647, "char_end": 1649, "chars": "ex" }, { "char_start": 1650, "char_end": 1651, "chars": "r" }, { "char_start": 1652, "char_end": 1653, "chars": "c" }, { "char_start": 1654, "char_end": 1655, "chars": "." }, { "char_start": 1658, "char_end": 1661, "chars": "}\n\n" }, { "char_start": 1662, "char_end": 1676, "chars": " // We have en" }, { "char_start": 1677, "char_end": 1682, "chars": "ured " }, { "char_start": 1683, "char_end": 1684, "chars": "h" }, { "char_start": 1687, "char_end": 1693, "chars": "clean_" }, { "char_start": 1697, "char_end": 1712, "chars": " will be added " }, { "char_start": 1713, "char_end": 1714, "chars": "o" }, { "char_start": 1715, "char_end": 1716, "chars": "a" }, { "char_start": 1717, "char_end": 1722, "chars": "relat" }, { "char_start": 1723, "char_end": 1726, "chars": "ve " }, { "char_start": 1729, "char_end": 1730, "chars": "h" }, { "char_start": 1731, "char_end": 1733, "chars": "by" }, { "char_start": 1734, "char_end": 1739, "chars": "the\n " }, { "char_start": 1740, "char_end": 1742, "chars": "//" }, { "char_start": 1743, "char_end": 1747, "chars": "time" }, { "char_start": 1748, "char_end": 1750, "chars": "we" }, { "char_start": 1751, "char_end": 1754, "chars": "get" }, { "char_start": 1755, "char_end": 1757, "chars": "he" }, { "char_start": 1759, "char_end": 1763, "chars": ".\n " }, { "char_start": 1764, "char_end": 1770, "chars": "o.appe" }, { "char_start": 1771, "char_end": 1779, "chars": "d(clean_" }, { "char_start": 1780, "char_end": 1781, "chars": "i" }, { "char_start": 1783, "char_end": 1784, "chars": ")" } ] }
github.com/facebook/hhvm/commit/65c95a01541dd2fbc9c978ac53bed235b5376686
hphp/runtime/ext/zip/ext_zip.cpp
cwe-022
new_goal
def new_goal(): """ new goal """ goals_dir_check() click.echo(chalk.blue('Input a single-word name of the goal:')) goal_name = input().strip() if goal_name_exists(goal_name): click.echo(chalk.red( 'A goal with this name already exists. Please type "yoda goals view" to see a list of existing goals')) else: click.echo(chalk.blue('Input description of the goal:')) text = input().strip() click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):')) deadline = input().strip() if os.path.isfile(GOALS_CONFIG_FILE_PATH): setup_data = dict( name=goal_name, text=text, deadline=deadline, status=0 ) append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH) else: setup_data = dict( entries=[ dict( name=goal_name, text=text, deadline=deadline, status=0 ) ] ) input_data(setup_data, GOALS_CONFIG_FILE_PATH) input_data(dict(entries=[]), get_goal_file_path(goal_name))
def new_goal(): """ new goal """ goals_dir_check() goal_name_not_ok = True click.echo(chalk.blue('Input a single-word name of the goal:')) while goal_name_not_ok: goal_name = input().strip() if goal_name.isalnum(): goal_name_not_ok = False else: click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:')) if goal_name_exists(goal_name): click.echo(chalk.red( 'A goal with this name already exists. Please type "yoda goals view" to see a list of existing goals')) else: click.echo(chalk.blue('Input description of the goal:')) text = input().strip() click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):')) incorrect_date_format = True while incorrect_date_format: deadline = input().strip() try: date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d') if date_str != deadline: raise ValueError incorrect_date_format = False except ValueError: click.echo(chalk.red("Incorrect data format, should be YYYY-MM-DD. Please repeat:")) if os.path.isfile(GOALS_CONFIG_FILE_PATH): setup_data = dict( name=goal_name, text=text, deadline=deadline, status=0 ) append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH) else: setup_data = dict( entries=[ dict( name=goal_name, text=text, deadline=deadline, status=0 ) ] ) input_data(setup_data, GOALS_CONFIG_FILE_PATH) input_data(dict(entries=[]), get_goal_file_path(goal_name))
{ "deleted": [ { "line_no": 9, "char_start": 137, "char_end": 169, "line": " goal_name = input().strip()\n" }, { "line_no": 19, "char_start": 535, "char_end": 570, "line": " deadline = input().strip()\n" } ], "added": [ { "line_no": 8, "char_start": 69, "char_end": 97, "line": " goal_name_not_ok = True\n" }, { "line_no": 9, "char_start": 97, "char_end": 98, "line": "\n" }, { "line_no": 11, "char_start": 166, "char_end": 194, "line": " while goal_name_not_ok:\n" }, { "line_no": 12, "char_start": 194, "char_end": 230, "line": " goal_name = input().strip()\n" }, { "line_no": 13, "char_start": 230, "char_end": 262, "line": " if goal_name.isalnum():\n" }, { "line_no": 14, "char_start": 262, "char_end": 299, "line": " goal_name_not_ok = False\n" }, { "line_no": 15, "char_start": 299, "char_end": 313, "line": " else:\n" }, { "line_no": 16, "char_start": 313, "char_end": 420, "line": " click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:'))\n" }, { "line_no": 26, "char_start": 786, "char_end": 823, "line": " incorrect_date_format = True\n" }, { "line_no": 27, "char_start": 823, "char_end": 860, "line": " while incorrect_date_format:\n" }, { "line_no": 28, "char_start": 860, "char_end": 899, "line": " deadline = input().strip()\n" }, { "line_no": 29, "char_start": 899, "char_end": 916, "line": " try:\n" }, { "line_no": 30, "char_start": 916, "char_end": 1013, "line": " date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d')\n" }, { "line_no": 31, "char_start": 1013, "char_end": 1054, "line": " if date_str != deadline:\n" }, { "line_no": 32, "char_start": 1054, "char_end": 1091, "line": " raise ValueError\n" }, { "line_no": 33, "char_start": 1091, "char_end": 1137, "line": " incorrect_date_format = False\n" }, { "line_no": 34, "char_start": 1137, "char_end": 1168, "line": " except ValueError:\n" }, { "line_no": 35, "char_start": 1168, "char_end": 1269, "line": " click.echo(chalk.red(\"Incorrect data format, should be YYYY-MM-DD. Please repeat:\"))\n" } ] }
{ "deleted": [], "added": [ { "char_start": 73, "char_end": 102, "chars": "goal_name_not_ok = True\n\n " }, { "char_start": 170, "char_end": 202, "chars": "while goal_name_not_ok:\n " }, { "char_start": 230, "char_end": 420, "chars": " if goal_name.isalnum():\n goal_name_not_ok = False\n else:\n click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:'))\n" }, { "char_start": 786, "char_end": 864, "chars": " incorrect_date_format = True\n while incorrect_date_format:\n " }, { "char_start": 897, "char_end": 1267, "chars": ")\n try:\n date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d')\n if date_str != deadline:\n raise ValueError\n incorrect_date_format = False\n except ValueError:\n click.echo(chalk.red(\"Incorrect data format, should be YYYY-MM-DD. Please repeat:\")" } ] }
github.com/yoda-pa/yoda/commit/263946316041601de75638ee303a892f2652cf40
modules/goals.py
cwe-022
_inject_admin_password_into_fs
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """ # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd, run_as_root=True) utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'), run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'), run_as_root=True) os.unlink(tmp_shadow)
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """ # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd') shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow') utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True) utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True) os.unlink(tmp_shadow)
{ "deleted": [ { "line_no": 23, "char_start": 689, "char_end": 760, "line": " utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,\n" }, { "line_no": 24, "char_start": 760, "char_end": 796, "line": " run_as_root=True)\n" }, { "line_no": 25, "char_start": 796, "char_end": 867, "line": " utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,\n" }, { "line_no": 26, "char_start": 867, "char_end": 903, "line": " run_as_root=True)\n" }, { "line_no": 28, "char_start": 969, "char_end": 1040, "line": " utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),\n" }, { "line_no": 29, "char_start": 1040, "char_end": 1076, "line": " run_as_root=True)\n" }, { "line_no": 31, "char_start": 1102, "char_end": 1173, "line": " utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),\n" }, { "line_no": 32, "char_start": 1173, "char_end": 1209, "line": " run_as_root=True)\n" } ], "added": [ { "line_no": 23, "char_start": 689, "char_end": 759, "line": " passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd')\n" }, { "line_no": 24, "char_start": 759, "char_end": 829, "line": " shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow')\n" }, { "line_no": 25, "char_start": 829, "char_end": 830, "line": "\n" }, { "line_no": 26, "char_start": 830, "char_end": 897, "line": " utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True)\n" }, { "line_no": 27, "char_start": 897, "char_end": 964, "line": " utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True)\n" }, { "line_no": 29, "char_start": 1030, "char_end": 1097, "line": " utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True)\n" }, { "line_no": 31, "char_start": 1123, "char_end": 1190, "line": " utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True)\n" } ] }
{ "deleted": [ { "char_start": 693, "char_end": 694, "chars": "u" }, { "char_start": 696, "char_end": 701, "chars": "ls.ex" }, { "char_start": 703, "char_end": 704, "chars": "u" }, { "char_start": 705, "char_end": 706, "chars": "e" }, { "char_start": 711, "char_end": 712, "chars": "," }, { "char_start": 714, "char_end": 716, "chars": "s." }, { "char_start": 720, "char_end": 721, "chars": "." }, { "char_start": 744, "char_end": 746, "chars": "')" }, { "char_start": 759, "char_end": 777, "chars": "\n " }, { "char_start": 820, "char_end": 845, "chars": "os.path.join(fs, 'etc', '" }, { "char_start": 851, "char_end": 853, "chars": "')" }, { "char_start": 866, "char_end": 884, "chars": "\n " }, { "char_start": 1005, "char_end": 1030, "chars": "os.path.join(fs, 'etc', '" }, { "char_start": 1036, "char_end": 1038, "chars": "')" }, { "char_start": 1039, "char_end": 1057, "chars": "\n " }, { "char_start": 1138, "char_end": 1163, "chars": "os.path.join(fs, 'etc', '" }, { "char_start": 1169, "char_end": 1171, "chars": "')" }, { "char_start": 1172, "char_end": 1190, "chars": "\n " } ], "added": [ { "char_start": 693, "char_end": 702, "chars": "passwd_pa" }, { "char_start": 703, "char_end": 710, "chars": "h = _jo" }, { "char_start": 711, "char_end": 719, "chars": "n_and_ch" }, { "char_start": 721, "char_end": 725, "chars": "k_pa" }, { "char_start": 726, "char_end": 737, "chars": "h_within_fs" }, { "char_start": 738, "char_end": 742, "chars": "fs, " }, { "char_start": 743, "char_end": 745, "chars": "et" }, { "char_start": 749, "char_end": 752, "chars": "'pa" }, { "char_start": 753, "char_end": 770, "chars": "swd')\n shadow_" }, { "char_start": 774, "char_end": 778, "chars": " = _" }, { "char_start": 782, "char_end": 807, "chars": "_and_check_path_within_fs" }, { "char_start": 820, "char_end": 854, "chars": "shadow')\n\n utils.execute('cp', " }, { "char_start": 860, "char_end": 865, "chars": "_path" }, { "char_start": 927, "char_end": 932, "chars": "_path" }, { "char_start": 1072, "char_end": 1077, "chars": "_path" }, { "char_start": 1165, "char_end": 1170, "chars": "_path" } ] }
github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7
nova/virt/disk/api.py
cwe-022
get_paths
def get_paths(base_path: pathlib.Path): data_file = pathlib.Path(str(base_path) + ".data") metadata_file = pathlib.Path(str(base_path) + ".meta") return data_file, metadata_file
def get_paths(root: str, sub_path: str) \ -> typing.Tuple[pathlib.Path, pathlib.Path]: base_path = flask.safe_join(root, sub_path) data_file = pathlib.Path(base_path + ".data") metadata_file = pathlib.Path(base_path + ".meta") return data_file, metadata_file
{ "deleted": [ { "line_no": 1, "char_start": 0, "char_end": 40, "line": "def get_paths(base_path: pathlib.Path):\n" } ], "added": [ { "line_no": 1, "char_start": 0, "char_end": 42, "line": "def get_paths(root: str, sub_path: str) \\\n" }, { "line_no": 2, "char_start": 42, "char_end": 95, "line": " -> typing.Tuple[pathlib.Path, pathlib.Path]:\n" }, { "line_no": 3, "char_start": 95, "char_end": 143, "line": " base_path = flask.safe_join(root, sub_path)\n" }, { "line_no": 4, "char_start": 143, "char_end": 193, "line": " data_file = pathlib.Path(base_path + \".data\")\n" }, { "line_no": 5, "char_start": 193, "char_end": 247, "line": " metadata_file = pathlib.Path(base_path + \".meta\")\n" } ] }
{ "deleted": [ { "char_start": 18, "char_end": 19, "chars": "_" }, { "char_start": 23, "char_end": 24, "chars": ":" }, { "char_start": 38, "char_end": 39, "chars": ":" }, { "char_start": 69, "char_end": 73, "chars": "str(" }, { "char_start": 82, "char_end": 83, "chars": ")" }, { "char_start": 128, "char_end": 132, "chars": "str(" }, { "char_start": 141, "char_end": 142, "chars": ")" } ], "added": [ { "char_start": 14, "char_end": 27, "chars": "root: str, su" }, { "char_start": 28, "char_end": 30, "chars": "_p" }, { "char_start": 31, "char_end": 35, "chars": "th: " }, { "char_start": 36, "char_end": 64, "chars": "tr) \\\n -> typing.Tupl" }, { "char_start": 65, "char_end": 66, "chars": "[" }, { "char_start": 70, "char_end": 79, "chars": "lib.Path," }, { "char_start": 92, "char_end": 93, "chars": "]" }, { "char_start": 99, "char_end": 147, "chars": "base_path = flask.safe_join(root, sub_path)\n " } ] }
github.com/horazont/xmpp-http-upload/commit/82056540191e89f0cd697c81f57714c00962ed75
xhu.py
cwe-022
compose_path
char *compose_path(ctrl_t *ctrl, char *path) { struct stat st; static char rpath[PATH_MAX]; char *name, *ptr; char dir[PATH_MAX] = { 0 }; strlcpy(dir, ctrl->cwd, sizeof(dir)); DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: ""); if (!path || !strlen(path)) goto check; if (path) { if (path[0] != '/') { if (dir[strlen(dir) - 1] != '/') strlcat(dir, "/", sizeof(dir)); } strlcat(dir, path, sizeof(dir)); } check: while ((ptr = strstr(dir, "//"))) memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1); if (!chrooted) { size_t len = strlen(home); DBG("Server path from CWD: %s", dir); if (len > 0 && home[len - 1] == '/') len--; memmove(dir + len, dir, strlen(dir) + 1); memcpy(dir, home, len); DBG("Resulting non-chroot path: %s", dir); } /* * Handle directories slightly differently, since dirname() on a * directory returns the parent directory. So, just squash .. */ if (!stat(dir, &st) && S_ISDIR(st.st_mode)) { if (!realpath(dir, rpath)) return NULL; } else { /* * Check realpath() of directory containing the file, a * STOR may want to save a new file. Then append the * file and return it. */ name = basename(path); ptr = dirname(dir); memset(rpath, 0, sizeof(rpath)); if (!realpath(ptr, rpath)) { INFO("Failed realpath(%s): %m", ptr); return NULL; } if (rpath[1] != 0) strlcat(rpath, "/", sizeof(rpath)); strlcat(rpath, name, sizeof(rpath)); } if (!chrooted && strncmp(dir, home, strlen(home))) { DBG("Failed non-chroot dir:%s vs home:%s", dir, home); return NULL; } return rpath; }
char *compose_path(ctrl_t *ctrl, char *path) { struct stat st; static char rpath[PATH_MAX]; char *name, *ptr; char dir[PATH_MAX] = { 0 }; strlcpy(dir, ctrl->cwd, sizeof(dir)); DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: ""); if (!path || !strlen(path)) goto check; if (path) { if (path[0] != '/') { if (dir[strlen(dir) - 1] != '/') strlcat(dir, "/", sizeof(dir)); } strlcat(dir, path, sizeof(dir)); } check: while ((ptr = strstr(dir, "//"))) memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1); if (!chrooted) { size_t len = strlen(home); DBG("Server path from CWD: %s", dir); if (len > 0 && home[len - 1] == '/') len--; memmove(dir + len, dir, strlen(dir) + 1); memcpy(dir, home, len); DBG("Resulting non-chroot path: %s", dir); } /* * Handle directories slightly differently, since dirname() on a * directory returns the parent directory. So, just squash .. */ if (!stat(dir, &st) && S_ISDIR(st.st_mode)) { if (!realpath(dir, rpath)) return NULL; } else { /* * Check realpath() of directory containing the file, a * STOR may want to save a new file. Then append the * file and return it. */ name = basename(path); ptr = dirname(dir); memset(rpath, 0, sizeof(rpath)); if (!realpath(ptr, rpath)) { INFO("Failed realpath(%s): %m", ptr); return NULL; } if (rpath[1] != 0) strlcat(rpath, "/", sizeof(rpath)); strlcat(rpath, name, sizeof(rpath)); } if (!chrooted && strncmp(rpath, home, strlen(home))) { DBG("Failed non-chroot dir:%s vs home:%s", dir, home); return NULL; } return rpath; }
{ "deleted": [ { "line_no": 63, "char_start": 1460, "char_end": 1514, "line": "\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n" } ], "added": [ { "line_no": 63, "char_start": 1460, "char_end": 1516, "line": "\tif (!chrooted && strncmp(rpath, home, strlen(home))) {\n" } ] }
{ "deleted": [ { "char_start": 1486, "char_end": 1488, "chars": "di" } ], "added": [ { "char_start": 1487, "char_end": 1491, "chars": "path" } ] }
github.com/troglobit/uftpd/commit/455b47d3756aed162d2d0ef7f40b549f3b5b30fe
src/common.c
cwe-022
valid_id
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_) except (AttributeError, KeyError, TypeError) as e: return False
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: if any(x in id_ for x in ('/', '\\', '\0')): return False return bool(clean_path(opts['pki_dir'], id_)) except (AttributeError, KeyError, TypeError): return False
{ "deleted": [ { "line_no": 6, "char_start": 88, "char_end": 160, "line": " return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)\n" }, { "line_no": 7, "char_start": 160, "char_end": 215, "line": " except (AttributeError, KeyError, TypeError) as e:\n" } ], "added": [ { "line_no": 6, "char_start": 88, "char_end": 141, "line": " if any(x in id_ for x in ('/', '\\\\', '\\0')):\n" }, { "line_no": 7, "char_start": 141, "char_end": 166, "line": " return False\n" }, { "line_no": 8, "char_start": 166, "char_end": 220, "line": " return bool(clean_path(opts['pki_dir'], id_))\n" }, { "line_no": 9, "char_start": 220, "char_end": 270, "line": " except (AttributeError, KeyError, TypeError):\n" } ] }
{ "deleted": [ { "char_start": 141, "char_end": 159, "chars": " and clean_id(id_)" }, { "char_start": 208, "char_end": 213, "chars": " as e" } ], "added": [ { "char_start": 96, "char_end": 174, "chars": "if any(x in id_ for x in ('/', '\\\\', '\\0')):\n return False\n " } ] }
github.com/saltstack/salt/commit/80d90307b07b3703428ecbb7c8bb468e28a9ae6d
salt/utils/verify.py
cwe-022
get
def get(self, path): return static_file(path, self.get_base_path())
def get(self, path): path = self.sanitize_path(path) base_paths = self.get_base_paths() if hasattr(base_paths, 'split'): # String, so go simple base_path = base_paths else: base_path = self.get_first_base(base_paths, path) return static_file(path, base_path)
{ "deleted": [ { "line_no": 2, "char_start": 25, "char_end": 79, "line": " return static_file(path, self.get_base_path())\n" } ], "added": [ { "line_no": 2, "char_start": 25, "char_end": 65, "line": " path = self.sanitize_path(path)\n" }, { "line_no": 3, "char_start": 65, "char_end": 108, "line": " base_paths = self.get_base_paths()\n" }, { "line_no": 4, "char_start": 108, "char_end": 149, "line": " if hasattr(base_paths, 'split'):\n" }, { "line_no": 6, "char_start": 184, "char_end": 219, "line": " base_path = base_paths\n" }, { "line_no": 7, "char_start": 219, "char_end": 233, "line": " else:\n" }, { "line_no": 8, "char_start": 233, "char_end": 295, "line": " base_path = self.get_first_base(base_paths, path)\n" }, { "line_no": 9, "char_start": 295, "char_end": 338, "line": " return static_file(path, base_path)\n" } ] }
{ "deleted": [ { "char_start": 36, "char_end": 37, "chars": "u" }, { "char_start": 44, "char_end": 49, "chars": "ic_fi" }, { "char_start": 51, "char_end": 52, "chars": "(" }, { "char_start": 56, "char_end": 57, "chars": "," }, { "char_start": 77, "char_end": 78, "chars": ")" } ], "added": [ { "char_start": 33, "char_end": 76, "chars": "path = self.sanitize_path(path)\n bas" }, { "char_start": 77, "char_end": 80, "chars": "_pa" }, { "char_start": 81, "char_end": 85, "chars": "hs =" }, { "char_start": 87, "char_end": 93, "chars": "elf.ge" }, { "char_start": 94, "char_end": 101, "chars": "_base_p" }, { "char_start": 103, "char_end": 116, "chars": "hs()\n " }, { "char_start": 118, "char_end": 143, "chars": " hasattr(base_paths, 'spl" }, { "char_start": 144, "char_end": 181, "chars": "t'):\n # String, so go simp" }, { "char_start": 183, "char_end": 250, "chars": "\n base_path = base_paths\n else:\n base_" }, { "char_start": 254, "char_end": 256, "chars": " =" }, { "char_start": 266, "char_end": 277, "chars": "first_base(" }, { "char_start": 286, "char_end": 293, "chars": "s, path" }, { "char_start": 294, "char_end": 337, "chars": "\n return static_file(path, base_path" } ] }
github.com/foxbunny/seagull/commit/1fb790712fe0c1d1957b31e34a8e0e6593af87a7
seagull/routes/app.py
cwe-022
dd_exist
int dd_exist(const struct dump_dir *dd, const char *path) { char *full_path = concat_path_file(dd->dd_dirname, path); int ret = exist_file_dir(full_path); free(full_path); return ret; }
int dd_exist(const struct dump_dir *dd, const char *path) { if (!str_is_correct_filename(path)) error_msg_and_die("Cannot test existence. '%s' is not a valid file name", path); char *full_path = concat_path_file(dd->dd_dirname, path); int ret = exist_file_dir(full_path); free(full_path); return ret; }
{ "deleted": [], "added": [ { "line_no": 3, "char_start": 60, "char_end": 100, "line": " if (!str_is_correct_filename(path))\n" }, { "line_no": 4, "char_start": 100, "char_end": 189, "line": " error_msg_and_die(\"Cannot test existence. '%s' is not a valid file name\", path);\n" }, { "line_no": 5, "char_start": 189, "char_end": 190, "line": "\n" } ] }
{ "deleted": [], "added": [ { "char_start": 64, "char_end": 194, "chars": "if (!str_is_correct_filename(path))\n error_msg_and_die(\"Cannot test existence. '%s' is not a valid file name\", path);\n\n " } ] }
github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277
src/lib/dump_dir.c
cwe-022
is_cgi
def is_cgi(self): """Test whether self.path corresponds to a CGI script, and return a boolean. This function sets self.cgi_info to a tuple (dir, rest) when it returns True, where dir is the directory part before the CGI script name. Note that rest begins with a slash if it is not empty. The default implementation tests whether the path begins with one of the strings in the list self.cgi_directories (and the next character is a '/' or the end of the string). """ path = self.path for x in self.cgi_directories: i = len(x) if path[:i] == x and (not path[i:] or path[i] == '/'): self.cgi_info = path[:i], path[i+1:] return True return False
def is_cgi(self): """Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string). """ splitpath = _url_collapse_path_split(self.path) if splitpath[0] in self.cgi_directories: self.cgi_info = splitpath return True return False
{ "deleted": [ { "line_no": 2, "char_start": 22, "char_end": 85, "line": " \"\"\"Test whether self.path corresponds to a CGI script,\n" }, { "line_no": 3, "char_start": 85, "char_end": 115, "line": " and return a boolean.\n" }, { "line_no": 4, "char_start": 115, "char_end": 116, "line": "\n" }, { "line_no": 5, "char_start": 116, "char_end": 180, "line": " This function sets self.cgi_info to a tuple (dir, rest)\n" }, { "line_no": 6, "char_start": 180, "char_end": 249, "line": " when it returns True, where dir is the directory part before\n" }, { "line_no": 7, "char_start": 249, "char_end": 308, "line": " the CGI script name. Note that rest begins with a\n" }, { "line_no": 8, "char_start": 308, "char_end": 342, "line": " slash if it is not empty.\n" }, { "line_no": 9, "char_start": 342, "char_end": 343, "line": "\n" }, { "line_no": 10, "char_start": 343, "char_end": 401, "line": " The default implementation tests whether the path\n" }, { "line_no": 11, "char_start": 401, "char_end": 452, "line": " begins with one of the strings in the list\n" }, { "line_no": 12, "char_start": 452, "char_end": 514, "line": " self.cgi_directories (and the next character is a '/'\n" }, { "line_no": 13, "char_start": 514, "char_end": 549, "line": " or the end of the string).\n" }, { "line_no": 14, "char_start": 549, "char_end": 561, "line": " \"\"\"\n" }, { "line_no": 16, "char_start": 562, "char_end": 587, "line": " path = self.path\n" }, { "line_no": 18, "char_start": 588, "char_end": 627, "line": " for x in self.cgi_directories:\n" }, { "line_no": 19, "char_start": 627, "char_end": 650, "line": " i = len(x)\n" }, { "line_no": 20, "char_start": 650, "char_end": 717, "line": " if path[:i] == x and (not path[i:] or path[i] == '/'):\n" }, { "line_no": 21, "char_start": 717, "char_end": 770, "line": " self.cgi_info = path[:i], path[i+1:]\n" }, { "line_no": 22, "char_start": 770, "char_end": 798, "line": " return True\n" } ], "added": [ { "line_no": 2, "char_start": 22, "char_end": 85, "line": " \"\"\"Test whether self.path corresponds to a CGI script.\n" }, { "line_no": 4, "char_start": 86, "char_end": 155, "line": " Returns True and updates the cgi_info attribute to the tuple\n" }, { "line_no": 5, "char_start": 155, "char_end": 219, "line": " (dir, rest) if self.path requires running a CGI script.\n" }, { "line_no": 6, "char_start": 219, "char_end": 252, "line": " Returns False otherwise.\n" }, { "line_no": 8, "char_start": 253, "char_end": 321, "line": " The default implementation tests whether the normalized url\n" }, { "line_no": 9, "char_start": 321, "char_end": 389, "line": " path begins with one of the strings in self.cgi_directories\n" }, { "line_no": 10, "char_start": 389, "char_end": 457, "line": " (and the next character is a '/' or the end of the string).\n" }, { "line_no": 11, "char_start": 457, "char_end": 469, "line": " \"\"\"\n" }, { "line_no": 12, "char_start": 469, "char_end": 525, "line": " splitpath = _url_collapse_path_split(self.path)\n" }, { "line_no": 13, "char_start": 525, "char_end": 574, "line": " if splitpath[0] in self.cgi_directories:\n" }, { "line_no": 14, "char_start": 574, "char_end": 612, "line": " self.cgi_info = splitpath\n" }, { "line_no": 15, "char_start": 612, "char_end": 636, "line": " return True\n" } ] }
{ "deleted": [ { "char_start": 83, "char_end": 84, "chars": "," }, { "char_start": 93, "char_end": 98, "chars": "and r" }, { "char_start": 104, "char_end": 110, "chars": "a bool" }, { "char_start": 113, "char_end": 120, "chars": ".\n\n " }, { "char_start": 121, "char_end": 130, "chars": " This f" }, { "char_start": 131, "char_end": 133, "chars": "nc" }, { "char_start": 134, "char_end": 139, "chars": "ion s" }, { "char_start": 140, "char_end": 141, "chars": "t" }, { "char_start": 143, "char_end": 144, "chars": "s" }, { "char_start": 145, "char_end": 148, "chars": "lf." }, { "char_start": 160, "char_end": 161, "chars": "a" }, { "char_start": 167, "char_end": 179, "chars": " (dir, rest)" }, { "char_start": 188, "char_end": 193, "chars": "when " }, { "char_start": 194, "char_end": 196, "chars": "t " }, { "char_start": 197, "char_end": 208, "chars": "eturns True" }, { "char_start": 210, "char_end": 213, "chars": "whe" }, { "char_start": 215, "char_end": 221, "chars": " dir i" }, { "char_start": 222, "char_end": 223, "chars": " " }, { "char_start": 224, "char_end": 226, "chars": "he" }, { "char_start": 227, "char_end": 228, "chars": "d" }, { "char_start": 229, "char_end": 236, "chars": "rectory" }, { "char_start": 239, "char_end": 240, "chars": "r" }, { "char_start": 242, "char_end": 243, "chars": "b" }, { "char_start": 244, "char_end": 246, "chars": "fo" }, { "char_start": 248, "char_end": 250, "chars": "\n " }, { "char_start": 251, "char_end": 255, "chars": " " }, { "char_start": 256, "char_end": 260, "chars": " the" }, { "char_start": 271, "char_end": 276, "chars": " name" }, { "char_start": 277, "char_end": 307, "chars": " Note that rest begins with a" }, { "char_start": 317, "char_end": 318, "chars": "l" }, { "char_start": 320, "char_end": 321, "chars": "h" }, { "char_start": 322, "char_end": 326, "chars": "if i" }, { "char_start": 327, "char_end": 328, "chars": " " }, { "char_start": 330, "char_end": 335, "chars": " not " }, { "char_start": 336, "char_end": 340, "chars": "mpty" }, { "char_start": 396, "char_end": 397, "chars": "p" }, { "char_start": 398, "char_end": 400, "chars": "th" }, { "char_start": 443, "char_end": 460, "chars": "the list\n " }, { "char_start": 513, "char_end": 521, "chars": "\n " }, { "char_start": 561, "char_end": 562, "chars": "\n" }, { "char_start": 586, "char_end": 587, "chars": "\n" }, { "char_start": 597, "char_end": 599, "chars": "or" }, { "char_start": 600, "char_end": 601, "chars": "x" }, { "char_start": 639, "char_end": 733, "chars": "i = len(x)\n if path[:i] == x and (not path[i:] or path[i] == '/'):\n " }, { "char_start": 750, "char_end": 755, "chars": "ath[:" }, { "char_start": 756, "char_end": 759, "chars": "], " }, { "char_start": 763, "char_end": 769, "chars": "[i+1:]" }, { "char_start": 770, "char_end": 774, "chars": " " } ], "added": [ { "char_start": 83, "char_end": 85, "chars": ".\n" }, { "char_start": 94, "char_end": 95, "chars": "R" }, { "char_start": 100, "char_end": 101, "chars": "s" }, { "char_start": 102, "char_end": 106, "chars": "True" }, { "char_start": 109, "char_end": 110, "chars": "d" }, { "char_start": 112, "char_end": 115, "chars": "pda" }, { "char_start": 119, "char_end": 121, "chars": "th" }, { "char_start": 122, "char_end": 123, "chars": " " }, { "char_start": 132, "char_end": 142, "chars": "attribute " }, { "char_start": 145, "char_end": 148, "chars": "the" }, { "char_start": 163, "char_end": 165, "chars": "(d" }, { "char_start": 171, "char_end": 174, "chars": "st)" }, { "char_start": 176, "char_end": 177, "chars": "f" }, { "char_start": 180, "char_end": 183, "chars": "lf." }, { "char_start": 186, "char_end": 187, "chars": "h" }, { "char_start": 188, "char_end": 189, "chars": "r" }, { "char_start": 190, "char_end": 193, "chars": "qui" }, { "char_start": 195, "char_end": 196, "chars": "s" }, { "char_start": 197, "char_end": 204, "chars": "running" }, { "char_start": 205, "char_end": 206, "chars": "a" }, { "char_start": 217, "char_end": 219, "chars": ".\n" }, { "char_start": 220, "char_end": 223, "chars": " " }, { "char_start": 227, "char_end": 228, "chars": "R" }, { "char_start": 230, "char_end": 232, "chars": "ur" }, { "char_start": 235, "char_end": 236, "chars": "F" }, { "char_start": 239, "char_end": 240, "chars": "e" }, { "char_start": 241, "char_end": 242, "chars": "o" }, { "char_start": 243, "char_end": 247, "chars": "herw" }, { "char_start": 306, "char_end": 310, "chars": "norm" }, { "char_start": 311, "char_end": 320, "chars": "lized url" }, { "char_start": 328, "char_end": 333, "chars": " path" }, { "char_start": 388, "char_end": 396, "chars": "\n " }, { "char_start": 477, "char_end": 482, "chars": "split" }, { "char_start": 489, "char_end": 514, "chars": "_url_collapse_path_split(" }, { "char_start": 523, "char_end": 524, "chars": ")" }, { "char_start": 533, "char_end": 534, "chars": "i" }, { "char_start": 536, "char_end": 548, "chars": "splitpath[0]" }, { "char_start": 602, "char_end": 603, "chars": "s" }, { "char_start": 604, "char_end": 605, "chars": "l" }, { "char_start": 606, "char_end": 607, "chars": "t" } ] }
github.com/Ricky-Wilson/Python/commit/c5abced949e6a4b001d1dee321593e74ecadecfe
Lib/CGIHTTPServer.py
cwe-022
deleteKey
def deleteKey(client): """Deletes the specified key. Returns an error if the key doesn't exist """ global BAD_REQUEST global NOT_FOUND validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) if re.search('[^a-zA-Z0-9]', token_data['key']): raise FoxlockError(BAD_REQUEST, 'Invalid key requested') try: os.remove('keys/%s/%s.key' % (client, token_data['key'])) except FileNotFoundError: raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['key']) return "Key '%s' successfully deleted" % token_data['key']
def deleteKey(client): """Deletes the specified key. Returns an error if the key doesn't exist """ global NOT_FOUND validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateKeyName(token_data['key']) try: os.remove('keys/%s/%s.key' % (client, token_data['key'])) except FileNotFoundError: raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['key']) return "Key '%s' successfully deleted" % token_data['key']
{ "deleted": [ { "line_no": 5, "char_start": 102, "char_end": 122, "line": "\tglobal BAD_REQUEST\n" }, { "line_no": 9, "char_start": 165, "char_end": 166, "line": "\n" }, { "line_no": 12, "char_start": 272, "char_end": 273, "line": "\n" }, { "line_no": 13, "char_start": 273, "char_end": 323, "line": "\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n" }, { "line_no": 14, "char_start": 323, "char_end": 382, "line": "\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')\n" } ], "added": [ { "line_no": 10, "char_start": 251, "char_end": 287, "line": "\tvalidateKeyName(token_data['key'])\n" } ] }
{ "deleted": [ { "char_start": 110, "char_end": 130, "chars": "BAD_REQUEST\n\tglobal " }, { "char_start": 165, "char_end": 166, "chars": "\n" }, { "char_start": 272, "char_end": 273, "chars": "\n" }, { "char_start": 275, "char_end": 278, "chars": "f r" }, { "char_start": 279, "char_end": 281, "chars": ".s" }, { "char_start": 283, "char_end": 286, "chars": "rch" }, { "char_start": 287, "char_end": 303, "chars": "'[^a-zA-Z0-9]', " }, { "char_start": 320, "char_end": 380, "chars": "):\n\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested'" } ], "added": [ { "char_start": 120, "char_end": 120, "chars": "" }, { "char_start": 252, "char_end": 255, "chars": "val" }, { "char_start": 256, "char_end": 259, "chars": "dat" }, { "char_start": 260, "char_end": 261, "chars": "K" }, { "char_start": 262, "char_end": 264, "chars": "yN" }, { "char_start": 265, "char_end": 267, "chars": "me" } ] }
github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833
impl.py
cwe-022
set
def set(self, key, value, replace=False): path = os.path.join(self.namespace, key) try: self.etcd.write(path, value, prevExist=replace) except etcd.EtcdAlreadyExist as err: raise CSStoreExists(str(err)) except etcd.EtcdException as err: log_error("Error storing key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to store key')
def set(self, key, value, replace=False): path = self._absolute_key(key) try: self.etcd.write(path, value, prevExist=replace) except etcd.EtcdAlreadyExist as err: raise CSStoreExists(str(err)) except etcd.EtcdException as err: log_error("Error storing key %s: [%r]" % (key, repr(err))) raise CSStoreError('Error occurred while trying to store key')
{ "deleted": [ { "line_no": 2, "char_start": 46, "char_end": 95, "line": " path = os.path.join(self.namespace, key)\n" } ], "added": [ { "line_no": 2, "char_start": 46, "char_end": 85, "line": " path = self._absolute_key(key)\n" } ] }
{ "deleted": [ { "char_start": 61, "char_end": 74, "chars": "os.path.join(" }, { "char_start": 79, "char_end": 80, "chars": "n" }, { "char_start": 81, "char_end": 83, "chars": "me" }, { "char_start": 84, "char_end": 87, "chars": "pac" }, { "char_start": 88, "char_end": 90, "chars": ", " } ], "added": [ { "char_start": 66, "char_end": 67, "chars": "_" }, { "char_start": 68, "char_end": 74, "chars": "bsolut" }, { "char_start": 75, "char_end": 77, "chars": "_k" }, { "char_start": 78, "char_end": 80, "chars": "y(" } ] }
github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4
custodia/store/etcdstore.py
cwe-022
_inject_key_into_fs
def _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = os.path.join(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join(sshdir, 'authorized_keys') key_data = [ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ] utils.execute('tee', '-a', keyfile, process_input=''.join(key_data), run_as_root=True)
def _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join('root', '.ssh', 'authorized_keys') key_data = ''.join([ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ]) _inject_file_into_fs(fs, keyfile, key_data, append=True)
{ "deleted": [ { "line_no": 7, "char_start": 229, "char_end": 275, "line": " sshdir = os.path.join(fs, 'root', '.ssh')\n" }, { "line_no": 11, "char_start": 455, "char_end": 509, "line": " keyfile = os.path.join(sshdir, 'authorized_keys')\n" }, { "line_no": 12, "char_start": 509, "char_end": 526, "line": " key_data = [\n" }, { "line_no": 18, "char_start": 645, "char_end": 651, "line": " ]\n" }, { "line_no": 19, "char_start": 651, "char_end": 691, "line": " utils.execute('tee', '-a', keyfile,\n" }, { "line_no": 20, "char_start": 691, "char_end": 759, "line": " process_input=''.join(key_data), run_as_root=True)\n" } ], "added": [ { "line_no": 7, "char_start": 229, "char_end": 293, "line": " sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh')\n" }, { "line_no": 11, "char_start": 473, "char_end": 474, "line": "\n" }, { "line_no": 12, "char_start": 474, "char_end": 536, "line": " keyfile = os.path.join('root', '.ssh', 'authorized_keys')\n" }, { "line_no": 13, "char_start": 536, "char_end": 537, "line": "\n" }, { "line_no": 14, "char_start": 537, "char_end": 562, "line": " key_data = ''.join([\n" }, { "line_no": 20, "char_start": 681, "char_end": 688, "line": " ])\n" }, { "line_no": 21, "char_start": 688, "char_end": 689, "line": "\n" }, { "line_no": 22, "char_start": 689, "char_end": 749, "line": " _inject_file_into_fs(fs, keyfile, key_data, append=True)\n" } ] }
{ "deleted": [ { "char_start": 243, "char_end": 245, "chars": "s." }, { "char_start": 249, "char_end": 252, "chars": ".jo" }, { "char_start": 485, "char_end": 488, "chars": "dir" }, { "char_start": 655, "char_end": 656, "chars": "u" }, { "char_start": 659, "char_end": 663, "chars": "s.ex" }, { "char_start": 664, "char_end": 666, "chars": "cu" }, { "char_start": 667, "char_end": 668, "chars": "e" }, { "char_start": 669, "char_end": 680, "chars": "'tee', '-a'" }, { "char_start": 690, "char_end": 699, "chars": "\n " }, { "char_start": 700, "char_end": 731, "chars": " process_input=''.join(" }, { "char_start": 739, "char_end": 740, "chars": ")" }, { "char_start": 742, "char_end": 744, "chars": "ru" }, { "char_start": 745, "char_end": 753, "chars": "_as_root" } ], "added": [ { "char_start": 242, "char_end": 244, "chars": "_j" }, { "char_start": 245, "char_end": 258, "chars": "in_and_check_" }, { "char_start": 262, "char_end": 267, "chars": "_with" }, { "char_start": 269, "char_end": 272, "chars": "_fs" }, { "char_start": 473, "char_end": 474, "chars": "\n" }, { "char_start": 501, "char_end": 511, "chars": "'root', '." }, { "char_start": 514, "char_end": 515, "chars": "'" }, { "char_start": 536, "char_end": 537, "chars": "\n" }, { "char_start": 552, "char_end": 560, "chars": "''.join(" }, { "char_start": 686, "char_end": 688, "chars": ")\n" }, { "char_start": 693, "char_end": 694, "chars": "_" }, { "char_start": 695, "char_end": 697, "chars": "nj" }, { "char_start": 700, "char_end": 704, "chars": "_fil" }, { "char_start": 705, "char_end": 708, "chars": "_in" }, { "char_start": 709, "char_end": 716, "chars": "o_fs(fs" }, { "char_start": 738, "char_end": 743, "chars": "ppend" } ] }
github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7
nova/virt/disk/api.py
cwe-022
start
def start(): print("[*] Starting backdoor process") print("[*] Decompressing target to tmp directory...") #subprocess.call("jar -x %s" % target, shell=True) with zipfile.ZipFile(target, 'r') as zip: zip.extractall("tmp") print("[*] Target dumped to tmp directory") print("[*] Modifying manifest file...") oldmain="" man = open("tmp/META-INF/MANIFEST.MF","r").read() with open("tmp/META-INF/MANIFEST.MF","w") as f: for l in man.split("\n"): if "Main-Class" in l: oldmain=l[12:] f.write("Main-Class: %s\n" % "Backdoor") else: f.write("%s\n" % l) print("[*] Manifest file modified") print("[*] Modifying provided backdoor...") inmain=False level=0 bd=open(backdoor, "r").read() with open("tmp/%s" % backdoor,'w') as f: for l in bd.split("\n"): if "main(" in l: inmain=True f.write(l) elif "}" in l and level<2 and inmain: f.write("%s.main(args);}" % oldmain) inmain=False elif "}" in l and level>1 and inmain: level-=1 f.write(l) elif "{" in l and inmain: level+=1 f.write(l) else: f.write(l) print("[*] Provided backdoor successfully modified") print("[*] Compiling modified backdoor...") if subprocess.call("javac -cp tmp/ tmp/%s" % backdoor, shell=True) != 0: print("[!] Error compiling %s" % backdoor) print("[*] Compiled modified backdoor") if(len(oldmain)<1): print("[!] Main-Class manifest attribute not found") else: print("[*] Repackaging target jar file...") createZip("tmp",outfile) print("[*] Target jar successfully repackaged") shutil.rmtree('tmp/')
def start(): print("[*] Starting backdoor process") print("[*] Decompressing target to tmp directory...") #subprocess.call("jar -x %s" % target, shell=True) with zipfile.ZipFile(target, 'r') as zip: zip.extractall("tmp") print("[*] Target dumped to tmp directory") print("[*] Modifying manifest file...") oldmain="" man = open("tmp/META-INF/MANIFEST.MF","r").read() with open("tmp/META-INF/MANIFEST.MF","w") as f: for l in man.split("\n"): if "Main-Class" in l: oldmain=l[12:] f.write("Main-Class: %s\n" % "Backdoor") else: f.write("%s\n" % l) print("[*] Manifest file modified") print("[*] Modifying provided backdoor...") inmain=False level=0 bd=open(backdoor, "r").read() with open("tmp/%s" % backdoor,'w') as f: for l in bd.split("\n"): if "main(" in l: inmain=True f.write(l) elif "}" in l and level<2 and inmain: f.write("%s.main(args);}" % oldmain) inmain=False elif "}" in l and level>1 and inmain: level-=1 f.write(l) elif "{" in l and inmain: level+=1 f.write(l) else: f.write(l) print("[*] Provided backdoor successfully modified") print("[*] Compiling modified backdoor...") #if subprocess.call("javac -cp tmp/ tmp/%s" % backdoor, shell=True) != 0: if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0: print("[!] Error compiling %s" % backdoor) print("[*] Compiled modified backdoor") if(len(oldmain)<1): print("[!] Main-Class manifest attribute not found") else: print("[*] Repackaging target jar file...") createZip("tmp",outfile) print("[*] Target jar successfully repackaged") shutil.rmtree('tmp/')
{ "deleted": [ { "line_no": 44, "char_start": 1462, "char_end": 1539, "line": " if subprocess.call(\"javac -cp tmp/ tmp/%s\" % backdoor, shell=True) != 0:\n" } ], "added": [ { "line_no": 45, "char_start": 1540, "char_end": 1623, "line": " if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0:\n" } ] }
{ "deleted": [], "added": [ { "char_start": 1466, "char_end": 1467, "chars": "#" }, { "char_start": 1531, "char_end": 1614, "chars": "e) != 0:\n if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=Fals" } ] }
github.com/Atticuss/ajar/commit/5ed8aba271ad20e6168f2e3bd6c25ba89b84484f
ajar.py
cwe-078
_map_vol_to_host
def _map_vol_to_host(self, volume_name, host_name): """Create a mapping between a volume to a host.""" LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to ' 'host %(host_name)s') % {'volume_name': volume_name, 'host_name': host_name}) # Check if this volume is already mapped to this host mapping_data = self._get_hostvdisk_mappings(host_name) mapped_flag = False result_lun = '-1' if volume_name in mapping_data: mapped_flag = True result_lun = mapping_data[volume_name]['SCSI_id'] else: lun_used = [int(v['SCSI_id']) for v in mapping_data.values()] lun_used.sort() # Assume all luns are taken to this point, and then try to find # an unused one result_lun = str(len(lun_used)) for index, n in enumerate(lun_used): if n > index: result_lun = str(index) break # Volume is not mapped to host, create a new LUN if not mapped_flag: ssh_cmd = ('svctask mkvdiskhostmap -host %(host_name)s -scsi ' '%(result_lun)s %(volume_name)s' % {'host_name': host_name, 'result_lun': result_lun, 'volume_name': volume_name}) out, err = self._run_ssh(ssh_cmd, check_exit_code=False) if err and err.startswith('CMMVC6071E'): if not self.configuration.storwize_svc_multihostmap_enabled: LOG.error(_('storwize_svc_multihostmap_enabled is set ' 'to False, Not allow multi host mapping')) exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\ 'was not created because the VDisk is '\ 'already mapped to a host.\n"' raise exception.CinderException(data=exception_msg) ssh_cmd = ssh_cmd.replace('mkvdiskhostmap', 'mkvdiskhostmap -force') # try to map one volume to multiple hosts out, err = self._run_ssh(ssh_cmd) LOG.warn(_('volume %s mapping to multi host') % volume_name) self._assert_ssh_return('successfully created' in out, '_map_vol_to_host', ssh_cmd, out, err) else: self._assert_ssh_return('successfully created' in out, '_map_vol_to_host', ssh_cmd, out, err) LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume ' '%(volume_name)s, host %(host_name)s') % {'result_lun': result_lun, 'volume_name': volume_name, 'host_name': host_name}) return result_lun
def _map_vol_to_host(self, volume_name, host_name): """Create a mapping between a volume to a host.""" LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to ' 'host %(host_name)s') % {'volume_name': volume_name, 'host_name': host_name}) # Check if this volume is already mapped to this host mapping_data = self._get_hostvdisk_mappings(host_name) mapped_flag = False result_lun = '-1' if volume_name in mapping_data: mapped_flag = True result_lun = mapping_data[volume_name]['SCSI_id'] else: lun_used = [int(v['SCSI_id']) for v in mapping_data.values()] lun_used.sort() # Assume all luns are taken to this point, and then try to find # an unused one result_lun = str(len(lun_used)) for index, n in enumerate(lun_used): if n > index: result_lun = str(index) break # Volume is not mapped to host, create a new LUN if not mapped_flag: ssh_cmd = ['svctask', 'mkvdiskhostmap', '-host', host_name, '-scsi', result_lun, volume_name] out, err = self._run_ssh(ssh_cmd, check_exit_code=False) if err and err.startswith('CMMVC6071E'): if not self.configuration.storwize_svc_multihostmap_enabled: LOG.error(_('storwize_svc_multihostmap_enabled is set ' 'to False, Not allow multi host mapping')) exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\ 'was not created because the VDisk is '\ 'already mapped to a host.\n"' raise exception.CinderException(data=exception_msg) for i in range(len(ssh_cmd)): if ssh_cmd[i] == 'mkvdiskhostmap': ssh_cmd.insert(i + 1, '-force') # try to map one volume to multiple hosts out, err = self._run_ssh(ssh_cmd) LOG.warn(_('volume %s mapping to multi host') % volume_name) self._assert_ssh_return('successfully created' in out, '_map_vol_to_host', ssh_cmd, out, err) else: self._assert_ssh_return('successfully created' in out, '_map_vol_to_host', ssh_cmd, out, err) LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume ' '%(volume_name)s, host %(host_name)s') % {'result_lun': result_lun, 'volume_name': volume_name, 'host_name': host_name}) return result_lun
{ "deleted": [ { "line_no": 29, "char_start": 1119, "char_end": 1194, "line": " ssh_cmd = ('svctask mkvdiskhostmap -host %(host_name)s -scsi '\n" }, { "line_no": 30, "char_start": 1194, "char_end": 1252, "line": " '%(result_lun)s %(volume_name)s' %\n" }, { "line_no": 31, "char_start": 1252, "char_end": 1300, "line": " {'host_name': host_name,\n" }, { "line_no": 32, "char_start": 1300, "char_end": 1350, "line": " 'result_lun': result_lun,\n" }, { "line_no": 33, "char_start": 1350, "char_end": 1403, "line": " 'volume_name': volume_name})\n" }, { "line_no": 43, "char_start": 2046, "char_end": 2106, "line": " ssh_cmd = ssh_cmd.replace('mkvdiskhostmap',\n" }, { "line_no": 44, "char_start": 2106, "char_end": 2173, "line": " 'mkvdiskhostmap -force')\n" } ], "added": [ { "line_no": 29, "char_start": 1119, "char_end": 1191, "line": " ssh_cmd = ['svctask', 'mkvdiskhostmap', '-host', host_name,\n" }, { "line_no": 30, "char_start": 1191, "char_end": 1248, "line": " '-scsi', result_lun, volume_name]\n" }, { "line_no": 40, "char_start": 1891, "char_end": 1892, "line": "\n" }, { "line_no": 41, "char_start": 1892, "char_end": 1938, "line": " for i in range(len(ssh_cmd)):\n" }, { "line_no": 42, "char_start": 1938, "char_end": 1993, "line": " if ssh_cmd[i] == 'mkvdiskhostmap':\n" }, { "line_no": 43, "char_start": 1993, "char_end": 2049, "line": " ssh_cmd.insert(i + 1, '-force')\n" }, { "line_no": 44, "char_start": 2049, "char_end": 2050, "line": "\n" } ] }
{ "deleted": [ { "char_start": 1141, "char_end": 1142, "chars": "(" }, { "char_start": 1165, "char_end": 1192, "chars": " -host %(host_name)s -scsi " }, { "char_start": 1193, "char_end": 1216, "chars": "\n " }, { "char_start": 1218, "char_end": 1277, "chars": "%(result_lun)s %(volume_name)s' %\n {'" }, { "char_start": 1281, "char_end": 1286, "chars": "_name" }, { "char_start": 1287, "char_end": 1288, "chars": ":" }, { "char_start": 1323, "char_end": 1324, "chars": " " }, { "char_start": 1325, "char_end": 1327, "chars": "re" }, { "char_start": 1328, "char_end": 1335, "chars": "ult_lun" }, { "char_start": 1336, "char_end": 1337, "chars": ":" }, { "char_start": 1349, "char_end": 1369, "chars": "\n " }, { "char_start": 1370, "char_end": 1375, "chars": " '" }, { "char_start": 1386, "char_end": 1402, "chars": "': volume_name})" }, { "char_start": 2070, "char_end": 2071, "chars": "=" }, { "char_start": 2079, "char_end": 2088, "chars": ".replace(" }, { "char_start": 2104, "char_end": 2105, "chars": "," }, { "char_start": 2106, "char_end": 2111, "chars": " " }, { "char_start": 2135, "char_end": 2149, "chars": " '" }, { "char_start": 2150, "char_end": 2152, "chars": "kv" }, { "char_start": 2155, "char_end": 2159, "chars": "khos" }, { "char_start": 2160, "char_end": 2163, "chars": "map" } ], "added": [ { "char_start": 1141, "char_end": 1142, "chars": "[" }, { "char_start": 1150, "char_end": 1152, "chars": "'," }, { "char_start": 1153, "char_end": 1154, "chars": "'" }, { "char_start": 1169, "char_end": 1170, "chars": "," }, { "char_start": 1172, "char_end": 1173, "chars": "-" }, { "char_start": 1178, "char_end": 1179, "chars": "," }, { "char_start": 1215, "char_end": 1216, "chars": "-" }, { "char_start": 1217, "char_end": 1220, "chars": "csi" }, { "char_start": 1221, "char_end": 1222, "chars": "," }, { "char_start": 1246, "char_end": 1247, "chars": "]" }, { "char_start": 1891, "char_end": 1892, "chars": "\n" }, { "char_start": 1908, "char_end": 1927, "chars": "for i in range(len(" }, { "char_start": 1934, "char_end": 1938, "chars": ")):\n" }, { "char_start": 1939, "char_end": 1960, "chars": " if" }, { "char_start": 1968, "char_end": 1975, "chars": "[i] == " }, { "char_start": 1991, "char_end": 1992, "chars": ":" }, { "char_start": 2017, "char_end": 2022, "chars": "ssh_c" }, { "char_start": 2024, "char_end": 2025, "chars": "." }, { "char_start": 2026, "char_end": 2027, "chars": "n" }, { "char_start": 2028, "char_end": 2030, "chars": "er" }, { "char_start": 2031, "char_end": 2033, "chars": "(i" }, { "char_start": 2034, "char_end": 2040, "chars": "+ 1, '" }, { "char_start": 2048, "char_end": 2049, "chars": "\n" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_delete_vdisk
def _delete_vdisk(self, name, force): """Deletes existing vdisks. It is very important to properly take care of mappings before deleting the disk: 1. If no mappings, then it was a vdisk, and can be deleted 2. If it is the source of a flashcopy mapping and copy_rate is 0, then it is a vdisk that has a snapshot. If the force flag is set, delete the mapping and the vdisk, otherwise set the mapping to copy and wait (this will allow users to delete vdisks that have snapshots if/when the upper layers allow it). 3. If it is the target of a mapping and copy_rate is 0, it is a snapshot, and we should properly stop the mapping and delete. 4. If it is the source/target of a mapping and copy_rate is not 0, it is a clone or vdisk created from a snapshot. We wait for the copy to complete (the mapping will be autodeleted) and then delete the vdisk. """ LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name) # Try to delete volume only if found on the storage vdisk_defined = self._is_vdisk_defined(name) if not vdisk_defined: LOG.info(_('warning: Tried to delete vdisk %s but it does not ' 'exist.') % name) return self._ensure_vdisk_no_fc_mappings(name) forceflag = '-force' if force else '' cmd_params = {'frc': forceflag, 'name': name} ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmvdisk self._assert_ssh_return(len(out.strip()) == 0, ('_delete_vdisk %(name)s') % {'name': name}, ssh_cmd, out, err) LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)
def _delete_vdisk(self, name, force): """Deletes existing vdisks. It is very important to properly take care of mappings before deleting the disk: 1. If no mappings, then it was a vdisk, and can be deleted 2. If it is the source of a flashcopy mapping and copy_rate is 0, then it is a vdisk that has a snapshot. If the force flag is set, delete the mapping and the vdisk, otherwise set the mapping to copy and wait (this will allow users to delete vdisks that have snapshots if/when the upper layers allow it). 3. If it is the target of a mapping and copy_rate is 0, it is a snapshot, and we should properly stop the mapping and delete. 4. If it is the source/target of a mapping and copy_rate is not 0, it is a clone or vdisk created from a snapshot. We wait for the copy to complete (the mapping will be autodeleted) and then delete the vdisk. """ LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name) # Try to delete volume only if found on the storage vdisk_defined = self._is_vdisk_defined(name) if not vdisk_defined: LOG.info(_('warning: Tried to delete vdisk %s but it does not ' 'exist.') % name) return self._ensure_vdisk_no_fc_mappings(name) ssh_cmd = ['svctask', 'rmvdisk', '-force', name] if not force: ssh_cmd.remove('-force') out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmvdisk self._assert_ssh_return(len(out.strip()) == 0, ('_delete_vdisk %(name)s') % {'name': name}, ssh_cmd, out, err) LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)
{ "deleted": [ { "line_no": 32, "char_start": 1403, "char_end": 1449, "line": " forceflag = '-force' if force else ''\n" }, { "line_no": 33, "char_start": 1449, "char_end": 1503, "line": " cmd_params = {'frc': forceflag, 'name': name}\n" }, { "line_no": 34, "char_start": 1503, "char_end": 1569, "line": " ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params\n" } ], "added": [ { "line_no": 32, "char_start": 1403, "char_end": 1460, "line": " ssh_cmd = ['svctask', 'rmvdisk', '-force', name]\n" }, { "line_no": 33, "char_start": 1460, "char_end": 1482, "line": " if not force:\n" }, { "line_no": 34, "char_start": 1482, "char_end": 1519, "line": " ssh_cmd.remove('-force')\n" } ] }
{ "deleted": [ { "char_start": 1411, "char_end": 1414, "chars": "for" }, { "char_start": 1415, "char_end": 1420, "chars": "eflag" }, { "char_start": 1424, "char_end": 1428, "chars": "-for" }, { "char_start": 1429, "char_end": 1430, "chars": "e" }, { "char_start": 1433, "char_end": 1434, "chars": "f" }, { "char_start": 1441, "char_end": 1444, "chars": "els" }, { "char_start": 1445, "char_end": 1448, "chars": " ''" }, { "char_start": 1457, "char_end": 1472, "chars": "cmd_params = {'" }, { "char_start": 1473, "char_end": 1477, "chars": "rc':" }, { "char_start": 1483, "char_end": 1488, "chars": "flag," }, { "char_start": 1489, "char_end": 1496, "chars": "'name':" }, { "char_start": 1497, "char_end": 1503, "chars": "name}\n" }, { "char_start": 1518, "char_end": 1530, "chars": " = 'svctask " }, { "char_start": 1533, "char_end": 1539, "chars": "disk %" }, { "char_start": 1543, "char_end": 1551, "chars": ")s %(nam" }, { "char_start": 1552, "char_end": 1554, "chars": ")s" }, { "char_start": 1555, "char_end": 1568, "chars": " % cmd_params" } ], "added": [ { "char_start": 1411, "char_end": 1415, "chars": "ssh_" }, { "char_start": 1416, "char_end": 1418, "chars": "md" }, { "char_start": 1421, "char_end": 1422, "chars": "[" }, { "char_start": 1423, "char_end": 1425, "chars": "sv" }, { "char_start": 1426, "char_end": 1430, "chars": "task" }, { "char_start": 1431, "char_end": 1432, "chars": "," }, { "char_start": 1433, "char_end": 1438, "chars": "'rmvd" }, { "char_start": 1439, "char_end": 1443, "chars": "sk'," }, { "char_start": 1444, "char_end": 1446, "chars": "'-" }, { "char_start": 1451, "char_end": 1453, "chars": "'," }, { "char_start": 1454, "char_end": 1457, "chars": "nam" }, { "char_start": 1458, "char_end": 1459, "chars": "]" }, { "char_start": 1468, "char_end": 1470, "chars": "if" }, { "char_start": 1471, "char_end": 1474, "chars": "not" }, { "char_start": 1476, "char_end": 1477, "chars": "o" }, { "char_start": 1479, "char_end": 1480, "chars": "e" }, { "char_start": 1481, "char_end": 1482, "chars": "\n" }, { "char_start": 1485, "char_end": 1486, "chars": " " }, { "char_start": 1501, "char_end": 1502, "chars": "." }, { "char_start": 1503, "char_end": 1504, "chars": "e" }, { "char_start": 1505, "char_end": 1506, "chars": "o" }, { "char_start": 1507, "char_end": 1508, "chars": "e" }, { "char_start": 1509, "char_end": 1511, "chars": "'-" }, { "char_start": 1512, "char_end": 1513, "chars": "o" }, { "char_start": 1517, "char_end": 1518, "chars": ")" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_cliq_run
def _cliq_run(self, verb, cliq_args, check_exit_code=True): """Runs a CLIQ command over SSH, without doing any result parsing""" cliq_arg_strings = [] for k, v in cliq_args.items(): cliq_arg_strings.append(" %s=%s" % (k, v)) cmd = verb + ''.join(cliq_arg_strings) return self._run_ssh(cmd, check_exit_code)
def _cliq_run(self, verb, cliq_args, check_exit_code=True): """Runs a CLIQ command over SSH, without doing any result parsing""" cmd_list = [verb] for k, v in cliq_args.items(): cmd_list.append("%s=%s" % (k, v)) return self._run_ssh(cmd_list, check_exit_code)
{ "deleted": [ { "line_no": 3, "char_start": 141, "char_end": 171, "line": " cliq_arg_strings = []\n" }, { "line_no": 5, "char_start": 210, "char_end": 265, "line": " cliq_arg_strings.append(\" %s=%s\" % (k, v))\n" }, { "line_no": 6, "char_start": 265, "char_end": 312, "line": " cmd = verb + ''.join(cliq_arg_strings)\n" }, { "line_no": 8, "char_start": 313, "char_end": 363, "line": " return self._run_ssh(cmd, check_exit_code)\n" } ], "added": [ { "line_no": 3, "char_start": 141, "char_end": 167, "line": " cmd_list = [verb]\n" }, { "line_no": 5, "char_start": 206, "char_end": 252, "line": " cmd_list.append(\"%s=%s\" % (k, v))\n" }, { "line_no": 7, "char_start": 253, "char_end": 308, "line": " return self._run_ssh(cmd_list, check_exit_code)\n" } ] }
{ "deleted": [ { "char_start": 152, "char_end": 158, "chars": "q_arg_" }, { "char_start": 160, "char_end": 165, "chars": "rings" }, { "char_start": 225, "char_end": 231, "chars": "q_arg_" }, { "char_start": 233, "char_end": 238, "chars": "rings" }, { "char_start": 247, "char_end": 248, "chars": " " }, { "char_start": 265, "char_end": 312, "chars": " cmd = verb + ''.join(cliq_arg_strings)\n" } ], "added": [ { "char_start": 150, "char_end": 153, "chars": "md_" }, { "char_start": 161, "char_end": 165, "chars": "verb" }, { "char_start": 219, "char_end": 222, "chars": "md_" }, { "char_start": 285, "char_end": 290, "chars": "_list" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp_lefthand.py
cwe-078
_set_qos_rule
def _set_qos_rule(self, qos, vvs_name): max_io = self._get_qos_value(qos, 'maxIOPS') max_bw = self._get_qos_value(qos, 'maxBWS') cli_qos_string = "" if max_io is not None: cli_qos_string += ('-io %s ' % max_io) if max_bw is not None: cli_qos_string += ('-bw %sM ' % max_bw) self._cli_run('setqos %svvset:%s' % (cli_qos_string, vvs_name), None)
def _set_qos_rule(self, qos, vvs_name): max_io = self._get_qos_value(qos, 'maxIOPS') max_bw = self._get_qos_value(qos, 'maxBWS') cli_qos_string = "" if max_io is not None: cli_qos_string += ('-io %s ' % max_io) if max_bw is not None: cli_qos_string += ('-bw %sM ' % max_bw) self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])
{ "deleted": [ { "line_no": 9, "char_start": 342, "char_end": 386, "line": " self._cli_run('setqos %svvset:%s' %\n" }, { "line_no": 10, "char_start": 386, "char_end": 441, "line": " (cli_qos_string, vvs_name), None)\n" } ], "added": [ { "line_no": 9, "char_start": 342, "char_end": 418, "line": " self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])\n" } ] }
{ "deleted": [ { "char_start": 385, "char_end": 407, "chars": "\n " }, { "char_start": 434, "char_end": 440, "chars": ", None" } ], "added": [ { "char_start": 364, "char_end": 365, "chars": "[" }, { "char_start": 372, "char_end": 374, "chars": "'," }, { "char_start": 375, "char_end": 376, "chars": "'" }, { "char_start": 416, "char_end": 417, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
get_lines
def get_lines(command: str) -> List[str]: """ Run a command and return lines of output :param str command: the command to run :returns: list of whitespace-stripped lines output by command """ stdout = get_output(command) return [line.strip().decode() for line in stdout.splitlines()]
def get_lines(command: List[str]) -> List[str]: """ Run a command and return lines of output :param str command: the command to run :returns: list of whitespace-stripped lines output by command """ stdout = get_output(command) return [line.strip() for line in stdout.splitlines()]
{ "deleted": [ { "line_no": 1, "char_start": 0, "char_end": 42, "line": "def get_lines(command: str) -> List[str]:\n" }, { "line_no": 9, "char_start": 246, "char_end": 312, "line": " return [line.strip().decode() for line in stdout.splitlines()]\n" } ], "added": [ { "line_no": 1, "char_start": 0, "char_end": 48, "line": "def get_lines(command: List[str]) -> List[str]:\n" }, { "line_no": 9, "char_start": 252, "char_end": 309, "line": " return [line.strip() for line in stdout.splitlines()]\n" } ] }
{ "deleted": [ { "char_start": 268, "char_end": 277, "chars": "().decode" } ], "added": [ { "char_start": 23, "char_end": 28, "chars": "List[" }, { "char_start": 31, "char_end": 32, "chars": "]" } ] }
github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76
isort/hooks.py
cwe-078
_modify_3par_iscsi_host
def _modify_3par_iscsi_host(self, hostname, iscsi_iqn): # when using -add, you can not send the persona or domain options self.common._cli_run('createhost -iscsi -add %s %s' % (hostname, iscsi_iqn), None)
def _modify_3par_iscsi_host(self, hostname, iscsi_iqn): # when using -add, you can not send the persona or domain options command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn] self.common._cli_run(command)
{ "deleted": [ { "line_no": 3, "char_start": 134, "char_end": 194, "line": " self.common._cli_run('createhost -iscsi -add %s %s'\n" }, { "line_no": 4, "char_start": 194, "char_end": 253, "line": " % (hostname, iscsi_iqn), None)\n" } ], "added": [ { "line_no": 3, "char_start": 134, "char_end": 206, "line": " command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn]\n" }, { "line_no": 4, "char_start": 206, "char_end": 243, "line": " self.common._cli_run(command)\n" } ] }
{ "deleted": [ { "char_start": 142, "char_end": 147, "chars": "self." }, { "char_start": 151, "char_end": 152, "chars": "o" }, { "char_start": 153, "char_end": 163, "chars": "._cli_run(" }, { "char_start": 186, "char_end": 192, "chars": " %s %s" }, { "char_start": 193, "char_end": 222, "chars": "\n " }, { "char_start": 223, "char_end": 226, "chars": "% (" }, { "char_start": 245, "char_end": 247, "chars": ")," }, { "char_start": 248, "char_end": 249, "chars": "N" }, { "char_start": 251, "char_end": 252, "chars": "e" } ], "added": [ { "char_start": 146, "char_end": 147, "chars": "a" }, { "char_start": 148, "char_end": 153, "chars": "d = [" }, { "char_start": 164, "char_end": 166, "chars": "'," }, { "char_start": 167, "char_end": 168, "chars": "'" }, { "char_start": 174, "char_end": 176, "chars": "'," }, { "char_start": 177, "char_end": 178, "chars": "'" }, { "char_start": 183, "char_end": 184, "chars": "," }, { "char_start": 204, "char_end": 206, "chars": "]\n" }, { "char_start": 207, "char_end": 223, "chars": " self.comm" }, { "char_start": 225, "char_end": 242, "chars": "._cli_run(command" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_iscsi.py
cwe-078
run_interactive_shell_command
@contextmanager def run_interactive_shell_command(command, **kwargs): """ Runs a command in shell and provides stdout, stderr and stdin streams. This function creates a context manager that sets up the process, returns to caller, closes streams and waits for process to exit on leaving. The process is opened in `universal_newlines` mode. :param command: The command to run on shell. :param kwargs: Additional keyword arguments to pass to `subprocess.Popen` that is used to spawn the process (except `shell`, `stdout`, `stderr`, `stdin` and `universal_newlines`, a `TypeError` is raised then). :return: A context manager yielding the process started from the command. """ process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE, universal_newlines=True, **kwargs) try: yield process finally: process.stdout.close() process.stderr.close() process.stdin.close() process.wait()
@contextmanager def run_interactive_shell_command(command, **kwargs): """ Runs a single command in shell and provides stdout, stderr and stdin streams. This function creates a context manager that sets up the process (using `subprocess.Popen()`), returns to caller, closes streams and waits for process to exit on leaving. Shell execution is disabled by default (so no shell expansion takes place). If you want to turn shell execution on, you can pass `shell=True` like you would do for `subprocess.Popen()`. The process is opened in `universal_newlines` mode by default. :param command: The command to run on shell. This parameter can either be a sequence of arguments that are directly passed to the process or a string. A string gets splitted beforehand using `shlex.split()`. :param kwargs: Additional keyword arguments to pass to `subprocess.Popen` that is used to spawn the process (except `stdout`, `stderr`, `stdin` and `universal_newlines`, a `TypeError` is raised then). :return: A context manager yielding the process started from the command. """ if isinstance(command, str): command = shlex.split(command) process = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE, universal_newlines=True, **kwargs) try: yield process finally: process.stdout.close() process.stderr.close() process.stdin.close() process.wait()
{ "deleted": [ { "line_no": 4, "char_start": 78, "char_end": 153, "line": " Runs a command in shell and provides stdout, stderr and stdin streams.\n" }, { "line_no": 6, "char_start": 154, "char_end": 232, "line": " This function creates a context manager that sets up the process, returns\n" }, { "line_no": 7, "char_start": 232, "char_end": 304, "line": " to caller, closes streams and waits for process to exit on leaving.\n" }, { "line_no": 9, "char_start": 305, "char_end": 361, "line": " The process is opened in `universal_newlines` mode.\n" }, { "line_no": 11, "char_start": 362, "char_end": 411, "line": " :param command: The command to run on shell.\n" }, { "line_no": 13, "char_start": 490, "char_end": 561, "line": " that is used to spawn the process (except `shell`,\n" }, { "line_no": 14, "char_start": 561, "char_end": 637, "line": " `stdout`, `stderr`, `stdin` and `universal_newlines`, a\n" }, { "line_no": 15, "char_start": 637, "char_end": 686, "line": " `TypeError` is raised then).\n" }, { "line_no": 20, "char_start": 828, "char_end": 860, "line": " shell=True,\n" } ], "added": [ { "line_no": 4, "char_start": 78, "char_end": 151, "line": " Runs a single command in shell and provides stdout, stderr and stdin\n" }, { "line_no": 5, "char_start": 151, "char_end": 164, "line": " streams.\n" }, { "line_no": 7, "char_start": 165, "char_end": 241, "line": " This function creates a context manager that sets up the process (using\n" }, { "line_no": 8, "char_start": 241, "char_end": 316, "line": " `subprocess.Popen()`), returns to caller, closes streams and waits for\n" }, { "line_no": 9, "char_start": 316, "char_end": 348, "line": " process to exit on leaving.\n" }, { "line_no": 11, "char_start": 349, "char_end": 429, "line": " Shell execution is disabled by default (so no shell expansion takes place).\n" }, { "line_no": 12, "char_start": 429, "char_end": 508, "line": " If you want to turn shell execution on, you can pass `shell=True` like you\n" }, { "line_no": 13, "char_start": 508, "char_end": 547, "line": " would do for `subprocess.Popen()`.\n" }, { "line_no": 15, "char_start": 548, "char_end": 615, "line": " The process is opened in `universal_newlines` mode by default.\n" }, { "line_no": 16, "char_start": 615, "char_end": 616, "line": "\n" }, { "line_no": 17, "char_start": 616, "char_end": 691, "line": " :param command: The command to run on shell. This parameter can either\n" }, { "line_no": 18, "char_start": 691, "char_end": 766, "line": " be a sequence of arguments that are directly passed to\n" }, { "line_no": 19, "char_start": 766, "char_end": 845, "line": " the process or a string. A string gets splitted beforehand\n" }, { "line_no": 20, "char_start": 845, "char_end": 888, "line": " using `shlex.split()`.\n" }, { "line_no": 22, "char_start": 967, "char_end": 1039, "line": " that is used to spawn the process (except `stdout`,\n" }, { "line_no": 23, "char_start": 1039, "char_end": 1117, "line": " `stderr`, `stdin` and `universal_newlines`, a `TypeError`\n" }, { "line_no": 24, "char_start": 1117, "char_end": 1154, "line": " is raised then).\n" }, { "line_no": 28, "char_start": 1267, "char_end": 1300, "line": " if isinstance(command, str):\n" }, { "line_no": 29, "char_start": 1300, "char_end": 1339, "line": " command = shlex.split(command)\n" }, { "line_no": 30, "char_start": 1339, "char_end": 1340, "line": "\n" } ] }
{ "deleted": [ { "char_start": 231, "char_end": 235, "chars": "\n " }, { "char_start": 554, "char_end": 558, "chars": "hell" }, { "char_start": 580, "char_end": 590, "chars": " `stdout`," }, { "char_start": 656, "char_end": 668, "chars": " `TypeError`" }, { "char_start": 803, "char_end": 808, "chars": "proce" }, { "char_start": 810, "char_end": 816, "chars": " = Pop" }, { "char_start": 817, "char_end": 818, "chars": "n" }, { "char_start": 844, "char_end": 850, "chars": " sh" }, { "char_start": 851, "char_end": 858, "chars": "ll=True" } ], "added": [ { "char_start": 89, "char_end": 96, "chars": "single " }, { "char_start": 150, "char_end": 154, "chars": "\n " }, { "char_start": 233, "char_end": 266, "chars": " (using\n `subprocess.Popen()`)" }, { "char_start": 315, "char_end": 319, "chars": "\n " }, { "char_start": 353, "char_end": 552, "chars": "Shell execution is disabled by default (so no shell expansion takes place).\n If you want to turn shell execution on, you can pass `shell=True` like you\n would do for `subprocess.Popen()`.\n\n " }, { "char_start": 602, "char_end": 613, "chars": " by default" }, { "char_start": 664, "char_end": 887, "chars": " This parameter can either\n be a sequence of arguments that are directly passed to\n the process or a string. A string gets splitted beforehand\n using `shlex.split()`." }, { "char_start": 1031, "char_end": 1036, "chars": "tdout" }, { "char_start": 1105, "char_end": 1117, "chars": "`TypeError`\n" }, { "char_start": 1271, "char_end": 1275, "chars": "if i" }, { "char_start": 1276, "char_end": 1278, "chars": "in" }, { "char_start": 1279, "char_end": 1283, "chars": "tanc" }, { "char_start": 1293, "char_end": 1299, "chars": " str):" }, { "char_start": 1308, "char_end": 1315, "chars": "command" }, { "char_start": 1316, "char_end": 1317, "chars": "=" }, { "char_start": 1318, "char_end": 1340, "chars": "shlex.split(command)\n\n" }, { "char_start": 1344, "char_end": 1348, "chars": "proc" }, { "char_start": 1349, "char_end": 1352, "chars": "ss " }, { "char_start": 1353, "char_end": 1357, "chars": " Pop" }, { "char_start": 1358, "char_end": 1367, "chars": "n(command" } ] }
github.com/coala/coala/commit/adc94c745e4d9f792fd9c9791c7b4cd8790d0d2f
coalib/misc/Shell.py
cwe-078
delete_video
@app.route('/delete_video/<filename>') def delete_video(filename): if 'username' in session: #os.remove("static/videos/{}".format(filename)) print(session['username'], file=sys.stdout) data=users.query.filter_by(Username=session['username']).first() video=Video.query.filter_by(UserID=data.UserID,Name=filename).first() if video != None: os.remove("static/videos/{}".format(filename)) db.session.delete(video) db.session.commit() else: return "Don't delete other people's videos!" return redirect(url_for('upload')) return "test"
@app.route('/delete_video/<filename>') def delete_video(filename): if 'username' in session: #os.remove("static/videos/{}".format(filename)) print(session['username'], file=sys.stdout) data=users.query.filter_by(Username=session['username']).first() video=Video.query.filter_by(UserID=data.UserID,Name=filename).first() if video != None: #os.remove("static/videos/{}".format(filename)) os.system("rm static/videos/{}".format(filename)) db.session.delete(video) db.session.commit() else: return "Don't delete other people's videos!" return redirect(url_for('upload')) return "test"
{ "deleted": [ { "line_no": 9, "char_start": 349, "char_end": 399, "line": "\t\t\tos.remove(\"static/videos/{}\".format(filename))\n" } ], "added": [ { "line_no": 10, "char_start": 400, "char_end": 453, "line": "\t\t\tos.system(\"rm static/videos/{}\".format(filename))\n" } ] }
{ "deleted": [], "added": [ { "char_start": 352, "char_end": 353, "chars": "#" }, { "char_start": 364, "char_end": 417, "chars": "static/videos/{}\".format(filename))\n\t\t\tos.system(\"rm " } ] }
github.com/jmarcello97/CSEC-380-Project/commit/05dcd628aa5879b6e4979c43e7c635075975de09
Trialwebsite/app/app.py
cwe-078
whitelist
def whitelist(users: str): for user in users.split(): call(WHITELIST_COMMAND_TEMPLATE.format(user))
def whitelist(channel: discord.TextChannel, users: str): for user in users.split(): if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408 await channel.send('\'{}\' is not a valid Minecraft username'.format(user)) else: call(WHITELIST_COMMAND_TEMPLATE.format(user))
{ "deleted": [ { "line_no": 1, "char_start": 0, "char_end": 27, "line": "def whitelist(users: str):\n" }, { "line_no": 3, "char_start": 58, "char_end": 111, "line": " call(WHITELIST_COMMAND_TEMPLATE.format(user))\n" } ], "added": [ { "line_no": 1, "char_start": 0, "char_end": 57, "line": "def whitelist(channel: discord.TextChannel, users: str):\n" }, { "line_no": 3, "char_start": 88, "char_end": 243, "line": " if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408\n" }, { "line_no": 4, "char_start": 243, "char_end": 331, "line": " await channel.send('\\'{}\\' is not a valid Minecraft username'.format(user))\n" }, { "line_no": 5, "char_start": 331, "char_end": 345, "line": " else:\n" }, { "line_no": 6, "char_start": 345, "char_end": 402, "line": " call(WHITELIST_COMMAND_TEMPLATE.format(user))\n" } ] }
{ "deleted": [], "added": [ { "char_start": 14, "char_end": 44, "chars": "channel: discord.TextChannel, " }, { "char_start": 88, "char_end": 349, "chars": " if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408\n await channel.send('\\'{}\\' is not a valid Minecraft username'.format(user))\n else:\n " } ] }
github.com/thomotron/Gatekeep/commit/955660f9b3dc336ab0d5dfb4392b3ab6deac6b25
bot.py
cwe-078
test_create_host
def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -persona 1 -domain (\'OpenStack\',) ' 'fakehost 123456789012345 123456789054321') _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)
def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', '123456789012345', '123456789054321']) _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)
{ "deleted": [ { "line_no": 13, "char_start": 501, "char_end": 554, "line": " show_host_cmd = 'showhost -verbose fakehost'\n" }, { "line_no": 16, "char_start": 635, "char_end": 712, "line": " create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n" }, { "line_no": 17, "char_start": 712, "char_end": 783, "line": " 'fakehost 123456789012345 123456789054321')\n" } ], "added": [ { "line_no": 13, "char_start": 501, "char_end": 562, "line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n" }, { "line_no": 16, "char_start": 643, "char_end": 713, "line": " create_host_cmd = (['createhost', '-persona', '1', '-domain',\n" }, { "line_no": 17, "char_start": 713, "char_end": 788, "line": " ('OpenStack',), 'fakehost', '123456789012345',\n" }, { "line_no": 18, "char_start": 788, "char_end": 836, "line": " '123456789054321'])\n" } ] }
{ "deleted": [ { "char_start": 692, "char_end": 706, "chars": " (\\'OpenStack\\" }, { "char_start": 708, "char_end": 711, "chars": ") '" } ], "added": [ { "char_start": 525, "char_end": 526, "chars": "[" }, { "char_start": 535, "char_end": 537, "chars": "'," }, { "char_start": 538, "char_end": 539, "chars": "'" }, { "char_start": 547, "char_end": 549, "chars": "'," }, { "char_start": 550, "char_end": 551, "chars": "'" }, { "char_start": 560, "char_end": 561, "chars": "]" }, { "char_start": 670, "char_end": 671, "chars": "[" }, { "char_start": 682, "char_end": 684, "chars": "'," }, { "char_start": 685, "char_end": 686, "chars": "'" }, { "char_start": 694, "char_end": 696, "chars": "'," }, { "char_start": 697, "char_end": 698, "chars": "'" }, { "char_start": 699, "char_end": 701, "chars": "'," }, { "char_start": 702, "char_end": 703, "chars": "'" }, { "char_start": 740, "char_end": 757, "chars": " ('OpenStack',), " }, { "char_start": 766, "char_end": 768, "chars": "'," }, { "char_start": 769, "char_end": 770, "chars": "'" }, { "char_start": 785, "char_end": 798, "chars": "',\n " }, { "char_start": 799, "char_end": 817, "chars": " '" }, { "char_start": 833, "char_end": 834, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/tests/test_hp3par.py
cwe-078
do_setup
def do_setup(self, ctxt): """Check that we have all configuration details from the storage.""" LOG.debug(_('enter: do_setup')) self._context = ctxt # Validate that the pool exists ssh_cmd = 'svcinfo lsmdiskgrp -delim ! -nohdr' out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) search_text = '!%s!' % self.configuration.storwize_svc_volpool_name if search_text not in out: raise exception.InvalidInput( reason=(_('pool %s doesn\'t exist') % self.configuration.storwize_svc_volpool_name)) # Check if compression is supported self._compression_enabled = False try: ssh_cmd = 'svcinfo lslicense -delim !' out, err = self._run_ssh(ssh_cmd) license_lines = out.strip().split('\n') for license_line in license_lines: name, foo, value = license_line.partition('!') if name in ('license_compression_enclosures', 'license_compression_capacity') and value != '0': self._compression_enabled = True break except exception.ProcessExecutionError: LOG.exception(_('Failed to get license information.')) # Get the iSCSI and FC names of the Storwize/SVC nodes ssh_cmd = 'svcinfo lsnode -delim !' out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) nodes = out.strip().split('\n') self._assert_ssh_return(len(nodes), 'do_setup', ssh_cmd, out, err) header = nodes.pop(0) for node_line in nodes: try: node_data = self._get_hdr_dic(header, node_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('do_setup', ssh_cmd, out, err) node = {} try: node['id'] = node_data['id'] node['name'] = node_data['name'] node['IO_group'] = node_data['IO_group_id'] node['iscsi_name'] = node_data['iscsi_name'] node['WWNN'] = node_data['WWNN'] node['status'] = node_data['status'] node['WWPN'] = [] node['ipv4'] = [] node['ipv6'] = [] node['enabled_protocols'] = [] if node['status'] == 'online': self._storage_nodes[node['id']] = node except KeyError: self._handle_keyerror('lsnode', header) # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes self._get_iscsi_ip_addrs() self._get_fc_wwpns() # For each node, check what connection modes it supports. Delete any # nodes that do not support any types (may be partially configured). to_delete = [] for k, node in self._storage_nodes.iteritems(): if ((len(node['ipv4']) or len(node['ipv6'])) and len(node['iscsi_name'])): node['enabled_protocols'].append('iSCSI') self._enabled_protocols.add('iSCSI') if len(node['WWPN']): node['enabled_protocols'].append('FC') self._enabled_protocols.add('FC') if not len(node['enabled_protocols']): to_delete.append(k) for delkey in to_delete: del self._storage_nodes[delkey] # Make sure we have at least one node configured self._driver_assert(len(self._storage_nodes), _('do_setup: No configured nodes')) LOG.debug(_('leave: do_setup'))
def do_setup(self, ctxt): """Check that we have all configuration details from the storage.""" LOG.debug(_('enter: do_setup')) self._context = ctxt # Validate that the pool exists ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-delim', '!', '-nohdr'] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) search_text = '!%s!' % self.configuration.storwize_svc_volpool_name if search_text not in out: raise exception.InvalidInput( reason=(_('pool %s doesn\'t exist') % self.configuration.storwize_svc_volpool_name)) # Check if compression is supported self._compression_enabled = False try: ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) license_lines = out.strip().split('\n') for license_line in license_lines: name, foo, value = license_line.partition('!') if name in ('license_compression_enclosures', 'license_compression_capacity') and value != '0': self._compression_enabled = True break except exception.ProcessExecutionError: LOG.exception(_('Failed to get license information.')) # Get the iSCSI and FC names of the Storwize/SVC nodes ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) nodes = out.strip().split('\n') self._assert_ssh_return(len(nodes), 'do_setup', ssh_cmd, out, err) header = nodes.pop(0) for node_line in nodes: try: node_data = self._get_hdr_dic(header, node_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('do_setup', ssh_cmd, out, err) node = {} try: node['id'] = node_data['id'] node['name'] = node_data['name'] node['IO_group'] = node_data['IO_group_id'] node['iscsi_name'] = node_data['iscsi_name'] node['WWNN'] = node_data['WWNN'] node['status'] = node_data['status'] node['WWPN'] = [] node['ipv4'] = [] node['ipv6'] = [] node['enabled_protocols'] = [] if node['status'] == 'online': self._storage_nodes[node['id']] = node except KeyError: self._handle_keyerror('lsnode', header) # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes self._get_iscsi_ip_addrs() self._get_fc_wwpns() # For each node, check what connection modes it supports. Delete any # nodes that do not support any types (may be partially configured). to_delete = [] for k, node in self._storage_nodes.iteritems(): if ((len(node['ipv4']) or len(node['ipv6'])) and len(node['iscsi_name'])): node['enabled_protocols'].append('iSCSI') self._enabled_protocols.add('iSCSI') if len(node['WWPN']): node['enabled_protocols'].append('FC') self._enabled_protocols.add('FC') if not len(node['enabled_protocols']): to_delete.append(k) for delkey in to_delete: del self._storage_nodes[delkey] # Make sure we have at least one node configured self._driver_assert(len(self._storage_nodes), _('do_setup: No configured nodes')) LOG.debug(_('leave: do_setup'))
{ "deleted": [ { "line_no": 8, "char_start": 218, "char_end": 273, "line": " ssh_cmd = 'svcinfo lsmdiskgrp -delim ! -nohdr'\n" }, { "line_no": 21, "char_start": 806, "char_end": 857, "line": " ssh_cmd = 'svcinfo lslicense -delim !'\n" }, { "line_no": 34, "char_start": 1463, "char_end": 1507, "line": " ssh_cmd = 'svcinfo lsnode -delim !'\n" } ], "added": [ { "line_no": 8, "char_start": 218, "char_end": 287, "line": " ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-delim', '!', '-nohdr']\n" }, { "line_no": 21, "char_start": 820, "char_end": 882, "line": " ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!']\n" }, { "line_no": 34, "char_start": 1488, "char_end": 1543, "line": " ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!']\n" } ] }
{ "deleted": [], "added": [ { "char_start": 236, "char_end": 237, "chars": "[" }, { "char_start": 245, "char_end": 247, "chars": "'," }, { "char_start": 248, "char_end": 249, "chars": "'" }, { "char_start": 259, "char_end": 261, "chars": "'," }, { "char_start": 262, "char_end": 263, "chars": "'" }, { "char_start": 269, "char_end": 271, "chars": "'," }, { "char_start": 272, "char_end": 273, "chars": "'" }, { "char_start": 274, "char_end": 276, "chars": "'," }, { "char_start": 277, "char_end": 278, "chars": "'" }, { "char_start": 285, "char_end": 286, "chars": "]" }, { "char_start": 842, "char_end": 843, "chars": "[" }, { "char_start": 851, "char_end": 853, "chars": "'," }, { "char_start": 854, "char_end": 855, "chars": "'" }, { "char_start": 864, "char_end": 866, "chars": "'," }, { "char_start": 867, "char_end": 868, "chars": "'" }, { "char_start": 874, "char_end": 876, "chars": "'," }, { "char_start": 877, "char_end": 878, "chars": "'" }, { "char_start": 880, "char_end": 881, "chars": "]" }, { "char_start": 1506, "char_end": 1507, "chars": "[" }, { "char_start": 1515, "char_end": 1517, "chars": "'," }, { "char_start": 1518, "char_end": 1519, "chars": "'" }, { "char_start": 1525, "char_end": 1527, "chars": "'," }, { "char_start": 1528, "char_end": 1529, "chars": "'" }, { "char_start": 1535, "char_end": 1537, "chars": "'," }, { "char_start": 1538, "char_end": 1539, "chars": "'" }, { "char_start": 1541, "char_end": 1542, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_execute_command_and_parse_attributes
def _execute_command_and_parse_attributes(self, ssh_cmd): """Execute command on the Storwize/SVC and parse attributes. Exception is raised if the information from the system can not be obtained. """ LOG.debug(_('enter: _execute_command_and_parse_attributes: ' ' command %s') % ssh_cmd) try: out, err = self._run_ssh(ssh_cmd) except exception.ProcessExecutionError as e: # Didn't get details from the storage, return None LOG.error(_('CLI Exception output:\n command: %(cmd)s\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'cmd': ssh_cmd, 'out': e.stdout, 'err': e.stderr}) return None self._assert_ssh_return(len(out), '_execute_command_and_parse_attributes', ssh_cmd, out, err) attributes = {} for attrib_line in out.split('\n'): # If '!' not found, return the string and two empty strings attrib_name, foo, attrib_value = attrib_line.partition('!') if attrib_name is not None and len(attrib_name.strip()): attributes[attrib_name] = attrib_value LOG.debug(_('leave: _execute_command_and_parse_attributes:\n' 'command: %(cmd)s\n' 'attributes: %(attr)s') % {'cmd': ssh_cmd, 'attr': str(attributes)}) return attributes
def _execute_command_and_parse_attributes(self, ssh_cmd): """Execute command on the Storwize/SVC and parse attributes. Exception is raised if the information from the system can not be obtained. """ LOG.debug(_('enter: _execute_command_and_parse_attributes: ' ' command %s') % str(ssh_cmd)) try: out, err = self._run_ssh(ssh_cmd) except exception.ProcessExecutionError as e: # Didn't get details from the storage, return None LOG.error(_('CLI Exception output:\n command: %(cmd)s\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'cmd': ssh_cmd, 'out': e.stdout, 'err': e.stderr}) return None self._assert_ssh_return(len(out), '_execute_command_and_parse_attributes', ssh_cmd, out, err) attributes = {} for attrib_line in out.split('\n'): # If '!' not found, return the string and two empty strings attrib_name, foo, attrib_value = attrib_line.partition('!') if attrib_name is not None and len(attrib_name.strip()): attributes[attrib_name] = attrib_value LOG.debug(_('leave: _execute_command_and_parse_attributes:\n' 'command: %(cmd)s\n' 'attributes: %(attr)s') % {'cmd': str(ssh_cmd), 'attr': str(attributes)}) return attributes
{ "deleted": [ { "line_no": 10, "char_start": 307, "char_end": 353, "line": " ' command %s') % ssh_cmd)\n" }, { "line_no": 36, "char_start": 1465, "char_end": 1502, "line": " % {'cmd': ssh_cmd,\n" } ], "added": [ { "line_no": 10, "char_start": 307, "char_end": 358, "line": " ' command %s') % str(ssh_cmd))\n" }, { "line_no": 36, "char_start": 1470, "char_end": 1512, "line": " % {'cmd': str(ssh_cmd),\n" } ] }
{ "deleted": [], "added": [ { "char_start": 345, "char_end": 349, "chars": "tr(s" }, { "char_start": 355, "char_end": 356, "chars": ")" }, { "char_start": 1499, "char_end": 1503, "chars": "tr(s" }, { "char_start": 1509, "char_end": 1510, "chars": ")" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
test_get_iscsi_ip_active
def test_get_iscsi_ip_active(self): self.flags(lock_path=self.tempdir) #record set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_port_cmd = 'showport' _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = 'showport -iscsi' _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = 'showport -iscsiname' _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) self.mox.ReplayAll() config = self.setup_configuration() config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) #record self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_vlun_cmd = 'showvlun -a -host fakehost' _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), '']) self.mox.ReplayAll() ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.253')
def test_get_iscsi_ip_active(self): self.flags(lock_path=self.tempdir) #record set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_port_cmd = ['showport'] _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsi'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsiname'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) self.mox.ReplayAll() config = self.setup_configuration() config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) #record self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost'] _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), '']) self.mox.ReplayAll() ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.253')
{ "deleted": [ { "line_no": 9, "char_start": 290, "char_end": 325, "line": " show_port_cmd = 'showport'\n" }, { "line_no": 12, "char_start": 397, "char_end": 441, "line": " show_port_i_cmd = 'showport -iscsi'\n" }, { "line_no": 16, "char_start": 579, "char_end": 627, "line": " show_port_i_cmd = 'showport -iscsiname'\n" }, { "line_no": 30, "char_start": 1105, "char_end": 1158, "line": " show_vlun_cmd = 'showvlun -a -host fakehost'\n" } ], "added": [ { "line_no": 9, "char_start": 290, "char_end": 327, "line": " show_port_cmd = ['showport']\n" }, { "line_no": 12, "char_start": 399, "char_end": 448, "line": " show_port_i_cmd = ['showport', '-iscsi']\n" }, { "line_no": 16, "char_start": 586, "char_end": 639, "line": " show_port_i_cmd = ['showport', '-iscsiname']\n" }, { "line_no": 30, "char_start": 1117, "char_end": 1181, "line": " show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n" } ] }
{ "deleted": [], "added": [ { "char_start": 314, "char_end": 315, "chars": "[" }, { "char_start": 325, "char_end": 326, "chars": "]" }, { "char_start": 425, "char_end": 426, "chars": "[" }, { "char_start": 435, "char_end": 437, "chars": "'," }, { "char_start": 438, "char_end": 439, "chars": "'" }, { "char_start": 446, "char_end": 447, "chars": "]" }, { "char_start": 612, "char_end": 613, "chars": "[" }, { "char_start": 622, "char_end": 624, "chars": "'," }, { "char_start": 625, "char_end": 626, "chars": "'" }, { "char_start": 637, "char_end": 638, "chars": "]" }, { "char_start": 1141, "char_end": 1142, "chars": "[" }, { "char_start": 1151, "char_end": 1153, "chars": "'," }, { "char_start": 1154, "char_end": 1155, "chars": "'" }, { "char_start": 1157, "char_end": 1159, "chars": "'," }, { "char_start": 1160, "char_end": 1161, "chars": "'" }, { "char_start": 1166, "char_end": 1168, "chars": "'," }, { "char_start": 1169, "char_end": 1170, "chars": "'" }, { "char_start": 1179, "char_end": 1180, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/tests/test_hp3par.py
cwe-078
_find_host_from_wwpn
def _find_host_from_wwpn(self, connector): for wwpn in connector['wwpns']: ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): # This WWPN is not in use continue host_lines = out.strip().split('\n') header = host_lines.pop(0).split('!') self._assert_ssh_return('remote_wwpn' in header and 'name' in header, '_find_host_from_wwpn', ssh_cmd, out, err) rmt_wwpn_idx = header.index('remote_wwpn') name_idx = header.index('name') wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines) if wwpn in wwpns: # All the wwpns will be the mapping for the same # host from this WWPN-based query. Just pick # the name from first line. hostname = host_lines[0].split('!')[name_idx] return hostname # Didn't find a host return None
def _find_host_from_wwpn(self, connector): for wwpn in connector['wwpns']: ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!'] out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): # This WWPN is not in use continue host_lines = out.strip().split('\n') header = host_lines.pop(0).split('!') self._assert_ssh_return('remote_wwpn' in header and 'name' in header, '_find_host_from_wwpn', ssh_cmd, out, err) rmt_wwpn_idx = header.index('remote_wwpn') name_idx = header.index('name') wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines) if wwpn in wwpns: # All the wwpns will be the mapping for the same # host from this WWPN-based query. Just pick # the name from first line. hostname = host_lines[0].split('!')[name_idx] return hostname # Didn't find a host return None
{ "deleted": [ { "line_no": 3, "char_start": 87, "char_end": 153, "line": " ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn\n" } ], "added": [ { "line_no": 3, "char_start": 87, "char_end": 163, "line": " ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']\n" } ] }
{ "deleted": [ { "char_start": 133, "char_end": 135, "chars": "%s" }, { "char_start": 145, "char_end": 152, "chars": " % wwpn" } ], "added": [ { "char_start": 109, "char_end": 110, "chars": "[" }, { "char_start": 118, "char_end": 120, "chars": "'," }, { "char_start": 121, "char_end": 122, "chars": "'" }, { "char_start": 130, "char_end": 132, "chars": "'," }, { "char_start": 133, "char_end": 134, "chars": "'" }, { "char_start": 139, "char_end": 141, "chars": "'," }, { "char_start": 142, "char_end": 147, "chars": "wwpn," }, { "char_start": 148, "char_end": 149, "chars": "'" }, { "char_start": 155, "char_end": 157, "chars": "'," }, { "char_start": 158, "char_end": 159, "chars": "'" }, { "char_start": 161, "char_end": 162, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
extend_volume
def extend_volume(self, volume, new_size): LOG.debug(_('enter: extend_volume: volume %s') % volume['id']) ret = self._ensure_vdisk_no_fc_mappings(volume['name'], allow_snaps=False) if not ret: exception_message = (_('extend_volume: Extending a volume with ' 'snapshots is not supported.')) raise exception.VolumeBackendAPIException(data=exception_message) extend_amt = int(new_size) - volume['size'] ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s' % {'amt': extend_amt, 'name': volume['name']}) out, err = self._run_ssh(ssh_cmd) # No output should be returned from expandvdisksize self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume', ssh_cmd, out, err) LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])
def extend_volume(self, volume, new_size): LOG.debug(_('enter: extend_volume: volume %s') % volume['id']) ret = self._ensure_vdisk_no_fc_mappings(volume['name'], allow_snaps=False) if not ret: exception_message = (_('extend_volume: Extending a volume with ' 'snapshots is not supported.')) raise exception.VolumeBackendAPIException(data=exception_message) extend_amt = int(new_size) - volume['size'] ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt), '-unit', 'gb', volume['name']]) out, err = self._run_ssh(ssh_cmd) # No output should be returned from expandvdisksize self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume', ssh_cmd, out, err) LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])
{ "deleted": [ { "line_no": 11, "char_start": 544, "char_end": 621, "line": " ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s'\n" }, { "line_no": 12, "char_start": 621, "char_end": 687, "line": " % {'amt': extend_amt, 'name': volume['name']})\n" } ], "added": [ { "line_no": 11, "char_start": 544, "char_end": 620, "line": " ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),\n" }, { "line_no": 12, "char_start": 620, "char_end": 672, "line": " '-unit', 'gb', volume['name']])\n" } ] }
{ "deleted": [ { "char_start": 594, "char_end": 595, "chars": "%" }, { "char_start": 596, "char_end": 598, "chars": "am" }, { "char_start": 599, "char_end": 600, "chars": ")" }, { "char_start": 601, "char_end": 614, "chars": " -unit gb %(n" }, { "char_start": 616, "char_end": 617, "chars": "e" }, { "char_start": 618, "char_end": 620, "chars": "s'" }, { "char_start": 640, "char_end": 641, "chars": "%" }, { "char_start": 642, "char_end": 643, "chars": "{" }, { "char_start": 644, "char_end": 654, "chars": "amt': exte" }, { "char_start": 655, "char_end": 659, "chars": "d_am" }, { "char_start": 663, "char_end": 667, "chars": "name" }, { "char_start": 668, "char_end": 669, "chars": ":" }, { "char_start": 684, "char_end": 685, "chars": "}" } ], "added": [ { "char_start": 563, "char_end": 564, "chars": "[" }, { "char_start": 572, "char_end": 574, "chars": "'," }, { "char_start": 575, "char_end": 576, "chars": "'" }, { "char_start": 591, "char_end": 593, "chars": "'," }, { "char_start": 594, "char_end": 595, "chars": "'" }, { "char_start": 600, "char_end": 602, "chars": "'," }, { "char_start": 603, "char_end": 604, "chars": "s" }, { "char_start": 605, "char_end": 606, "chars": "r" }, { "char_start": 607, "char_end": 611, "chars": "exte" }, { "char_start": 612, "char_end": 614, "chars": "d_" }, { "char_start": 616, "char_end": 617, "chars": "t" }, { "char_start": 618, "char_end": 619, "chars": "," }, { "char_start": 641, "char_end": 645, "chars": "-uni" }, { "char_start": 650, "char_end": 652, "chars": "gb" }, { "char_start": 653, "char_end": 654, "chars": "," }, { "char_start": 669, "char_end": 670, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_get_host_from_connector
def _get_host_from_connector(self, connector): """List the hosts defined in the storage. Return the host name with the given connection info, or None if there is no host fitting that information. """ prefix = self._connector_to_hostname_prefix(connector) LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix) # Get list of host in the storage ssh_cmd = 'svcinfo lshost -delim !' out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return None # If we have FC information, we have a faster lookup option hostname = None if 'wwpns' in connector: hostname = self._find_host_from_wwpn(connector) # If we don't have a hostname yet, try the long way if not hostname: host_lines = out.strip().split('\n') self._assert_ssh_return(len(host_lines), '_get_host_from_connector', ssh_cmd, out, err) header = host_lines.pop(0).split('!') self._assert_ssh_return('name' in header, '_get_host_from_connector', ssh_cmd, out, err) name_index = header.index('name') hosts = map(lambda x: x.split('!')[name_index], host_lines) hostname = self._find_host_exhaustive(connector, hosts) LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname) return hostname
def _get_host_from_connector(self, connector): """List the hosts defined in the storage. Return the host name with the given connection info, or None if there is no host fitting that information. """ prefix = self._connector_to_hostname_prefix(connector) LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix) # Get list of host in the storage ssh_cmd = ['svcinfo', 'lshost', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return None # If we have FC information, we have a faster lookup option hostname = None if 'wwpns' in connector: hostname = self._find_host_from_wwpn(connector) # If we don't have a hostname yet, try the long way if not hostname: host_lines = out.strip().split('\n') self._assert_ssh_return(len(host_lines), '_get_host_from_connector', ssh_cmd, out, err) header = host_lines.pop(0).split('!') self._assert_ssh_return('name' in header, '_get_host_from_connector', ssh_cmd, out, err) name_index = header.index('name') hosts = map(lambda x: x.split('!')[name_index], host_lines) hostname = self._find_host_exhaustive(connector, hosts) LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname) return hostname
{ "deleted": [ { "line_no": 13, "char_start": 421, "char_end": 465, "line": " ssh_cmd = 'svcinfo lshost -delim !'\n" } ], "added": [ { "line_no": 13, "char_start": 421, "char_end": 476, "line": " ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']\n" } ] }
{ "deleted": [], "added": [ { "char_start": 439, "char_end": 440, "chars": "[" }, { "char_start": 448, "char_end": 450, "chars": "'," }, { "char_start": 451, "char_end": 452, "chars": "'" }, { "char_start": 458, "char_end": 460, "chars": "'," }, { "char_start": 461, "char_end": 462, "chars": "'" }, { "char_start": 468, "char_end": 470, "chars": "'," }, { "char_start": 471, "char_end": 472, "chars": "'" }, { "char_start": 474, "char_end": 475, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_get_hostvdisk_mappings
def _get_hostvdisk_mappings(self, host_name): """Return the defined storage mappings for a host.""" return_data = {} ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name out, err = self._run_ssh(ssh_cmd) mappings = out.strip().split('\n') if len(mappings): header = mappings.pop(0) for mapping_line in mappings: mapping_data = self._get_hdr_dic(header, mapping_line, '!') return_data[mapping_data['vdisk_name']] = mapping_data return return_data
def _get_hostvdisk_mappings(self, host_name): """Return the defined storage mappings for a host.""" return_data = {} ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name] out, err = self._run_ssh(ssh_cmd) mappings = out.strip().split('\n') if len(mappings): header = mappings.pop(0) for mapping_line in mappings: mapping_data = self._get_hdr_dic(header, mapping_line, '!') return_data[mapping_data['vdisk_name']] = mapping_data return return_data
{ "deleted": [ { "line_no": 5, "char_start": 138, "char_end": 205, "line": " ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name\n" } ], "added": [ { "line_no": 5, "char_start": 138, "char_end": 212, "line": " ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]\n" } ] }
{ "deleted": [ { "char_start": 188, "char_end": 191, "chars": " %s" }, { "char_start": 192, "char_end": 194, "chars": " %" } ], "added": [ { "char_start": 156, "char_end": 157, "chars": "[" }, { "char_start": 165, "char_end": 167, "chars": "'," }, { "char_start": 168, "char_end": 169, "chars": "'" }, { "char_start": 183, "char_end": 185, "chars": "'," }, { "char_start": 186, "char_end": 187, "chars": "'" }, { "char_start": 193, "char_end": 195, "chars": "'," }, { "char_start": 196, "char_end": 197, "chars": "'" }, { "char_start": 199, "char_end": 200, "chars": "," }, { "char_start": 210, "char_end": 211, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
main
def main(): global word print("Starting script... press 'ctrl+c' in terminal to turn off") while True: if pyperclip.paste() != word and len(pyperclip.paste().split())<5: word = pyperclip.paste() wordChc=False req = requests.get("https://api-portal.dictionary.com/dcom/pageData/%s" % word) wordChcURB = False reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word) try: data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions'] except TypeError: os.system('notify-send "Cant find |%s| on dictionary.com!"' % word) wordChc = True except KeyError: os.system('notify-send "Cant find |%s| on dictionary.com!"' % word) wordChc = True if not wordChc: definitions = [] try: for definition in data[:3]: definitions.append(cleanhtml(definition['definition'])) definitions.append("------------") os.system('notify-send "definitions from dictionary.com:[{}\n{}"'\ .format(word+"]\n------------",'\n'.join(definitions))) except KeyError: os.system('notify-send "no results in dictionary.com"') try: dataURB = json.loads(reqURB.text)['list'] except TypeError: os.system('notify-send "Cant find |%s| on urbandictionary.com!"' % word) wordChcURB = True except KeyError: os.system('notify-send "Cant find |%s| on urbandictionary.com!"' % word) wordChcURB = True if not wordChcURB: definitionsURB = [] for definition in dataURB[:3]: definitionsURB.append(definition['definition']) definitionsURB.append("------------") os.system('notify-send "definitions from urbandictionary.com:[{}\n{}"'\ .format(word+"]\n------------",'\n'.join(definitionsURB))) os.system('notify-send "Thank you for using define.py made by kelj0"')
def main(): global word print("Starting script... press 'ctrl+c' in terminal to turn off") while True: if pyperclip.paste() != word and len(pyperclip.paste().split())<5: word = pyperclip.paste() wordChc=False req = requests.get("https://api-portal.dictionary.com/dcom/pageData/%s" % word) wordChcURB = False reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word) try: data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions'] except TypeError: os.system('notify-send "Cant find that word on dictionary.com!"') wordChc = True except KeyError: os.system('notify-send "Cant find that word on dictionary.com!"') wordChc = True if not wordChc: definitions = [] try: for definition in data[:3]: definitions.append(cleanhtml(definition['definition'])) definitions.append("------------") os.system('notify-send "definitions from dictionary.com:\n{}"'.format('\n'.join(definitions))) except KeyError: os.system('notify-send "no results in dictionary.com"') try: dataURB = json.loads(reqURB.text)['list'] except TypeError: os.system('notify-send "Cant find that word on urbandictionary.com!"' % word) wordChcURB = True except KeyError: os.system('notify-send "Cant find that word on urbandictionary.com!"' % word) wordChcURB = True if not wordChcURB: definitionsURB = [] for definition in dataURB[:3]: definitionsURB.append(definition['definition']) definitionsURB.append("------------") os.system('notify-send "definitions from urbandictionary.com:\n{}"'.format('\n'.join(definitionsURB))) os.system('notify-send "Thank you for using define.py made by kelj0"')
{ "deleted": [ { "line_no": 14, "char_start": 630, "char_end": 714, "line": " os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n" }, { "line_no": 17, "char_start": 774, "char_end": 858, "line": " os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n" }, { "line_no": 26, "char_start": 1159, "char_end": 1246, "line": " os.system('notify-send \"definitions from dictionary.com:[{}\\n{}\"'\\\n" }, { "line_no": 27, "char_start": 1246, "char_end": 1322, "line": " .format(word+\"]\\n------------\",'\\n'.join(definitions)))\n" }, { "line_no": 33, "char_start": 1540, "char_end": 1629, "line": " os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n" }, { "line_no": 36, "char_start": 1692, "char_end": 1781, "line": " os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n" }, { "line_no": 44, "char_start": 2060, "char_end": 2148, "line": " os.system('notify-send \"definitions from urbandictionary.com:[{}\\n{}\"'\\\n" }, { "line_no": 45, "char_start": 2148, "char_end": 2223, "line": " .format(word+\"]\\n------------\",'\\n'.join(definitionsURB)))\n" } ], "added": [ { "line_no": 14, "char_start": 630, "char_end": 712, "line": " os.system('notify-send \"Cant find that word on dictionary.com!\"')\n" }, { "line_no": 17, "char_start": 772, "char_end": 854, "line": " os.system('notify-send \"Cant find that word on dictionary.com!\"')\n" }, { "line_no": 26, "char_start": 1155, "char_end": 1270, "line": " os.system('notify-send \"definitions from dictionary.com:\\n{}\"'.format('\\n'.join(definitions)))\n" }, { "line_no": 32, "char_start": 1488, "char_end": 1582, "line": " os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n" }, { "line_no": 35, "char_start": 1645, "char_end": 1739, "line": " os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n" }, { "line_no": 43, "char_start": 2018, "char_end": 2137, "line": " os.system('notify-send \"definitions from urbandictionary.com:\\n{}\"'.format('\\n'.join(definitionsURB)))\n" } ] }
{ "deleted": [ { "char_start": 680, "char_end": 684, "chars": "|%s|" }, { "char_start": 705, "char_end": 712, "chars": " % word" }, { "char_start": 824, "char_end": 828, "chars": "|%s|" }, { "char_start": 849, "char_end": 856, "chars": " % word" }, { "char_start": 1235, "char_end": 1238, "chars": "[{}" }, { "char_start": 1244, "char_end": 1266, "chars": "\\\n " }, { "char_start": 1274, "char_end": 1297, "chars": "word+\"]\\n------------\"," }, { "char_start": 1590, "char_end": 1594, "chars": "|%s|" }, { "char_start": 1742, "char_end": 1746, "chars": "|%s|" }, { "char_start": 2137, "char_end": 2140, "chars": "[{}" }, { "char_start": 2146, "char_end": 2164, "chars": "\\\n " }, { "char_start": 2172, "char_end": 2195, "chars": "word+\"]\\n------------\"," } ], "added": [ { "char_start": 680, "char_end": 689, "chars": "that word" }, { "char_start": 822, "char_end": 831, "chars": "that word" }, { "char_start": 1538, "char_end": 1547, "chars": "that word" }, { "char_start": 1695, "char_end": 1704, "chars": "that word" } ] }
github.com/kelj0/LearningPython/commit/2563088bf44f4d5e7f7d65f3c41f12fdaef4a1e4
SmallProjects/Define/define.py
cwe-078
_get_vvset_from_3par
def _get_vvset_from_3par(self, volume_name): """Get Virtual Volume Set from 3PAR. The only way to do this currently is to try and delete the volume to get the error message. NOTE(walter-boring): don't call this unless you know the volume is already in a vvset! """ cmd = "removevv -f %s" % volume_name LOG.debug("Issuing remove command to find vvset name %s" % cmd) out = self._cli_run(cmd, None) vvset_name = None if out and len(out) > 1: if out[1].startswith("Attempt to delete "): words = out[1].split(" ") vvset_name = words[len(words) - 1] return vvset_name
def _get_vvset_from_3par(self, volume_name): """Get Virtual Volume Set from 3PAR. The only way to do this currently is to try and delete the volume to get the error message. NOTE(walter-boring): don't call this unless you know the volume is already in a vvset! """ cmd = ['removevv', '-f', volume_name] LOG.debug("Issuing remove command to find vvset name %s" % cmd) out = self._cli_run(cmd) vvset_name = None if out and len(out) > 1: if out[1].startswith("Attempt to delete "): words = out[1].split(" ") vvset_name = words[len(words) - 1] return vvset_name
{ "deleted": [ { "line_no": 10, "char_start": 319, "char_end": 364, "line": " cmd = \"removevv -f %s\" % volume_name\n" }, { "line_no": 12, "char_start": 436, "char_end": 475, "line": " out = self._cli_run(cmd, None)\n" } ], "added": [ { "line_no": 10, "char_start": 319, "char_end": 365, "line": " cmd = ['removevv', '-f', volume_name]\n" }, { "line_no": 12, "char_start": 437, "char_end": 470, "line": " out = self._cli_run(cmd)\n" } ] }
{ "deleted": [ { "char_start": 333, "char_end": 334, "chars": "\"" }, { "char_start": 345, "char_end": 351, "chars": " %s\" %" }, { "char_start": 467, "char_end": 473, "chars": ", None" } ], "added": [ { "char_start": 333, "char_end": 335, "chars": "['" }, { "char_start": 343, "char_end": 345, "chars": "'," }, { "char_start": 346, "char_end": 347, "chars": "'" }, { "char_start": 349, "char_end": 351, "chars": "'," }, { "char_start": 363, "char_end": 364, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
_get_flashcopy_mapping_attributes
def _get_flashcopy_mapping_attributes(self, fc_map_id): LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s') % fc_map_id) fc_ls_map_cmd = 'svcinfo lsfcmap -filtervalue id=%s -delim !' % \ fc_map_id out, err = self._run_ssh(fc_ls_map_cmd) if not len(out.strip()): return None # Get list of FlashCopy mappings # We expect zero or one line if mapping does not exist, # two lines if it does exist, otherwise error lines = out.strip().split('\n') self._assert_ssh_return(len(lines) <= 2, '_get_flashcopy_mapping_attributes', fc_ls_map_cmd, out, err) if len(lines) == 2: attributes = self._get_hdr_dic(lines[0], lines[1], '!') else: # 0 or 1 lines attributes = None LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping ' '%(fc_map_id)s, attributes %(attributes)s') % {'fc_map_id': fc_map_id, 'attributes': attributes}) return attributes
def _get_flashcopy_mapping_attributes(self, fc_map_id): LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s') % fc_map_id) fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-filtervalue', 'id=%s' % fc_map_id, '-delim', '!'] out, err = self._run_ssh(fc_ls_map_cmd) if not len(out.strip()): return None # Get list of FlashCopy mappings # We expect zero or one line if mapping does not exist, # two lines if it does exist, otherwise error lines = out.strip().split('\n') self._assert_ssh_return(len(lines) <= 2, '_get_flashcopy_mapping_attributes', fc_ls_map_cmd, out, err) if len(lines) == 2: attributes = self._get_hdr_dic(lines[0], lines[1], '!') else: # 0 or 1 lines attributes = None LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping ' '%(fc_map_id)s, attributes %(attributes)s') % {'fc_map_id': fc_map_id, 'attributes': attributes}) return attributes
{ "deleted": [ { "line_no": 5, "char_start": 168, "char_end": 242, "line": " fc_ls_map_cmd = 'svcinfo lsfcmap -filtervalue id=%s -delim !' % \\\n" }, { "line_no": 6, "char_start": 242, "char_end": 264, "line": " fc_map_id\n" } ], "added": [ { "line_no": 5, "char_start": 168, "char_end": 231, "line": " fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-filtervalue',\n" }, { "line_no": 6, "char_start": 231, "char_end": 292, "line": " 'id=%s' % fc_map_id, '-delim', '!']\n" } ] }
{ "deleted": [ { "char_start": 222, "char_end": 227, "chars": "id=%s" }, { "char_start": 228, "char_end": 234, "chars": "-delim" }, { "char_start": 235, "char_end": 237, "chars": "!'" }, { "char_start": 238, "char_end": 239, "chars": "%" }, { "char_start": 240, "char_end": 242, "chars": "\\\n" } ], "added": [ { "char_start": 192, "char_end": 193, "chars": "[" }, { "char_start": 201, "char_end": 203, "chars": "'," }, { "char_start": 204, "char_end": 205, "chars": "'" }, { "char_start": 212, "char_end": 214, "chars": "'," }, { "char_start": 215, "char_end": 216, "chars": "'" }, { "char_start": 228, "char_end": 236, "chars": "',\n " }, { "char_start": 238, "char_end": 243, "chars": " " }, { "char_start": 254, "char_end": 265, "chars": " 'id=%s' %" }, { "char_start": 275, "char_end": 291, "chars": ", '-delim', '!']" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_add_volume_to_volume_set
def _add_volume_to_volume_set(self, volume, volume_name, cpg, vvs_name, qos): if vvs_name is not None: # Admin has set a volume set name to add the volume to self._cli_run('createvvset -add %s %s' % (vvs_name, volume_name), None) else: vvs_name = self._get_3par_vvs_name(volume['id']) domain = self.get_domain(cpg) self._cli_run('createvvset -domain %s %s' % (domain, vvs_name), None) self._set_qos_rule(qos, vvs_name) self._cli_run('createvvset -add %s %s' % (vvs_name, volume_name), None)
def _add_volume_to_volume_set(self, volume, volume_name, cpg, vvs_name, qos): if vvs_name is not None: # Admin has set a volume set name to add the volume to self._cli_run(['createvvset', '-add', vvs_name, volume_name]) else: vvs_name = self._get_3par_vvs_name(volume['id']) domain = self.get_domain(cpg) self._cli_run(['createvvset', '-domain', domain, vvs_name]) self._set_qos_rule(qos, vvs_name) self._cli_run(['createvvset', '-add', vvs_name, volume_name])
{ "deleted": [ { "line_no": 5, "char_start": 216, "char_end": 280, "line": " self._cli_run('createvvset -add %s %s' % (vvs_name,\n" }, { "line_no": 6, "char_start": 280, "char_end": 354, "line": " volume_name), None)\n" }, { "line_no": 10, "char_start": 471, "char_end": 536, "line": " self._cli_run('createvvset -domain %s %s' % (domain,\n" }, { "line_no": 11, "char_start": 536, "char_end": 610, "line": " vvs_name), None)\n" }, { "line_no": 13, "char_start": 656, "char_end": 720, "line": " self._cli_run('createvvset -add %s %s' % (vvs_name,\n" }, { "line_no": 14, "char_start": 720, "char_end": 793, "line": " volume_name), None)\n" } ], "added": [ { "line_no": 5, "char_start": 216, "char_end": 290, "line": " self._cli_run(['createvvset', '-add', vvs_name, volume_name])\n" }, { "line_no": 9, "char_start": 407, "char_end": 479, "line": " self._cli_run(['createvvset', '-domain', domain, vvs_name])\n" }, { "line_no": 11, "char_start": 525, "char_end": 598, "line": " self._cli_run(['createvvset', '-add', vvs_name, volume_name])\n" } ] }
{ "deleted": [ { "char_start": 259, "char_end": 265, "chars": " %s %s" }, { "char_start": 266, "char_end": 268, "chars": " %" }, { "char_start": 269, "char_end": 270, "chars": "(" }, { "char_start": 279, "char_end": 333, "chars": "\n " }, { "char_start": 345, "char_end": 352, "chars": "), None" }, { "char_start": 517, "char_end": 523, "chars": " %s %s" }, { "char_start": 524, "char_end": 526, "chars": " %" }, { "char_start": 527, "char_end": 528, "chars": "(" }, { "char_start": 535, "char_end": 592, "chars": "\n " }, { "char_start": 601, "char_end": 608, "chars": "), None" }, { "char_start": 699, "char_end": 705, "chars": " %s %s" }, { "char_start": 706, "char_end": 708, "chars": " %" }, { "char_start": 709, "char_end": 710, "chars": "(" }, { "char_start": 719, "char_end": 773, "chars": "\n " }, { "char_start": 785, "char_end": 792, "chars": "), None" } ], "added": [ { "char_start": 242, "char_end": 243, "chars": "[" }, { "char_start": 255, "char_end": 257, "chars": "'," }, { "char_start": 258, "char_end": 259, "chars": "'" }, { "char_start": 264, "char_end": 265, "chars": "," }, { "char_start": 287, "char_end": 288, "chars": "]" }, { "char_start": 433, "char_end": 434, "chars": "[" }, { "char_start": 446, "char_end": 448, "chars": "'," }, { "char_start": 449, "char_end": 450, "chars": "'" }, { "char_start": 458, "char_end": 459, "chars": "," }, { "char_start": 476, "char_end": 477, "chars": "]" }, { "char_start": 551, "char_end": 552, "chars": "[" }, { "char_start": 564, "char_end": 566, "chars": "'," }, { "char_start": 567, "char_end": 568, "chars": "'" }, { "char_start": 573, "char_end": 574, "chars": "," }, { "char_start": 596, "char_end": 597, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
test_initialize_connection
def test_initialize_connection(self): self.driver._eql_execute = self.mox.\ CreateMock(self.driver._eql_execute) volume = {'name': self.volume_name} self.stubs.Set(self.driver, "_get_iscsi_properties", self._fake_get_iscsi_properties) self.driver._eql_execute('volume', 'select', volume['name'], 'access', 'create', 'initiator', self.connector['initiator'], 'authmethod chap', 'username', self.configuration.eqlx_chap_login) self.mox.ReplayAll() iscsi_properties = self.driver.initialize_connection(volume, self.connector) self.assertEqual(iscsi_properties['data'], self._fake_get_iscsi_properties(volume))
def test_initialize_connection(self): self.driver._eql_execute = self.mox.\ CreateMock(self.driver._eql_execute) volume = {'name': self.volume_name} self.stubs.Set(self.driver, "_get_iscsi_properties", self._fake_get_iscsi_properties) self.driver._eql_execute('volume', 'select', volume['name'], 'access', 'create', 'initiator', self.connector['initiator'], 'authmethod', 'chap', 'username', self.configuration.eqlx_chap_login) self.mox.ReplayAll() iscsi_properties = self.driver.initialize_connection(volume, self.connector) self.assertEqual(iscsi_properties['data'], self._fake_get_iscsi_properties(volume))
{ "deleted": [ { "line_no": 10, "char_start": 495, "char_end": 547, "line": " 'authmethod chap',\n" } ], "added": [ { "line_no": 10, "char_start": 495, "char_end": 550, "line": " 'authmethod', 'chap',\n" } ] }
{ "deleted": [], "added": [ { "char_start": 539, "char_end": 541, "chars": "'," }, { "char_start": 542, "char_end": 543, "chars": "'" } ] }
github.com/thatsdone/cinder/commit/9e858bebb89de05b1c9ecc27f5bd9fbff95a728e
cinder/tests/test_eqlx.py
cwe-078
test_create_invalid_host
def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -persona 1 -domain (\'OpenStack\',) ' 'fakehost 123456789012345 123456789054321') create_host_ret = pack(CLI_CR + 'already used by host fakehost.foo (19)') _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, '']) show_3par_cmd = 'showhost -verbose fakehost.foo' _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')
def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', '123456789012345', '123456789054321']) create_host_ret = pack(CLI_CR + 'already used by host fakehost.foo (19)') _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, '']) show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo'] _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')
{ "deleted": [ { "line_no": 13, "char_start": 505, "char_end": 558, "line": " show_host_cmd = 'showhost -verbose fakehost'\n" }, { "line_no": 16, "char_start": 639, "char_end": 716, "line": " create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n" }, { "line_no": 17, "char_start": 716, "char_end": 787, "line": " 'fakehost 123456789012345 123456789054321')\n" }, { "line_no": 22, "char_start": 975, "char_end": 1032, "line": " show_3par_cmd = 'showhost -verbose fakehost.foo'\n" } ], "added": [ { "line_no": 13, "char_start": 505, "char_end": 566, "line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n" }, { "line_no": 16, "char_start": 647, "char_end": 717, "line": " create_host_cmd = (['createhost', '-persona', '1', '-domain',\n" }, { "line_no": 17, "char_start": 717, "char_end": 792, "line": " ('OpenStack',), 'fakehost', '123456789012345',\n" }, { "line_no": 18, "char_start": 792, "char_end": 840, "line": " '123456789054321'])\n" }, { "line_no": 23, "char_start": 1028, "char_end": 1093, "line": " show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n" } ] }
{ "deleted": [ { "char_start": 696, "char_end": 710, "chars": " (\\'OpenStack\\" }, { "char_start": 712, "char_end": 715, "chars": ") '" } ], "added": [ { "char_start": 529, "char_end": 530, "chars": "[" }, { "char_start": 539, "char_end": 541, "chars": "'," }, { "char_start": 542, "char_end": 543, "chars": "'" }, { "char_start": 551, "char_end": 553, "chars": "'," }, { "char_start": 554, "char_end": 555, "chars": "'" }, { "char_start": 564, "char_end": 565, "chars": "]" }, { "char_start": 674, "char_end": 675, "chars": "[" }, { "char_start": 686, "char_end": 688, "chars": "'," }, { "char_start": 689, "char_end": 690, "chars": "'" }, { "char_start": 698, "char_end": 700, "chars": "'," }, { "char_start": 701, "char_end": 702, "chars": "'" }, { "char_start": 703, "char_end": 705, "chars": "'," }, { "char_start": 706, "char_end": 707, "chars": "'" }, { "char_start": 744, "char_end": 761, "chars": " ('OpenStack',), " }, { "char_start": 770, "char_end": 772, "chars": "'," }, { "char_start": 773, "char_end": 774, "chars": "'" }, { "char_start": 789, "char_end": 802, "chars": "',\n " }, { "char_start": 803, "char_end": 821, "chars": " '" }, { "char_start": 837, "char_end": 838, "chars": "]" }, { "char_start": 1052, "char_end": 1053, "chars": "[" }, { "char_start": 1062, "char_end": 1064, "chars": "'," }, { "char_start": 1065, "char_end": 1066, "chars": "'" }, { "char_start": 1074, "char_end": 1076, "chars": "'," }, { "char_start": 1077, "char_end": 1078, "chars": "'" }, { "char_start": 1091, "char_end": 1092, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/tests/test_hp3par.py
cwe-078
get_logs
@app.route('/api/uploads/<sid>/logs') def get_logs(sid): if '/' not in sid: path = os.path.join(app.config['UPLOAD_FOLDER'], sid) if os.path.isfile(os.path.join(path, app.config['LOG_FILE'])): return send_from_directory(directory=path, filename=app.config['LOG_FILE']) else: abort(404) else: abort(403)
@app.route('/api/uploads/<sid>/logs') def get_logs(sid): if utils.sid_is_valid(sid): path = join(app.config['UPLOAD_FOLDER'], sid) if os.path.isfile(join(path, app.config['LOG_FILE'])): return send_from_directory(directory=path, filename=app.config['LOG_FILE']) else: abort(404) else: abort(404)
{ "deleted": [ { "line_no": 3, "char_start": 57, "char_end": 80, "line": " if '/' not in sid:\n" }, { "line_no": 4, "char_start": 80, "char_end": 142, "line": " path = os.path.join(app.config['UPLOAD_FOLDER'], sid)\n" }, { "line_no": 5, "char_start": 142, "char_end": 213, "line": " if os.path.isfile(os.path.join(path, app.config['LOG_FILE'])):\n" }, { "line_no": 11, "char_start": 388, "char_end": 406, "line": " abort(403)\n" } ], "added": [ { "line_no": 3, "char_start": 57, "char_end": 89, "line": " if utils.sid_is_valid(sid):\n" }, { "line_no": 4, "char_start": 89, "char_end": 143, "line": " path = join(app.config['UPLOAD_FOLDER'], sid)\n" }, { "line_no": 5, "char_start": 143, "char_end": 144, "line": "\n" }, { "line_no": 6, "char_start": 144, "char_end": 207, "line": " if os.path.isfile(join(path, app.config['LOG_FILE'])):\n" }, { "line_no": 12, "char_start": 382, "char_end": 400, "line": " abort(404)\n" } ] }
{ "deleted": [ { "char_start": 64, "char_end": 70, "chars": "'/' no" }, { "char_start": 71, "char_end": 72, "chars": " " }, { "char_start": 73, "char_end": 75, "chars": "n " }, { "char_start": 95, "char_end": 103, "chars": "os.path." }, { "char_start": 168, "char_end": 176, "chars": "os.path." }, { "char_start": 404, "char_end": 405, "chars": "3" } ], "added": [ { "char_start": 64, "char_end": 65, "chars": "u" }, { "char_start": 66, "char_end": 80, "chars": "ils.sid_is_val" }, { "char_start": 81, "char_end": 83, "chars": "d(" }, { "char_start": 86, "char_end": 87, "chars": ")" }, { "char_start": 143, "char_end": 144, "chars": "\n" }, { "char_start": 398, "char_end": 399, "chars": "4" } ] }
github.com/cheukyin699/genset-demo-site/commit/abb55b1a6786b0a995c2cdf77a7977a1d51cfc0d
app/views.py
cwe-078
_make_fc_map
def _make_fc_map(self, source, target, full_copy): copyflag = '' if full_copy else '-copyrate 0' fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s ' '-autodelete %(copyflag)s' % {'src': source, 'tgt': target, 'copyflag': copyflag}) out, err = self._run_ssh(fc_map_cli_cmd) self._driver_assert( len(out.strip()), _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) # Ensure that the output is as expected match_obj = re.search('FlashCopy Mapping, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a "successfully created" message with vdisk id self._driver_assert( match_obj is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) try: fc_map_id = match_obj.group(1) self._driver_assert( fc_map_id is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) except IndexError: self._driver_assert( False, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) return fc_map_id
def _make_fc_map(self, source, target, full_copy): fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target', target, '-autodelete'] if not full_copy: fc_map_cli_cmd.extend(['-copyrate', '0']) out, err = self._run_ssh(fc_map_cli_cmd) self._driver_assert( len(out.strip()), _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) # Ensure that the output is as expected match_obj = re.search('FlashCopy Mapping, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a "successfully created" message with vdisk id self._driver_assert( match_obj is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) try: fc_map_id = match_obj.group(1) self._driver_assert( fc_map_id is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) except IndexError: self._driver_assert( False, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) return fc_map_id
{ "deleted": [ { "line_no": 2, "char_start": 55, "char_end": 109, "line": " copyflag = '' if full_copy else '-copyrate 0'\n" }, { "line_no": 3, "char_start": 109, "char_end": 186, "line": " fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s '\n" }, { "line_no": 4, "char_start": 186, "char_end": 241, "line": " '-autodelete %(copyflag)s' %\n" }, { "line_no": 5, "char_start": 241, "char_end": 283, "line": " {'src': source,\n" }, { "line_no": 6, "char_start": 283, "char_end": 325, "line": " 'tgt': target,\n" }, { "line_no": 7, "char_start": 325, "char_end": 375, "line": " 'copyflag': copyflag})\n" } ], "added": [ { "line_no": 2, "char_start": 55, "char_end": 133, "line": " fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target',\n" }, { "line_no": 3, "char_start": 133, "char_end": 182, "line": " target, '-autodelete']\n" }, { "line_no": 4, "char_start": 182, "char_end": 208, "line": " if not full_copy:\n" }, { "line_no": 5, "char_start": 208, "char_end": 262, "line": " fc_map_cli_cmd.extend(['-copyrate', '0'])\n" } ] }
{ "deleted": [ { "char_start": 63, "char_end": 117, "chars": "copyflag = '' if full_copy else '-copyrate 0'\n " }, { "char_start": 134, "char_end": 135, "chars": "(" }, { "char_start": 160, "char_end": 162, "chars": "%(" }, { "char_start": 165, "char_end": 167, "chars": ")s" }, { "char_start": 175, "char_end": 184, "chars": " %(tgt)s " }, { "char_start": 224, "char_end": 237, "chars": " %(copyflag)s" }, { "char_start": 238, "char_end": 240, "chars": " %" }, { "char_start": 241, "char_end": 242, "chars": " " }, { "char_start": 252, "char_end": 271, "chars": " {'sr" }, { "char_start": 272, "char_end": 273, "chars": "'" }, { "char_start": 274, "char_end": 282, "chars": " source," }, { "char_start": 295, "char_end": 318, "chars": " 'tgt': t" }, { "char_start": 319, "char_end": 321, "chars": "rg" }, { "char_start": 323, "char_end": 352, "chars": ",\n " }, { "char_start": 357, "char_end": 359, "chars": "fl" }, { "char_start": 360, "char_end": 361, "chars": "g" }, { "char_start": 362, "char_end": 363, "chars": ":" }, { "char_start": 364, "char_end": 373, "chars": "copyflag}" } ], "added": [ { "char_start": 80, "char_end": 81, "chars": "[" }, { "char_start": 89, "char_end": 91, "chars": "'," }, { "char_start": 92, "char_end": 93, "chars": "'" }, { "char_start": 100, "char_end": 102, "chars": "'," }, { "char_start": 103, "char_end": 104, "chars": "'" }, { "char_start": 111, "char_end": 113, "chars": "'," }, { "char_start": 115, "char_end": 117, "chars": "ou" }, { "char_start": 119, "char_end": 121, "chars": "e," }, { "char_start": 122, "char_end": 123, "chars": "'" }, { "char_start": 131, "char_end": 132, "chars": "," }, { "char_start": 159, "char_end": 167, "chars": "target, " }, { "char_start": 180, "char_end": 181, "chars": "]" }, { "char_start": 190, "char_end": 192, "chars": "if" }, { "char_start": 193, "char_end": 196, "chars": "not" }, { "char_start": 197, "char_end": 198, "chars": "f" }, { "char_start": 199, "char_end": 202, "chars": "ll_" }, { "char_start": 203, "char_end": 207, "chars": "opy:" }, { "char_start": 220, "char_end": 224, "chars": "fc_m" }, { "char_start": 225, "char_end": 235, "chars": "p_cli_cmd." }, { "char_start": 236, "char_end": 237, "chars": "x" }, { "char_start": 238, "char_end": 243, "chars": "end([" }, { "char_start": 244, "char_end": 245, "chars": "-" }, { "char_start": 249, "char_end": 250, "chars": "r" }, { "char_start": 251, "char_end": 253, "chars": "te" }, { "char_start": 254, "char_end": 255, "chars": "," }, { "char_start": 256, "char_end": 260, "chars": "'0']" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
test_get_iscsi_ip
def test_get_iscsi_ip(self): self.flags(lock_path=self.tempdir) #record driver set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_port_cmd = 'showport' _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = 'showport -iscsi' _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = 'showport -iscsiname' _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) #record show_vlun_cmd = 'showvlun -a -host fakehost' show_vlun_ret = 'no vluns listed\r\n' _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), '']) show_vlun_cmd = 'showvlun -a -showcols Port' _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() config = self.setup_configuration() config.iscsi_ip_address = '10.10.10.10' config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.252')
def test_get_iscsi_ip(self): self.flags(lock_path=self.tempdir) #record driver set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_port_cmd = ['showport'] _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsi'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsiname'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) #record show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost'] show_vlun_ret = 'no vluns listed\r\n' _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), '']) show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port'] _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() config = self.setup_configuration() config.iscsi_ip_address = '10.10.10.10' config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.252')
{ "deleted": [ { "line_no": 9, "char_start": 290, "char_end": 325, "line": " show_port_cmd = 'showport'\n" }, { "line_no": 12, "char_start": 397, "char_end": 441, "line": " show_port_i_cmd = 'showport -iscsi'\n" }, { "line_no": 16, "char_start": 579, "char_end": 627, "line": " show_port_i_cmd = 'showport -iscsiname'\n" }, { "line_no": 20, "char_start": 724, "char_end": 777, "line": " show_vlun_cmd = 'showvlun -a -host fakehost'\n" }, { "line_no": 23, "char_start": 899, "char_end": 952, "line": " show_vlun_cmd = 'showvlun -a -showcols Port'\n" } ], "added": [ { "line_no": 9, "char_start": 290, "char_end": 327, "line": " show_port_cmd = ['showport']\n" }, { "line_no": 12, "char_start": 399, "char_end": 448, "line": " show_port_i_cmd = ['showport', '-iscsi']\n" }, { "line_no": 16, "char_start": 586, "char_end": 639, "line": " show_port_i_cmd = ['showport', '-iscsiname']\n" }, { "line_no": 20, "char_start": 736, "char_end": 800, "line": " show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n" }, { "line_no": 23, "char_start": 922, "char_end": 986, "line": " show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n" } ] }
{ "deleted": [], "added": [ { "char_start": 314, "char_end": 315, "chars": "[" }, { "char_start": 325, "char_end": 326, "chars": "]" }, { "char_start": 425, "char_end": 426, "chars": "[" }, { "char_start": 435, "char_end": 437, "chars": "'," }, { "char_start": 438, "char_end": 439, "chars": "'" }, { "char_start": 446, "char_end": 447, "chars": "]" }, { "char_start": 612, "char_end": 613, "chars": "[" }, { "char_start": 622, "char_end": 624, "chars": "'," }, { "char_start": 625, "char_end": 626, "chars": "'" }, { "char_start": 637, "char_end": 638, "chars": "]" }, { "char_start": 760, "char_end": 761, "chars": "[" }, { "char_start": 770, "char_end": 772, "chars": "'," }, { "char_start": 773, "char_end": 774, "chars": "'" }, { "char_start": 776, "char_end": 778, "chars": "'," }, { "char_start": 779, "char_end": 780, "chars": "'" }, { "char_start": 785, "char_end": 787, "chars": "'," }, { "char_start": 788, "char_end": 789, "chars": "'" }, { "char_start": 798, "char_end": 799, "chars": "]" }, { "char_start": 946, "char_end": 947, "chars": "[" }, { "char_start": 956, "char_end": 958, "chars": "'," }, { "char_start": 959, "char_end": 960, "chars": "'" }, { "char_start": 962, "char_end": 964, "chars": "'," }, { "char_start": 965, "char_end": 966, "chars": "'" }, { "char_start": 975, "char_end": 977, "chars": "'," }, { "char_start": 978, "char_end": 979, "chars": "'" }, { "char_start": 984, "char_end": 985, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/tests/test_hp3par.py
cwe-078
usage
def usage(args=None): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD': cmd = 'df -kP' else: cmd = 'df' if args: cmd = cmd + ' -' + args ret = {} out = __salt__['cmd.run'](cmd).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.warn("Problem parsing disk usage information") ret = {} return ret
def usage(args=None): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = '' allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: break if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD': cmd = 'df -kP' else: cmd = 'df' if args: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.warn("Problem parsing disk usage information") ret = {} return ret
{ "deleted": [ { "line_no": 18, "char_start": 346, "char_end": 378, "line": " cmd = cmd + ' -' + args\n" } ], "added": [ { "line_no": 11, "char_start": 175, "char_end": 190, "line": " flags = ''\n" }, { "line_no": 12, "char_start": 190, "char_end": 265, "line": " allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n" }, { "line_no": 13, "char_start": 265, "char_end": 287, "line": " for flag in args:\n" }, { "line_no": 14, "char_start": 287, "char_end": 315, "line": " if flag in allowed:\n" }, { "line_no": 15, "char_start": 315, "char_end": 341, "line": " flags += flag\n" }, { "line_no": 16, "char_start": 341, "char_end": 355, "line": " else:\n" }, { "line_no": 17, "char_start": 355, "char_end": 373, "line": " break\n" }, { "line_no": 25, "char_start": 544, "char_end": 581, "line": " cmd += ' -{0}'.format(flags)\n" } ] }
{ "deleted": [ { "char_start": 215, "char_end": 215, "chars": "" }, { "char_start": 359, "char_end": 365, "chars": " cmd +" }, { "char_start": 370, "char_end": 373, "chars": " + " }, { "char_start": 374, "char_end": 375, "chars": "r" } ], "added": [ { "char_start": 179, "char_end": 377, "chars": "flags = ''\n allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n for flag in args:\n if flag in allowed:\n flags += flag\n else:\n break\n " }, { "char_start": 557, "char_end": 558, "chars": "=" }, { "char_start": 562, "char_end": 565, "chars": "{0}" }, { "char_start": 566, "char_end": 571, "chars": ".form" }, { "char_start": 572, "char_end": 577, "chars": "t(fla" }, { "char_start": 579, "char_end": 580, "chars": ")" } ] }
github.com/saltstack/salt/commit/ebdef37b7e5d2b95a01d34b211c61c61da67e46a
salt/modules/disk.py
cwe-078
_get_fc_wwpns
def _get_fc_wwpns(self): for key in self._storage_nodes: node = self._storage_nodes[key] ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id'] raw = self._run_ssh(ssh_cmd) resp = CLIResponse(raw, delim='!', with_header=False) wwpns = set(node['WWPN']) for i, s in resp.select('port_id', 'port_status'): if 'unconfigured' != s: wwpns.add(i) node['WWPN'] = list(wwpns) LOG.info(_('WWPN on node %(node)s: %(wwpn)s') % {'node': node['id'], 'wwpn': node['WWPN']})
def _get_fc_wwpns(self): for key in self._storage_nodes: node = self._storage_nodes[key] ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']] raw = self._run_ssh(ssh_cmd) resp = CLIResponse(raw, delim='!', with_header=False) wwpns = set(node['WWPN']) for i, s in resp.select('port_id', 'port_status'): if 'unconfigured' != s: wwpns.add(i) node['WWPN'] = list(wwpns) LOG.info(_('WWPN on node %(node)s: %(wwpn)s') % {'node': node['id'], 'wwpn': node['WWPN']})
{ "deleted": [ { "line_no": 4, "char_start": 113, "char_end": 177, "line": " ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id']\n" } ], "added": [ { "line_no": 4, "char_start": 113, "char_end": 184, "line": " ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']]\n" } ] }
{ "deleted": [ { "char_start": 159, "char_end": 162, "chars": " %s" }, { "char_start": 163, "char_end": 165, "chars": " %" } ], "added": [ { "char_start": 135, "char_end": 136, "chars": "[" }, { "char_start": 144, "char_end": 146, "chars": "'," }, { "char_start": 147, "char_end": 148, "chars": "'" }, { "char_start": 154, "char_end": 156, "chars": "'," }, { "char_start": 157, "char_end": 158, "chars": "'" }, { "char_start": 164, "char_end": 166, "chars": "'," }, { "char_start": 167, "char_end": 168, "chars": "'" }, { "char_start": 170, "char_end": 171, "chars": "," }, { "char_start": 181, "char_end": 182, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
ls
def ls(self, data, path): credentials = self._formatCredentials(data, name='current') command = ( '{credentials} ' 'rclone lsjson current:{path}' ).format( credentials=credentials, path=path, ) try: result = self._execute(command) result = json.loads(result) return result except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))
def ls(self, data, path): credentials = self._formatCredentials(data, name='current') command = [ 'rclone', 'lsjson', 'current:{}'.format(path), ] try: result = self._execute(command, credentials) result = json.loads(result) return result except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))
{ "deleted": [ { "line_no": 3, "char_start": 98, "char_end": 99, "line": "\n" }, { "line_no": 4, "char_start": 99, "char_end": 119, "line": " command = (\n" }, { "line_no": 5, "char_start": 119, "char_end": 148, "line": " '{credentials} '\n" }, { "line_no": 6, "char_start": 148, "char_end": 191, "line": " 'rclone lsjson current:{path}'\n" }, { "line_no": 7, "char_start": 191, "char_end": 209, "line": " ).format(\n" }, { "line_no": 8, "char_start": 209, "char_end": 246, "line": " credentials=credentials,\n" }, { "line_no": 9, "char_start": 246, "char_end": 269, "line": " path=path,\n" }, { "line_no": 10, "char_start": 269, "char_end": 279, "line": " )\n" }, { "line_no": 13, "char_start": 293, "char_end": 337, "line": " result = self._execute(command)\n" } ], "added": [ { "line_no": 3, "char_start": 98, "char_end": 118, "line": " command = [\n" }, { "line_no": 4, "char_start": 118, "char_end": 140, "line": " 'rclone',\n" }, { "line_no": 5, "char_start": 140, "char_end": 162, "line": " 'lsjson',\n" }, { "line_no": 6, "char_start": 162, "char_end": 201, "line": " 'current:{}'.format(path),\n" }, { "line_no": 7, "char_start": 201, "char_end": 211, "line": " ]\n" }, { "line_no": 10, "char_start": 225, "char_end": 282, "line": " result = self._execute(command, credentials)\n" } ] }
{ "deleted": [ { "char_start": 98, "char_end": 99, "chars": "\n" }, { "char_start": 117, "char_end": 118, "chars": "(" }, { "char_start": 132, "char_end": 134, "chars": "{c" }, { "char_start": 135, "char_end": 142, "chars": "edentia" }, { "char_start": 143, "char_end": 146, "chars": "s} " }, { "char_start": 161, "char_end": 168, "chars": "rclone " }, { "char_start": 174, "char_end": 189, "chars": " current:{path}" }, { "char_start": 199, "char_end": 210, "chars": ").format(\n " }, { "char_start": 214, "char_end": 221, "chars": " " }, { "char_start": 223, "char_end": 234, "chars": "edentials=c" }, { "char_start": 236, "char_end": 238, "chars": "de" }, { "char_start": 240, "char_end": 259, "chars": "ials,\n p" }, { "char_start": 261, "char_end": 263, "chars": "h=" }, { "char_start": 277, "char_end": 278, "chars": ")" } ], "added": [ { "char_start": 116, "char_end": 117, "chars": "[" }, { "char_start": 131, "char_end": 132, "chars": "r" }, { "char_start": 134, "char_end": 137, "chars": "one" }, { "char_start": 138, "char_end": 139, "chars": "," }, { "char_start": 160, "char_end": 161, "chars": "," }, { "char_start": 174, "char_end": 175, "chars": "'" }, { "char_start": 176, "char_end": 178, "chars": "ur" }, { "char_start": 182, "char_end": 189, "chars": ":{}'.fo" }, { "char_start": 190, "char_end": 191, "chars": "m" }, { "char_start": 193, "char_end": 194, "chars": "(" }, { "char_start": 198, "char_end": 199, "chars": ")" }, { "char_start": 209, "char_end": 210, "chars": "]" }, { "char_start": 267, "char_end": 280, "chars": ", credentials" } ] }
github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db
src/backend/api/utils/rclone_connection.py
cwe-078
_run_ssh
def _run_ssh(self, command, check_exit=True, attempts=1): if not self.sshpool: self.sshpool = utils.SSHPool(self.config.san_ip, self.config.san_ssh_port, self.config.ssh_conn_timeout, self.config.san_login, password=self.config.san_password, privatekey= self.config.san_private_key, min_size= self.config.ssh_min_pool_conn, max_size= self.config.ssh_max_pool_conn) try: total_attempts = attempts with self.sshpool.item() as ssh: while attempts > 0: attempts -= 1 try: return self._ssh_execute(ssh, command, check_exit_code=check_exit) except Exception as e: LOG.error(e) greenthread.sleep(randint(20, 500) / 100.0) msg = (_("SSH Command failed after '%(total_attempts)r' " "attempts : '%(command)s'") % {'total_attempts': total_attempts, 'command': command}) raise paramiko.SSHException(msg) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error running ssh command: %s") % command)
def _run_ssh(self, cmd_list, check_exit=True, attempts=1): utils.check_ssh_injection(cmd_list) command = ' '. join(cmd_list) if not self.sshpool: self.sshpool = utils.SSHPool(self.config.san_ip, self.config.san_ssh_port, self.config.ssh_conn_timeout, self.config.san_login, password=self.config.san_password, privatekey= self.config.san_private_key, min_size= self.config.ssh_min_pool_conn, max_size= self.config.ssh_max_pool_conn) try: total_attempts = attempts with self.sshpool.item() as ssh: while attempts > 0: attempts -= 1 try: return self._ssh_execute(ssh, command, check_exit_code=check_exit) except Exception as e: LOG.error(e) greenthread.sleep(randint(20, 500) / 100.0) msg = (_("SSH Command failed after '%(total_attempts)r' " "attempts : '%(command)s'") % {'total_attempts': total_attempts, 'command': command}) raise paramiko.SSHException(msg) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error running ssh command: %s") % command)
{ "deleted": [ { "line_no": 1, "char_start": 0, "char_end": 62, "line": " def _run_ssh(self, command, check_exit=True, attempts=1):\n" } ], "added": [ { "line_no": 1, "char_start": 0, "char_end": 63, "line": " def _run_ssh(self, cmd_list, check_exit=True, attempts=1):\n" }, { "line_no": 2, "char_start": 63, "char_end": 107, "line": " utils.check_ssh_injection(cmd_list)\n" }, { "line_no": 3, "char_start": 107, "char_end": 145, "line": " command = ' '. join(cmd_list)\n" }, { "line_no": 4, "char_start": 145, "char_end": 146, "line": "\n" } ] }
{ "deleted": [ { "char_start": 24, "char_end": 25, "chars": "o" }, { "char_start": 26, "char_end": 29, "chars": "man" } ], "added": [ { "char_start": 26, "char_end": 31, "chars": "_list" }, { "char_start": 62, "char_end": 145, "chars": "\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
verify
def verify(self, data): credentials = self._formatCredentials(data, name='current') command = '{} rclone lsjson current:'.format(credentials) try: result = self._execute(command) return { 'result': True, 'message': 'Success', } except subprocess.CalledProcessError as e: returncode = e.returncode return { 'result': False, 'message': 'Exit status {}'.format(returncode), }
def verify(self, data): credentials = self._formatCredentials(data, name='current') command = [ 'rclone', 'lsjson', 'current:', ] try: result = self._execute(command, credentials) return { 'result': True, 'message': 'Success', } except subprocess.CalledProcessError as e: returncode = e.returncode return { 'result': False, 'message': 'Exit status {}'.format(returncode), }
{ "deleted": [ { "line_no": 3, "char_start": 96, "char_end": 162, "line": " command = '{} rclone lsjson current:'.format(credentials)\n" }, { "line_no": 6, "char_start": 176, "char_end": 220, "line": " result = self._execute(command)\n" } ], "added": [ { "line_no": 3, "char_start": 96, "char_end": 116, "line": " command = [\n" }, { "line_no": 4, "char_start": 116, "char_end": 138, "line": " 'rclone',\n" }, { "line_no": 5, "char_start": 138, "char_end": 160, "line": " 'lsjson',\n" }, { "line_no": 6, "char_start": 160, "char_end": 184, "line": " 'current:',\n" }, { "line_no": 7, "char_start": 184, "char_end": 194, "line": " ]\n" }, { "line_no": 10, "char_start": 208, "char_end": 265, "line": " result = self._execute(command, credentials)\n" } ] }
{ "deleted": [ { "char_start": 115, "char_end": 118, "chars": "{} " }, { "char_start": 141, "char_end": 161, "chars": ".format(credentials)" } ], "added": [ { "char_start": 114, "char_end": 123, "chars": "[\n " }, { "char_start": 124, "char_end": 129, "chars": " '" }, { "char_start": 135, "char_end": 141, "chars": "',\n " }, { "char_start": 142, "char_end": 151, "chars": " '" }, { "char_start": 157, "char_end": 171, "chars": "',\n " }, { "char_start": 172, "char_end": 173, "chars": "'" }, { "char_start": 182, "char_end": 193, "chars": ",\n ]" }, { "char_start": 250, "char_end": 263, "chars": ", credentials" } ] }
github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db
src/backend/api/utils/rclone_connection.py
cwe-078
add_extra_args
def add_extra_args(self, args=None): """Add more args depending on how known args are set.""" parsed = vars(self.parse_known_args(nohelp=True)[0]) # find which image mode specified if any, and add additional arguments image_mode = parsed.get('image_mode', None) if image_mode is not None and image_mode != 'none': self.add_image_args(image_mode) # find which task specified if any, and add its specific arguments task = parsed.get('task', None) if task is not None: self.add_task_args(task) evaltask = parsed.get('evaltask', None) if evaltask is not None: self.add_task_args(evaltask) # find which model specified if any, and add its specific arguments model = parsed.get('model', None) if model is not None: self.add_model_subargs(model) # reset parser-level defaults over any model-level defaults try: self.set_defaults(**self._defaults) except AttributeError: raise RuntimeError('Please file an issue on github that argparse ' 'got an attribute error when parsing.')
def add_extra_args(self, args=None): """Add more args depending on how known args are set.""" parsed = vars(self.parse_known_args(args, nohelp=True)[0]) # find which image mode specified if any, and add additional arguments image_mode = parsed.get('image_mode', None) if image_mode is not None and image_mode != 'none': self.add_image_args(image_mode) # find which task specified if any, and add its specific arguments task = parsed.get('task', None) if task is not None: self.add_task_args(task) evaltask = parsed.get('evaltask', None) if evaltask is not None: self.add_task_args(evaltask) # find which model specified if any, and add its specific arguments model = parsed.get('model', None) if model is not None: self.add_model_subargs(model) # reset parser-level defaults over any model-level defaults try: self.set_defaults(**self._defaults) except AttributeError: raise RuntimeError('Please file an issue on github that argparse ' 'got an attribute error when parsing.')
{ "deleted": [ { "line_no": 3, "char_start": 106, "char_end": 167, "line": " parsed = vars(self.parse_known_args(nohelp=True)[0])\n" } ], "added": [ { "line_no": 3, "char_start": 106, "char_end": 173, "line": " parsed = vars(self.parse_known_args(args, nohelp=True)[0])\n" } ] }
{ "deleted": [], "added": [ { "char_start": 150, "char_end": 156, "chars": "args, " } ] }
github.com/freedombenLiu/ParlAI/commit/601668d569e1276e0b8bf2bf8fb43e391e10d170
parlai/core/params.py
cwe-078
_get_vdisk_fc_mappings
def _get_vdisk_fc_mappings(self, vdisk_name): """Return FlashCopy mappings that this vdisk is associated with.""" ssh_cmd = 'svcinfo lsvdiskfcmappings -nohdr %s' % vdisk_name out, err = self._run_ssh(ssh_cmd) mapping_ids = [] if (len(out.strip())): lines = out.strip().split('\n') mapping_ids = [line.split()[0] for line in lines] return mapping_ids
def _get_vdisk_fc_mappings(self, vdisk_name): """Return FlashCopy mappings that this vdisk is associated with.""" ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_name] out, err = self._run_ssh(ssh_cmd) mapping_ids = [] if (len(out.strip())): lines = out.strip().split('\n') mapping_ids = [line.split()[0] for line in lines] return mapping_ids
{ "deleted": [ { "line_no": 4, "char_start": 127, "char_end": 196, "line": " ssh_cmd = 'svcinfo lsvdiskfcmappings -nohdr %s' % vdisk_name\n" } ], "added": [ { "line_no": 4, "char_start": 127, "char_end": 200, "line": " ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_name]\n" } ] }
{ "deleted": [ { "char_start": 178, "char_end": 181, "chars": " %s" }, { "char_start": 182, "char_end": 184, "chars": " %" } ], "added": [ { "char_start": 145, "char_end": 146, "chars": "[" }, { "char_start": 154, "char_end": 156, "chars": "'," }, { "char_start": 157, "char_end": 158, "chars": "'" }, { "char_start": 175, "char_end": 177, "chars": "'," }, { "char_start": 178, "char_end": 179, "chars": "'" }, { "char_start": 186, "char_end": 187, "chars": "," }, { "char_start": 198, "char_end": 199, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
test_create_host
def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -iscsi -persona 1 -domain ' '(\'OpenStack\',) ' 'fakehost iqn.1993-08.org.debian:01:222') _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)
def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', 'iqn.1993-08.org.debian:01:222']) _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)
{ "deleted": [ { "line_no": 13, "char_start": 497, "char_end": 550, "line": " show_host_cmd = 'showhost -verbose fakehost'\n" }, { "line_no": 16, "char_start": 631, "char_end": 698, "line": " create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n" }, { "line_no": 17, "char_start": 698, "char_end": 745, "line": " '(\\'OpenStack\\',) '\n" }, { "line_no": 18, "char_start": 745, "char_end": 814, "line": " 'fakehost iqn.1993-08.org.debian:01:222')\n" } ], "added": [ { "line_no": 13, "char_start": 497, "char_end": 558, "line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n" }, { "line_no": 16, "char_start": 639, "char_end": 719, "line": " create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n" }, { "line_no": 17, "char_start": 719, "char_end": 775, "line": " ('OpenStack',), 'fakehost',\n" }, { "line_no": 18, "char_start": 775, "char_end": 837, "line": " 'iqn.1993-08.org.debian:01:222'])\n" } ] }
{ "deleted": [ { "char_start": 695, "char_end": 696, "chars": " " }, { "char_start": 725, "char_end": 726, "chars": "'" }, { "char_start": 727, "char_end": 728, "chars": "\\" }, { "char_start": 738, "char_end": 739, "chars": "\\" }, { "char_start": 772, "char_end": 781, "chars": "'fakehost" } ], "added": [ { "char_start": 521, "char_end": 522, "chars": "[" }, { "char_start": 531, "char_end": 533, "chars": "'," }, { "char_start": 534, "char_end": 535, "chars": "'" }, { "char_start": 543, "char_end": 545, "chars": "'," }, { "char_start": 546, "char_end": 547, "chars": "'" }, { "char_start": 556, "char_end": 557, "chars": "]" }, { "char_start": 666, "char_end": 667, "chars": "[" }, { "char_start": 678, "char_end": 680, "chars": "'," }, { "char_start": 681, "char_end": 682, "chars": "'" }, { "char_start": 688, "char_end": 690, "chars": "'," }, { "char_start": 691, "char_end": 692, "chars": "'" }, { "char_start": 700, "char_end": 702, "chars": "'," }, { "char_start": 703, "char_end": 704, "chars": "'" }, { "char_start": 705, "char_end": 707, "chars": "'," }, { "char_start": 708, "char_end": 709, "chars": "'" }, { "char_start": 717, "char_end": 718, "chars": "," }, { "char_start": 719, "char_end": 720, "chars": " " }, { "char_start": 761, "char_end": 762, "chars": "," }, { "char_start": 764, "char_end": 774, "chars": "fakehost'," }, { "char_start": 775, "char_end": 776, "chars": " " }, { "char_start": 834, "char_end": 835, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/tests/test_hp3par.py
cwe-078
_copy_volume
def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None, tpvv=True): # Virtual volume sets are not supported with the -online option cmd = 'createvvcopy -p %s -online ' % src_name if snap_cpg: cmd += '-snp_cpg %s ' % snap_cpg if tpvv: cmd += '-tpvv ' if cpg: cmd += cpg + ' ' cmd += dest_name LOG.debug('Creating clone of a volume with %s' % cmd) self._cli_run(cmd, None)
def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None, tpvv=True): # Virtual volume sets are not supported with the -online option cmd = ['createvvcopy', '-p', src_name, '-online'] if snap_cpg: cmd.extend(['-snp_cpg', snap_cpg]) if tpvv: cmd.append('-tpvv') if cpg: cmd.append(cpg) cmd.append(dest_name) LOG.debug('Creating clone of a volume with %s' % cmd) self._cli_run(cmd)
{ "deleted": [ { "line_no": 4, "char_start": 178, "char_end": 233, "line": " cmd = 'createvvcopy -p %s -online ' % src_name\n" }, { "line_no": 6, "char_start": 254, "char_end": 299, "line": " cmd += '-snp_cpg %s ' % snap_cpg\n" }, { "line_no": 8, "char_start": 316, "char_end": 344, "line": " cmd += '-tpvv '\n" }, { "line_no": 10, "char_start": 360, "char_end": 389, "line": " cmd += cpg + ' '\n" }, { "line_no": 11, "char_start": 389, "char_end": 414, "line": " cmd += dest_name\n" }, { "line_no": 13, "char_start": 476, "char_end": 508, "line": " self._cli_run(cmd, None)\n" } ], "added": [ { "line_no": 4, "char_start": 178, "char_end": 236, "line": " cmd = ['createvvcopy', '-p', src_name, '-online']\n" }, { "line_no": 6, "char_start": 257, "char_end": 304, "line": " cmd.extend(['-snp_cpg', snap_cpg])\n" }, { "line_no": 8, "char_start": 321, "char_end": 353, "line": " cmd.append('-tpvv')\n" }, { "line_no": 10, "char_start": 369, "char_end": 397, "line": " cmd.append(cpg)\n" }, { "line_no": 11, "char_start": 397, "char_end": 427, "line": " cmd.append(dest_name)\n" }, { "line_no": 13, "char_start": 489, "char_end": 515, "line": " self._cli_run(cmd)\n" } ] }
{ "deleted": [ { "char_start": 209, "char_end": 210, "chars": "%" }, { "char_start": 219, "char_end": 220, "chars": " " }, { "char_start": 221, "char_end": 232, "chars": " % src_name" }, { "char_start": 269, "char_end": 273, "chars": " += " }, { "char_start": 282, "char_end": 286, "chars": " %s " }, { "char_start": 287, "char_end": 289, "chars": " %" }, { "char_start": 331, "char_end": 335, "chars": " += " }, { "char_start": 341, "char_end": 342, "chars": " " }, { "char_start": 375, "char_end": 379, "chars": " += " }, { "char_start": 382, "char_end": 388, "chars": " + ' '" }, { "char_start": 400, "char_end": 404, "chars": " += " }, { "char_start": 501, "char_end": 507, "chars": ", None" } ], "added": [ { "char_start": 192, "char_end": 193, "chars": "[" }, { "char_start": 206, "char_end": 208, "chars": "'," }, { "char_start": 209, "char_end": 210, "chars": "'" }, { "char_start": 212, "char_end": 214, "chars": "'," }, { "char_start": 216, "char_end": 224, "chars": "rc_name," }, { "char_start": 225, "char_end": 226, "chars": "'" }, { "char_start": 234, "char_end": 235, "chars": "]" }, { "char_start": 272, "char_end": 281, "chars": ".extend([" }, { "char_start": 291, "char_end": 292, "chars": "," }, { "char_start": 301, "char_end": 303, "chars": "])" }, { "char_start": 336, "char_end": 344, "chars": ".append(" }, { "char_start": 351, "char_end": 352, "chars": ")" }, { "char_start": 384, "char_end": 392, "chars": ".append(" }, { "char_start": 395, "char_end": 396, "chars": ")" }, { "char_start": 408, "char_end": 416, "chars": ".append(" }, { "char_start": 425, "char_end": 426, "chars": ")" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
_get_active_nsp
def _get_active_nsp(self, hostname): """Return the active nsp, if one exists, for the given host.""" result = self.common._cli_run('showvlun -a -host %s' % hostname, None) if result: # first line is header result = result[1:] for line in result: info = line.split(",") if info and len(info) > 4: return info[4]
def _get_active_nsp(self, hostname): """Return the active nsp, if one exists, for the given host.""" result = self.common._cli_run(['showvlun', '-a', '-host', hostname]) if result: # first line is header result = result[1:] for line in result: info = line.split(",") if info and len(info) > 4: return info[4]
{ "deleted": [ { "line_no": 3, "char_start": 113, "char_end": 192, "line": " result = self.common._cli_run('showvlun -a -host %s' % hostname, None)\n" } ], "added": [ { "line_no": 3, "char_start": 113, "char_end": 190, "line": " result = self.common._cli_run(['showvlun', '-a', '-host', hostname])\n" } ] }
{ "deleted": [ { "char_start": 169, "char_end": 172, "chars": " %s" }, { "char_start": 173, "char_end": 175, "chars": " %" }, { "char_start": 184, "char_end": 190, "chars": ", None" } ], "added": [ { "char_start": 151, "char_end": 152, "chars": "[" }, { "char_start": 161, "char_end": 163, "chars": "'," }, { "char_start": 164, "char_end": 165, "chars": "'" }, { "char_start": 167, "char_end": 169, "chars": "'," }, { "char_start": 170, "char_end": 171, "chars": "'" }, { "char_start": 177, "char_end": 178, "chars": "," }, { "char_start": 187, "char_end": 188, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_iscsi.py
cwe-078
initialize_connection
def initialize_connection(self, volume, connector): """Restrict access to a volume.""" try: cmd = ['volume', 'select', volume['name'], 'access', 'create', 'initiator', connector['initiator']] if self.configuration.eqlx_use_chap: cmd.extend(['authmethod chap', 'username', self.configuration.eqlx_chap_login]) self._eql_execute(*cmd) iscsi_properties = self._get_iscsi_properties(volume) return { 'driver_volume_type': 'iscsi', 'data': iscsi_properties } except Exception: with excutils.save_and_reraise_exception(): LOG.error(_('Failed to initialize connection to volume %s'), volume['name'])
def initialize_connection(self, volume, connector): """Restrict access to a volume.""" try: cmd = ['volume', 'select', volume['name'], 'access', 'create', 'initiator', connector['initiator']] if self.configuration.eqlx_use_chap: cmd.extend(['authmethod', 'chap', 'username', self.configuration.eqlx_chap_login]) self._eql_execute(*cmd) iscsi_properties = self._get_iscsi_properties(volume) return { 'driver_volume_type': 'iscsi', 'data': iscsi_properties } except Exception: with excutils.save_and_reraise_exception(): LOG.error(_('Failed to initialize connection to volume %s'), volume['name'])
{ "deleted": [ { "line_no": 7, "char_start": 292, "char_end": 351, "line": " cmd.extend(['authmethod chap', 'username',\n" } ], "added": [ { "line_no": 7, "char_start": 292, "char_end": 354, "line": " cmd.extend(['authmethod', 'chap', 'username',\n" } ] }
{ "deleted": [], "added": [ { "char_start": 331, "char_end": 333, "chars": "'," }, { "char_start": 334, "char_end": 335, "chars": "'" } ] }
github.com/thatsdone/cinder/commit/9e858bebb89de05b1c9ecc27f5bd9fbff95a728e
cinder/volume/drivers/eqlx.py
cwe-078
mkdir
def mkdir(self, data, path): credentials = self._formatCredentials(data, name='current') command = ( '{credentials} ' 'rclone touch current:{path}/.keep' ).format( credentials=credentials, path=path, ) try: result = self._execute(command) return { 'message': 'Success', } except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))
def mkdir(self, data, path): credentials = self._formatCredentials(data, name='current') command = [ 'rclone', 'touch', 'current:{}/.keep'.format(path), ] try: result = self._execute(command, credentials) return { 'message': 'Success', } except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))
{ "deleted": [ { "line_no": 3, "char_start": 101, "char_end": 102, "line": "\n" }, { "line_no": 4, "char_start": 102, "char_end": 122, "line": " command = (\n" }, { "line_no": 5, "char_start": 122, "char_end": 151, "line": " '{credentials} '\n" }, { "line_no": 6, "char_start": 151, "char_end": 199, "line": " 'rclone touch current:{path}/.keep'\n" }, { "line_no": 7, "char_start": 199, "char_end": 217, "line": " ).format(\n" }, { "line_no": 8, "char_start": 217, "char_end": 254, "line": " credentials=credentials,\n" }, { "line_no": 9, "char_start": 254, "char_end": 277, "line": " path=path,\n" }, { "line_no": 10, "char_start": 277, "char_end": 287, "line": " )\n" }, { "line_no": 13, "char_start": 301, "char_end": 345, "line": " result = self._execute(command)\n" } ], "added": [ { "line_no": 3, "char_start": 101, "char_end": 121, "line": " command = [\n" }, { "line_no": 4, "char_start": 121, "char_end": 143, "line": " 'rclone',\n" }, { "line_no": 5, "char_start": 143, "char_end": 164, "line": " 'touch',\n" }, { "line_no": 6, "char_start": 164, "char_end": 209, "line": " 'current:{}/.keep'.format(path),\n" }, { "line_no": 7, "char_start": 209, "char_end": 219, "line": " ]\n" }, { "line_no": 10, "char_start": 233, "char_end": 290, "line": " result = self._execute(command, credentials)\n" } ] }
{ "deleted": [ { "char_start": 101, "char_end": 102, "chars": "\n" }, { "char_start": 120, "char_end": 121, "chars": "(" }, { "char_start": 135, "char_end": 137, "chars": "{c" }, { "char_start": 138, "char_end": 145, "chars": "edentia" }, { "char_start": 146, "char_end": 149, "chars": "s} " }, { "char_start": 164, "char_end": 171, "chars": "rclone " }, { "char_start": 186, "char_end": 190, "chars": "path" }, { "char_start": 198, "char_end": 208, "chars": "\n )" }, { "char_start": 216, "char_end": 266, "chars": "\n credentials=credentials,\n " }, { "char_start": 270, "char_end": 275, "chars": "=path" }, { "char_start": 285, "char_end": 286, "chars": ")" } ], "added": [ { "char_start": 119, "char_end": 120, "chars": "[" }, { "char_start": 134, "char_end": 135, "chars": "r" }, { "char_start": 136, "char_end": 139, "chars": "lon" }, { "char_start": 141, "char_end": 142, "chars": "," }, { "char_start": 161, "char_end": 166, "chars": "',\n " }, { "char_start": 167, "char_end": 177, "chars": " '" }, { "char_start": 206, "char_end": 207, "chars": ")" }, { "char_start": 217, "char_end": 218, "chars": "]" }, { "char_start": 275, "char_end": 288, "chars": ", credentials" } ] }
github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db
src/backend/api/utils/rclone_connection.py
cwe-078
populate_custom_grains_and_pillar
def populate_custom_grains_and_pillar(): ''' Populate local salt-minion grains and pillar fields values as specified in config file. For example: custom_grains_pillar: grains: - selinux: selinux:enabled - release: osrelease pillar: - ntpserver: network_services:ntpserver Note that the core grains are already included in hubble grains -- this is only necessary for custom grains and pillar data. ''' log.debug('Fetching custom grains and pillar details') grains = {} salt.modules.config.__opts__ = __opts__ custom_grains = __salt__['config.get']('custom_grains_pillar:grains', []) for grain in custom_grains: for key in grain: if _valid_command(grain[key]): value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\n')[1].strip() grains[key] = value custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', []) for pillar in custom_pillar: for key in pillar: if _valid_command(pillar[key]): value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\n')[1].strip() grains[key] = value log.debug('Done with fetching custom grains and pillar details') return grains
def populate_custom_grains_and_pillar(): ''' Populate local salt-minion grains and pillar fields values as specified in config file. For example: custom_grains_pillar: grains: - selinux: selinux:enabled - release: osrelease pillar: - ntpserver: network_services:ntpserver Note that the core grains are already included in hubble grains -- this is only necessary for custom grains and pillar data. ''' log.debug('Fetching custom grains and pillar details') grains = {} salt.modules.config.__opts__ = __opts__ custom_grains = __salt__['config.get']('custom_grains_pillar:grains', []) for grain in custom_grains: for key in grain: value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\n')[1].strip() grains[key] = value custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', []) for pillar in custom_pillar: for key in pillar: value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\n')[1].strip() grains[key] = value log.debug('Done with fetching custom grains and pillar details') return grains
{ "deleted": [ { "line_no": 24, "char_start": 751, "char_end": 794, "line": " if _valid_command(grain[key]):\n" }, { "line_no": 25, "char_start": 794, "char_end": 908, "line": " value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\\n')[1].strip()\n" }, { "line_no": 26, "char_start": 908, "char_end": 944, "line": " grains[key] = value\n" }, { "line_no": 30, "char_start": 1082, "char_end": 1126, "line": " if _valid_command(pillar[key]):\n" }, { "line_no": 31, "char_start": 1126, "char_end": 1241, "line": " value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\\n')[1].strip()\n" }, { "line_no": 32, "char_start": 1241, "char_end": 1277, "line": " grains[key] = value\n" } ], "added": [ { "line_no": 24, "char_start": 751, "char_end": 855, "line": " value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\\n')[1].strip()\n" }, { "line_no": 25, "char_start": 855, "char_end": 887, "line": " grains[key] = value\n" }, { "line_no": 29, "char_start": 1025, "char_end": 1130, "line": " value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\\n')[1].strip()\n" }, { "line_no": 30, "char_start": 1130, "char_end": 1162, "line": " grains[key] = value\n" } ] }
{ "deleted": [ { "char_start": 763, "char_end": 810, "chars": "if _valid_command(grain[key]):\n " }, { "char_start": 860, "char_end": 872, "chars": "{0}'.format(" }, { "char_start": 882, "char_end": 883, "chars": ")" }, { "char_start": 908, "char_end": 912, "chars": " " }, { "char_start": 1094, "char_end": 1142, "chars": "if _valid_command(pillar[key]):\n " }, { "char_start": 1192, "char_end": 1204, "chars": "{0}'.format(" }, { "char_start": 1215, "char_end": 1216, "chars": ")" }, { "char_start": 1241, "char_end": 1245, "chars": " " } ], "added": [ { "char_start": 791, "char_end": 792, "chars": "[" }, { "char_start": 802, "char_end": 804, "chars": "'," }, { "char_start": 805, "char_end": 806, "chars": "'" }, { "char_start": 817, "char_end": 819, "chars": ", " }, { "char_start": 829, "char_end": 830, "chars": "]" }, { "char_start": 1065, "char_end": 1066, "chars": "[" }, { "char_start": 1076, "char_end": 1078, "chars": "'," }, { "char_start": 1079, "char_end": 1080, "chars": "'" }, { "char_start": 1091, "char_end": 1093, "chars": ", " }, { "char_start": 1104, "char_end": 1105, "chars": "]" } ] }
github.com/hubblestack/hubble/commit/d9ca4a93ea5aabb1298c5b3dbfb23e94203428b9
hubblestack/extmods/grains/custom_grains_pillar.py
cwe-078
copy
def copy(self, src_data, src_path, dst_data, dst_path, job_id=None): credentials = '' if src_data is None: # Local src = src_path else: credentials += self._formatCredentials(src_data, name='src') src = 'src:{}'.format(src_path) if dst_data is None: # Local dst = dst_path else: credentials += self._formatCredentials(dst_data, name='dst') dst = 'dst:{}'.format(dst_path) command = ( '{credentials} ' 'rclone copy {src} {dst} ' '--progress ' '--stats 2s ' ).format( credentials=credentials, src=src, dst=dst, ) logging.info(sanitize(command)) if job_id is None: job_id = self._get_next_job_id() else: if self._job_id_exists(job_id): raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id)) self._stop_events[job_id] = threading.Event() try: self._execute_interactive(command, job_id) except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e))) return job_id
def copy(self, src_data, src_path, dst_data, dst_path, job_id=None): credentials = {} if src_data is None: # Local src = src_path else: credentials.update(self._formatCredentials(src_data, name='src')) src = 'src:{}'.format(src_path) if dst_data is None: # Local dst = dst_path else: credentials.update(self._formatCredentials(dst_data, name='dst')) dst = 'dst:{}'.format(dst_path) command = [ 'rclone', 'copy', src, dst, '--progress', '--stats', '2s', ] bash_command = "{} {}".format( ' '.join("{}='{}'".format(key, value) for key, value in credentials.items()), ' '.join(command), ) logging.info(sanitize(bash_command)) if job_id is None: job_id = self._get_next_job_id() else: if self._job_id_exists(job_id): raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id)) self._stop_events[job_id] = threading.Event() try: self._execute_interactive(command, credentials, job_id) except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e))) return job_id
{ "deleted": [ { "line_no": 2, "char_start": 73, "char_end": 98, "line": " credentials = ''\n" }, { "line_no": 7, "char_start": 177, "char_end": 250, "line": " credentials += self._formatCredentials(src_data, name='src')\n" }, { "line_no": 13, "char_start": 373, "char_end": 446, "line": " credentials += self._formatCredentials(dst_data, name='dst')\n" }, { "line_no": 17, "char_start": 492, "char_end": 512, "line": " command = (\n" }, { "line_no": 18, "char_start": 512, "char_end": 541, "line": " '{credentials} '\n" }, { "line_no": 19, "char_start": 541, "char_end": 580, "line": " 'rclone copy {src} {dst} '\n" }, { "line_no": 20, "char_start": 580, "char_end": 606, "line": " '--progress '\n" }, { "line_no": 21, "char_start": 606, "char_end": 632, "line": " '--stats 2s '\n" }, { "line_no": 22, "char_start": 632, "char_end": 650, "line": " ).format(\n" }, { "line_no": 23, "char_start": 650, "char_end": 687, "line": " credentials=credentials,\n" }, { "line_no": 24, "char_start": 687, "char_end": 708, "line": " src=src,\n" }, { "line_no": 25, "char_start": 708, "char_end": 729, "line": " dst=dst,\n" }, { "line_no": 28, "char_start": 740, "char_end": 780, "line": " logging.info(sanitize(command))\n" }, { "line_no": 39, "char_start": 1073, "char_end": 1128, "line": " self._execute_interactive(command, job_id)\n" } ], "added": [ { "line_no": 2, "char_start": 73, "char_end": 98, "line": " credentials = {}\n" }, { "line_no": 7, "char_start": 177, "char_end": 255, "line": " credentials.update(self._formatCredentials(src_data, name='src'))\n" }, { "line_no": 13, "char_start": 378, "char_end": 456, "line": " credentials.update(self._formatCredentials(dst_data, name='dst'))\n" }, { "line_no": 16, "char_start": 501, "char_end": 521, "line": " command = [\n" }, { "line_no": 17, "char_start": 521, "char_end": 543, "line": " 'rclone',\n" }, { "line_no": 18, "char_start": 543, "char_end": 563, "line": " 'copy',\n" }, { "line_no": 19, "char_start": 563, "char_end": 580, "line": " src,\n" }, { "line_no": 20, "char_start": 580, "char_end": 597, "line": " dst,\n" }, { "line_no": 21, "char_start": 597, "char_end": 623, "line": " '--progress',\n" }, { "line_no": 22, "char_start": 623, "char_end": 652, "line": " '--stats', '2s',\n" }, { "line_no": 23, "char_start": 652, "char_end": 662, "line": " ]\n" }, { "line_no": 25, "char_start": 663, "char_end": 702, "line": " bash_command = \"{} {}\".format(\n" }, { "line_no": 26, "char_start": 702, "char_end": 792, "line": " ' '.join(\"{}='{}'\".format(key, value) for key, value in credentials.items()),\n" }, { "line_no": 27, "char_start": 792, "char_end": 823, "line": " ' '.join(command),\n" }, { "line_no": 30, "char_start": 834, "char_end": 879, "line": " logging.info(sanitize(bash_command))\n" }, { "line_no": 41, "char_start": 1172, "char_end": 1240, "line": " self._execute_interactive(command, credentials, job_id)\n" } ] }
{ "deleted": [ { "char_start": 95, "char_end": 97, "chars": "''" }, { "char_start": 200, "char_end": 204, "chars": " += " }, { "char_start": 396, "char_end": 400, "chars": " += " }, { "char_start": 491, "char_end": 492, "chars": "\n" }, { "char_start": 510, "char_end": 511, "chars": "(" }, { "char_start": 525, "char_end": 526, "chars": "{" }, { "char_start": 527, "char_end": 528, "chars": "r" }, { "char_start": 529, "char_end": 539, "chars": "dentials} " }, { "char_start": 554, "char_end": 561, "chars": "rclone " }, { "char_start": 566, "char_end": 567, "chars": "{" }, { "char_start": 570, "char_end": 571, "chars": "}" }, { "char_start": 572, "char_end": 573, "chars": "{" }, { "char_start": 576, "char_end": 579, "chars": "} '" }, { "char_start": 603, "char_end": 604, "chars": " " }, { "char_start": 630, "char_end": 631, "chars": "'" }, { "char_start": 640, "char_end": 641, "chars": ")" }, { "char_start": 662, "char_end": 663, "chars": "c" }, { "char_start": 665, "char_end": 666, "chars": "d" }, { "char_start": 667, "char_end": 670, "chars": "nti" }, { "char_start": 672, "char_end": 674, "chars": "s=" }, { "char_start": 699, "char_end": 701, "chars": "sr" }, { "char_start": 702, "char_end": 720, "chars": "=src,\n " }, { "char_start": 721, "char_end": 727, "chars": "st=dst" } ], "added": [ { "char_start": 95, "char_end": 97, "chars": "{}" }, { "char_start": 200, "char_end": 208, "chars": ".update(" }, { "char_start": 252, "char_end": 253, "chars": ")" }, { "char_start": 401, "char_end": 409, "chars": ".update(" }, { "char_start": 454, "char_end": 455, "chars": ")" }, { "char_start": 519, "char_end": 520, "chars": "[" }, { "char_start": 535, "char_end": 536, "chars": "c" }, { "char_start": 537, "char_end": 540, "chars": "one" }, { "char_start": 541, "char_end": 542, "chars": "," }, { "char_start": 560, "char_end": 563, "chars": "',\n" }, { "char_start": 564, "char_end": 575, "chars": " " }, { "char_start": 578, "char_end": 586, "chars": ",\n " }, { "char_start": 587, "char_end": 592, "chars": " " }, { "char_start": 595, "char_end": 596, "chars": "," }, { "char_start": 621, "char_end": 622, "chars": "," }, { "char_start": 643, "char_end": 645, "chars": "'," }, { "char_start": 646, "char_end": 647, "chars": "'" }, { "char_start": 650, "char_end": 651, "chars": "," }, { "char_start": 660, "char_end": 693, "chars": "]\n\n bash_command = \"{} {}\"" }, { "char_start": 714, "char_end": 735, "chars": "' '.join(\"{}='{}'\".fo" }, { "char_start": 736, "char_end": 741, "chars": "mat(k" }, { "char_start": 742, "char_end": 749, "chars": "y, valu" }, { "char_start": 750, "char_end": 762, "chars": ") for key, v" }, { "char_start": 764, "char_end": 770, "chars": "ue in " }, { "char_start": 781, "char_end": 786, "chars": ".item" }, { "char_start": 787, "char_end": 790, "chars": "())" }, { "char_start": 804, "char_end": 819, "chars": "' '.join(comman" }, { "char_start": 820, "char_end": 821, "chars": ")" }, { "char_start": 864, "char_end": 869, "chars": "bash_" }, { "char_start": 1217, "char_end": 1230, "chars": ", credentials" } ] }
github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db
src/backend/api/utils/rclone_connection.py
cwe-078
IsBlacklistedArg
bool IsBlacklistedArg(const base::CommandLine::CharType* arg) { #if defined(OS_WIN) const auto converted = base::WideToUTF8(arg); const char* a = converted.c_str(); #else const char* a = arg; #endif static const char* prefixes[] = {"--", "-", "/"}; int prefix_length = 0; for (auto& prefix : prefixes) { if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) { prefix_length = strlen(prefix); break; } } if (prefix_length > 0) { a += prefix_length; std::string switch_name(a, strcspn(a, "=")); auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist), switch_name); if (iter != std::end(kBlacklist) && switch_name == *iter) { return true; } } return false; }
bool IsBlacklistedArg(const base::CommandLine::CharType* arg) { #if defined(OS_WIN) const auto converted = base::WideToUTF8(arg); const char* a = converted.c_str(); #else const char* a = arg; #endif static const char* prefixes[] = {"--", "-", "/"}; int prefix_length = 0; for (auto& prefix : prefixes) { if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) { prefix_length = strlen(prefix); break; } } if (prefix_length > 0) { a += prefix_length; std::string switch_name = base::ToLowerASCII(base::StringPiece(a, strcspn(a, "="))); auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist), switch_name); if (iter != std::end(kBlacklist) && switch_name == *iter) { return true; } } return false; }
{ "deleted": [ { "line_no": 21, "char_start": 500, "char_end": 549, "line": " std::string switch_name(a, strcspn(a, \"=\"));\n" } ], "added": [ { "line_no": 21, "char_start": 500, "char_end": 530, "line": " std::string switch_name =\n" }, { "line_no": 22, "char_start": 530, "char_end": 597, "line": " base::ToLowerASCII(base::StringPiece(a, strcspn(a, \"=\")));\n" } ] }
{ "deleted": [], "added": [ { "char_start": 527, "char_end": 574, "chars": " =\n base::ToLowerASCII(base::StringPiece" }, { "char_start": 592, "char_end": 593, "chars": ")" } ] }
github.com/electron/electron/commit/ce361a12e355f9e1e99c989f1ea056c9e502dbe7
atom/app/command_line_args.cc
cwe-078
_remove_volume_from_volume_set
def _remove_volume_from_volume_set(self, volume_name, vvs_name): self._cli_run('removevvset -f %s %s' % (vvs_name, volume_name), None)
def _remove_volume_from_volume_set(self, volume_name, vvs_name): self._cli_run(['removevvset', '-f', vvs_name, volume_name])
{ "deleted": [ { "line_no": 2, "char_start": 69, "char_end": 146, "line": " self._cli_run('removevvset -f %s %s' % (vvs_name, volume_name), None)\n" } ], "added": [ { "line_no": 2, "char_start": 69, "char_end": 136, "line": " self._cli_run(['removevvset', '-f', vvs_name, volume_name])\n" } ] }
{ "deleted": [ { "char_start": 106, "char_end": 112, "chars": " %s %s" }, { "char_start": 113, "char_end": 115, "chars": " %" }, { "char_start": 116, "char_end": 117, "chars": "(" }, { "char_start": 138, "char_end": 145, "chars": "), None" } ], "added": [ { "char_start": 91, "char_end": 92, "chars": "[" }, { "char_start": 104, "char_end": 106, "chars": "'," }, { "char_start": 107, "char_end": 108, "chars": "'" }, { "char_start": 111, "char_end": 112, "chars": "," }, { "char_start": 134, "char_end": 135, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f
cinder/volume/drivers/san/hp/hp_3par_common.py
cwe-078
handle_message
def handle_message(self, ch, method, properties, body): """ this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body """ input = {} try: self.sessid = method.routing_key input = json_decode(body) data = input['data'] # since this comes as "path" we dont know if it's view or workflow yet #TODO: just a workaround till we modify ui to if 'path' in data: if data['path'] in settings.VIEW_URLS: data['view'] = data['path'] else: data['wf'] = data['path'] session = Session(self.sessid) headers = {'remote_ip': input['_zops_remote_ip']} if 'wf' in data: output = self._handle_workflow(session, data, headers) elif 'job' in data: self._handle_job(session, data, headers) return else: output = self._handle_view(session, data, headers) except HTTPError as e: import sys if hasattr(sys, '_called_from_test'): raise output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), "code": e.code} log.exception("Http error occurred") except: self.current = Current(session=session, input=data) self.current.headers = headers import sys if hasattr(sys, '_called_from_test'): raise err = traceback.format_exc() output = {'error': self._prepare_error_msg(err), "code": 500} log.exception("Worker error occurred with messsage body:\n%s" % body) if 'callbackID' in input: output['callbackID'] = input['callbackID'] log.info("OUTPUT for %s: %s" % (self.sessid, output)) output['reply_timestamp'] = time() self.send_output(output)
def handle_message(self, ch, method, properties, body): """ this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body """ input = {} headers = {} try: self.sessid = method.routing_key input = json_decode(body) data = input['data'] # since this comes as "path" we dont know if it's view or workflow yet # TODO: just a workaround till we modify ui to if 'path' in data: if data['path'] in settings.VIEW_URLS: data['view'] = data['path'] else: data['wf'] = data['path'] session = Session(self.sessid) headers = {'remote_ip': input['_zops_remote_ip'], 'source': input['_zops_source']} if 'wf' in data: output = self._handle_workflow(session, data, headers) elif 'job' in data: self._handle_job(session, data, headers) return else: output = self._handle_view(session, data, headers) except HTTPError as e: import sys if hasattr(sys, '_called_from_test'): raise output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), "code": e.code} log.exception("Http error occurred") except: self.current = Current(session=session, input=data) self.current.headers = headers import sys if hasattr(sys, '_called_from_test'): raise err = traceback.format_exc() output = {'error': self._prepare_error_msg(err), "code": 500} log.exception("Worker error occurred with messsage body:\n%s" % body) if 'callbackID' in input: output['callbackID'] = input['callbackID'] log.info("OUTPUT for %s: %s" % (self.sessid, output)) output['reply_timestamp'] = time() self.send_output(output)
{ "deleted": [ { "line_no": 28, "char_start": 867, "char_end": 929, "line": " headers = {'remote_ip': input['_zops_remote_ip']}\n" } ], "added": [ { "line_no": 13, "char_start": 349, "char_end": 370, "line": " headers = {}\n" }, { "line_no": 29, "char_start": 889, "char_end": 951, "line": " headers = {'remote_ip': input['_zops_remote_ip'],\n" }, { "line_no": 30, "char_start": 951, "char_end": 1007, "line": " 'source': input['_zops_source']}\n" } ] }
{ "deleted": [], "added": [ { "char_start": 357, "char_end": 378, "chars": "headers = {}\n " }, { "char_start": 597, "char_end": 598, "chars": " " }, { "char_start": 947, "char_end": 1003, "chars": "'],\n 'source': input['_zops_source" } ] }
github.com/zetaops/zengine/commit/52eafbee90f8ddf78be0c7452828d49423246851
zengine/wf_daemon.py
cwe-078
_add_chapsecret_to_host
def _add_chapsecret_to_host(self, host_name): """Generate and store a randomly-generated CHAP secret for the host.""" chap_secret = utils.generate_password() ssh_cmd = ('svctask chhost -chapsecret "%(chap_secret)s" %(host_name)s' % {'chap_secret': chap_secret, 'host_name': host_name}) out, err = self._run_ssh(ssh_cmd) # No output should be returned from chhost self._assert_ssh_return(len(out.strip()) == 0, '_add_chapsecret_to_host', ssh_cmd, out, err) return chap_secret
def _add_chapsecret_to_host(self, host_name): """Generate and store a randomly-generated CHAP secret for the host.""" chap_secret = utils.generate_password() ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name] out, err = self._run_ssh(ssh_cmd) # No output should be returned from chhost self._assert_ssh_return(len(out.strip()) == 0, '_add_chapsecret_to_host', ssh_cmd, out, err) return chap_secret
{ "deleted": [ { "line_no": 5, "char_start": 179, "char_end": 259, "line": " ssh_cmd = ('svctask chhost -chapsecret \"%(chap_secret)s\" %(host_name)s'\n" }, { "line_no": 6, "char_start": 259, "char_end": 334, "line": " % {'chap_secret': chap_secret, 'host_name': host_name})\n" } ], "added": [ { "line_no": 5, "char_start": 179, "char_end": 258, "line": " ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name]\n" } ] }
{ "deleted": [ { "char_start": 197, "char_end": 198, "chars": "(" }, { "char_start": 206, "char_end": 225, "chars": " chhost -chapsecret" }, { "char_start": 226, "char_end": 229, "chars": "\"%(" }, { "char_start": 231, "char_end": 246, "chars": "ap_secret)s\" %(" }, { "char_start": 250, "char_end": 257, "chars": "_name)s" }, { "char_start": 258, "char_end": 279, "chars": "\n %" }, { "char_start": 280, "char_end": 281, "chars": "{" }, { "char_start": 286, "char_end": 287, "chars": "_" }, { "char_start": 294, "char_end": 295, "chars": ":" }, { "char_start": 309, "char_end": 310, "chars": "'" }, { "char_start": 319, "char_end": 333, "chars": "': host_name})" } ], "added": [ { "char_start": 197, "char_end": 198, "chars": "[" }, { "char_start": 206, "char_end": 208, "chars": "'," }, { "char_start": 209, "char_end": 210, "chars": "'" }, { "char_start": 217, "char_end": 218, "chars": "," }, { "char_start": 220, "char_end": 221, "chars": "-" }, { "char_start": 232, "char_end": 233, "chars": "," }, { "char_start": 256, "char_end": 257, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
_call_prepare_fc_map
def _call_prepare_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})
def _call_prepare_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id]) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})
{ "deleted": [ { "line_no": 3, "char_start": 76, "char_end": 153, "line": " out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id)\n" } ], "added": [ { "line_no": 3, "char_start": 76, "char_end": 154, "line": " out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])\n" } ] }
{ "deleted": [ { "char_start": 135, "char_end": 138, "chars": " %s" }, { "char_start": 139, "char_end": 141, "chars": " %" } ], "added": [ { "char_start": 113, "char_end": 114, "chars": "[" }, { "char_start": 122, "char_end": 124, "chars": "'," }, { "char_start": 125, "char_end": 126, "chars": "'" }, { "char_start": 140, "char_end": 141, "chars": "," }, { "char_start": 151, "char_end": 152, "chars": "]" } ] }
github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4
cinder/volume/drivers/storwize_svc.py
cwe-078
bin_symbols
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, "bin.demangle"); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3); const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, "bin"); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("["); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs exports\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Exports]\n"); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Symbols]\n"); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n"); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf ("%s.%s", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf ("[Warning] Can't find flag (%s)\n", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, "\"", "\\\"", 1); r_cons_printf ("%s{\"name\":\"%s\"," "\"demname\":\"%s\"," "\"flagname\":\"%s\"," "\"ordinal\":%d," "\"bind\":\"%s\"," "\"size\":%d," "\"type\":\"%s\"," "\"vaddr\":%"PFMT64d"," "\"paddr\":%"PFMT64d"}", ((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""), str, sn.demname? sn.demname: "", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("0x%08"PFMT64x" %d %s\n", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("%s\n", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, "imp.", 4)) { if (lastfs != 'i') { r_cons_printf ("fs imports\n"); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? "exports": "symbols"; r_cons_printf ("fs %s\n", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n", r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, "pe")) { char *module = strdup (r_symbol_name); char *p = strstr (module, ".dll_"); if (p && strstr (module, "imp.")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf ("k bin/pe/%s/%d=%s.%s\n", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf ("k bin/pe/%s/%d=%s\n", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: "NONE"; const char *type = symbol->type? symbol->type: "NONE"; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf ("%03u", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf (" ----------"); } else { r_cons_printf (" 0x%08"PFMT64x, symbol->paddr); } r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n", addr, bind, type, symbol->size, *name? " ": "", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf ("{}"); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("]"); } r_spaces_pop (&r->anal->meta_spaces); return true; }
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, "bin.demangle"); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3); const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, "bin"); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("["); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs exports\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Exports]\n"); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Symbols]\n"); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n"); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf ("%s.%s", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf ("[Warning] Can't find flag (%s)\n", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, "\"", "\\\"", 1); r_cons_printf ("%s{\"name\":\"%s\"," "\"demname\":\"%s\"," "\"flagname\":\"%s\"," "\"ordinal\":%d," "\"bind\":\"%s\"," "\"size\":%d," "\"type\":\"%s\"," "\"vaddr\":%"PFMT64d"," "\"paddr\":%"PFMT64d"}", ((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""), str, sn.demname? sn.demname: "", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("0x%08"PFMT64x" %d %s\n", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("%s\n", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, "imp.", 4)) { if (lastfs != 'i') { r_cons_printf ("fs imports\n"); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? "exports": "symbols"; r_cons_printf ("fs %s\n", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n", r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, "pe")) { char *module = strdup (r_symbol_name); char *p = strstr (module, ".dll_"); if (p && strstr (module, "imp.")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf ("\"k bin/pe/%s/%d=%s.%s\"\n", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf ("\"k bin/pe/%s/%d=%s\"\n", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: "NONE"; const char *type = symbol->type? symbol->type: "NONE"; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf ("%03u", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf (" ----------"); } else { r_cons_printf (" 0x%08"PFMT64x, symbol->paddr); } r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n", addr, bind, type, symbol->size, *name? " ": "", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf ("{}"); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("]"); } r_spaces_pop (&r->anal->meta_spaces); return true; }
{ "deleted": [ { "line_no": 211, "char_start": 6599, "char_end": 6647, "line": "\t\t\t\t\t\t\tr_cons_printf (\"k bin/pe/%s/%d=%s.%s\\n\",\n" }, { "line_no": 214, "char_start": 6721, "char_end": 6766, "line": "\t\t\t\t\t\t\tr_cons_printf (\"k bin/pe/%s/%d=%s\\n\",\n" } ], "added": [ { "line_no": 211, "char_start": 6599, "char_end": 6651, "line": "\t\t\t\t\t\t\tr_cons_printf (\"\\\"k bin/pe/%s/%d=%s.%s\\\"\\n\",\n" }, { "line_no": 214, "char_start": 6725, "char_end": 6774, "line": "\t\t\t\t\t\t\tr_cons_printf (\"\\\"k bin/pe/%s/%d=%s\\\"\\n\",\n" } ] }
{ "deleted": [], "added": [ { "char_start": 6622, "char_end": 6624, "chars": "\\\"" }, { "char_start": 6644, "char_end": 6646, "chars": "\\\"" }, { "char_start": 6748, "char_end": 6750, "chars": "\\\"" }, { "char_start": 6767, "char_end": 6769, "chars": "\\\"" } ] }
github.com/radareorg/radare2/commit/5411543a310a470b1257fb93273cdd6e8dfcb3af
libr/core/cbin.c
cwe-078
on_message
def on_message( self, profile_id, profile_name, level, message, timeout ): if 1 == level: cmd = "notify-send " if timeout > 0: cmd = cmd + " -t %s" % (1000 * timeout) title = "Back In Time (%s) : %s" % (self.user, profile_name) message = message.replace("\n", ' ') message = message.replace("\r", '') cmd = cmd + " \"%s\" \"%s\"" % (title, message) print(cmd) os.system(cmd) return
def on_message( self, profile_id, profile_name, level, message, timeout ): if 1 == level: cmd = ['notify-send'] if timeout > 0: cmd.extend(['-t', str(1000 * timeout)]) title = "Back In Time (%s) : %s" % (self.user, profile_name) message = message.replace("\n", ' ') message = message.replace("\r", '') cmd.append(title) cmd.append(message) subprocess.Popen(cmd).communicate() return
{ "deleted": [ { "line_no": 3, "char_start": 102, "char_end": 135, "line": " cmd = \"notify-send \"\n" }, { "line_no": 5, "char_start": 163, "char_end": 219, "line": " cmd = cmd + \" -t %s\" % (1000 * timeout)\n" }, { "line_no": 11, "char_start": 391, "char_end": 451, "line": " cmd = cmd + \" \\\"%s\\\" \\\"%s\\\"\" % (title, message)\n" }, { "line_no": 12, "char_start": 451, "char_end": 474, "line": " print(cmd)\n" }, { "line_no": 13, "char_start": 474, "char_end": 501, "line": " os.system(cmd)\n" } ], "added": [ { "line_no": 3, "char_start": 102, "char_end": 136, "line": " cmd = ['notify-send']\n" }, { "line_no": 5, "char_start": 164, "char_end": 220, "line": " cmd.extend(['-t', str(1000 * timeout)])\n" }, { "line_no": 11, "char_start": 392, "char_end": 422, "line": " cmd.append(title)\n" }, { "line_no": 12, "char_start": 422, "char_end": 454, "line": " cmd.append(message)\n" }, { "line_no": 13, "char_start": 454, "char_end": 502, "line": " subprocess.Popen(cmd).communicate()\n" } ] }
{ "deleted": [ { "char_start": 120, "char_end": 121, "chars": "\"" }, { "char_start": 132, "char_end": 134, "chars": " \"" }, { "char_start": 182, "char_end": 187, "chars": " = cm" }, { "char_start": 188, "char_end": 193, "chars": " + \" " }, { "char_start": 196, "char_end": 197, "chars": "%" }, { "char_start": 198, "char_end": 202, "chars": "\" % " }, { "char_start": 406, "char_end": 411, "chars": " = cm" }, { "char_start": 412, "char_end": 434, "chars": " + \" \\\"%s\\\" \\\"%s\\\"\" % " }, { "char_start": 440, "char_end": 449, "chars": ", message" }, { "char_start": 464, "char_end": 466, "chars": "ri" }, { "char_start": 467, "char_end": 468, "chars": "t" }, { "char_start": 469, "char_end": 470, "chars": "c" }, { "char_start": 471, "char_end": 472, "chars": "d" }, { "char_start": 486, "char_end": 487, "chars": "o" }, { "char_start": 488, "char_end": 489, "chars": "." }, { "char_start": 490, "char_end": 491, "chars": "y" }, { "char_start": 492, "char_end": 493, "chars": "t" }, { "char_start": 494, "char_end": 495, "chars": "m" } ], "added": [ { "char_start": 120, "char_end": 122, "chars": "['" }, { "char_start": 133, "char_end": 135, "chars": "']" }, { "char_start": 183, "char_end": 189, "chars": ".exten" }, { "char_start": 190, "char_end": 193, "chars": "(['" }, { "char_start": 195, "char_end": 197, "chars": "'," }, { "char_start": 199, "char_end": 201, "chars": "tr" }, { "char_start": 216, "char_end": 218, "chars": ")]" }, { "char_start": 407, "char_end": 413, "chars": ".appen" }, { "char_start": 434, "char_end": 439, "chars": "cmd.a" }, { "char_start": 440, "char_end": 442, "chars": "pe" }, { "char_start": 443, "char_end": 444, "chars": "d" }, { "char_start": 446, "char_end": 452, "chars": "essage" }, { "char_start": 466, "char_end": 471, "chars": "subpr" }, { "char_start": 472, "char_end": 475, "chars": "ces" }, { "char_start": 477, "char_end": 480, "chars": "Pop" }, { "char_start": 481, "char_end": 482, "chars": "n" }, { "char_start": 486, "char_end": 500, "chars": ").communicate(" } ] }
github.com/bit-team/backintime/commit/cef81d0da93ff601252607df3db1a48f7f6f01b3
qt4/plugins/notifyplugin.py
cwe-078
podbeuter::pb_controller::play_file
void pb_controller::play_file(const std::string& file) { std::string cmdline; std::string player = cfg->get_configvalue("player"); if (player == "") return; cmdline.append(player); cmdline.append(" \""); cmdline.append(utils::replace_all(file,"\"", "\\\"")); cmdline.append("\""); stfl::reset(); utils::run_interactively(cmdline, "pb_controller::play_file"); }
void pb_controller::play_file(const std::string& file) { std::string cmdline; std::string player = cfg->get_configvalue("player"); if (player == "") return; cmdline.append(player); cmdline.append(" '"); cmdline.append(utils::replace_all(file,"'", "%27")); cmdline.append("'"); stfl::reset(); utils::run_interactively(cmdline, "pb_controller::play_file"); }
{ "deleted": [ { "line_no": 7, "char_start": 187, "char_end": 211, "line": "\tcmdline.append(\" \\\"\");\n" }, { "line_no": 8, "char_start": 211, "char_end": 267, "line": "\tcmdline.append(utils::replace_all(file,\"\\\"\", \"\\\\\\\"\"));\n" }, { "line_no": 9, "char_start": 267, "char_end": 290, "line": "\tcmdline.append(\"\\\"\");\n" } ], "added": [ { "line_no": 7, "char_start": 187, "char_end": 210, "line": "\tcmdline.append(\" '\");\n" }, { "line_no": 8, "char_start": 210, "char_end": 264, "line": "\tcmdline.append(utils::replace_all(file,\"'\", \"%27\"));\n" }, { "line_no": 9, "char_start": 264, "char_end": 286, "line": "\tcmdline.append(\"'\");\n" } ] }
{ "deleted": [ { "char_start": 205, "char_end": 207, "chars": "\\\"" }, { "char_start": 252, "char_end": 254, "chars": "\\\"" }, { "char_start": 258, "char_end": 262, "chars": "\\\\\\\"" }, { "char_start": 284, "char_end": 286, "chars": "\\\"" } ], "added": [ { "char_start": 205, "char_end": 206, "chars": "'" }, { "char_start": 251, "char_end": 252, "chars": "'" }, { "char_start": 256, "char_end": 259, "chars": "%27" }, { "char_start": 281, "char_end": 282, "chars": "'" } ] }
github.com/akrennmair/newsbeuter/commit/c8fea2f60c18ed30bdd1bb6f798e994e51a58260
src/pb_controller.cpp
cwe-078