code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
template <class T> void testFeatTable(const T & table, const char * testName) { FeatureMap testFeatureMap; dummyFace.replace_table(TtfUtil::Tag::Feat, &table, sizeof(T)); gr_face * face = gr_make_face_with_ops(&dummyFace, &face_handle::ops, gr_face_dumbRendering); if (!face) throw std::runtime_error("failed to load font"); bool readStatus = testFeatureMap.readFeats(*face); testAssert("readFeats", readStatus); fprintf(stderr, testName, NULL); testAssertEqual("test num features %hu,%hu\n", testFeatureMap.numFeats(), table.m_header.m_numFeat); for (size_t i = 0; i < sizeof(table.m_defs) / sizeof(FeatDefn); i++) { const FeatureRef * ref = testFeatureMap.findFeatureRef(table.m_defs[i].m_featId); testAssert("test feat\n", ref); testAssertEqual("test feat settings %hu %hu\n", ref->getNumSettings(), table.m_defs[i].m_numFeatSettings); testAssertEqual("test feat label %hu %hu\n", ref->getNameId(), table.m_defs[i].m_label); size_t settingsIndex = (table.m_defs[i].m_settingsOffset - sizeof(FeatHeader) - (sizeof(FeatDefn) * table.m_header.m_numFeat)) / sizeof(FeatSetting); for (size_t j = 0; j < table.m_defs[i].m_numFeatSettings; j++) { testAssertEqual("setting label %hu %hu\n", ref->getSettingName(j), table.m_settings[settingsIndex+j].m_label); } } gr_face_destroy(face); }
0
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles) { auto* zei = entries.getUnchecked (index); #if JUCE_WINDOWS auto entryPath = zei->entry.filename; #else auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/'); #endif if (entryPath.isEmpty()) return Result::ok(); auto targetFile = targetDirectory.getChildFile (entryPath); if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\')) return targetFile.createDirectory(); // (entry is a directory, not a file) std::unique_ptr<InputStream> in (createStreamForEntry (index)); if (in == nullptr) return Result::fail ("Failed to open the zip file for reading"); if (targetFile.exists()) { if (! shouldOverwriteFiles) return Result::ok(); if (! targetFile.deleteFile()) return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName()); } if (! targetFile.getParentDirectory().createDirectory()) return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName()); if (zei->entry.isSymbolicLink) { String originalFilePath (in->readEntireStreamAsString() .replaceCharacter (L'/', File::getSeparatorChar())); if (! File::createSymbolicLink (targetFile, originalFilePath, true)) return Result::fail ("Failed to create symbolic link: " + originalFilePath); } else { FileOutputStream out (targetFile); if (out.failedToOpen()) return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName()); out << *in; } targetFile.setCreationTime (zei->entry.fileTime); targetFile.setLastModificationTime (zei->entry.fileTime); targetFile.setLastAccessTime (zei->entry.fileTime); return Result::ok(); }
0
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 0; RBinJavaAttrInfo *attr = NULL; attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (attr && sz >= offset) { attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR; attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset); if (attr->info.annotation_default_attr.default_value) { offset += attr->info.annotation_default_attr.default_value->size; } } r_bin_java_print_annotation_default_attr_summary (attr); return attr; }
0
C++
CWE-805
Buffer Access with Incorrect Length Value
The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.
https://cwe.mitre.org/data/definitions/805.html
vulnerable
void nodeRename(Proxy &node, const RegexMatchConfigs &rename_array, extra_settings &ext) { std::string &remark = node.Remark, original_remark = node.Remark, returned_remark, real_rule; for(const RegexMatchConfig &x : rename_array) { if(!x.Script.empty()) { script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { std::string script = x.Script; if(startsWith(script, "path:")) script = fileGet(script.substr(5), true); try { ctx.eval(script); auto rename = (std::function<std::string(const Proxy&)>) ctx.eval("rename"); returned_remark = rename(node); if(!returned_remark.empty()) remark = returned_remark; } catch (qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); continue; } if(applyMatcher(x.Match, real_rule, node) && real_rule.size()) remark = regReplace(remark, real_rule, x.Replace); } if(remark.empty()) remark = original_remark; return; }
0
C++
CWE-434
Unrestricted Upload of File with Dangerous Type
The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.
https://cwe.mitre.org/data/definitions/434.html
vulnerable
int GetS16BE (int nPos, bool *pbSuccess) { //*pbSuccess = true; if ( nPos < 0 || nPos + 1 >= m_nLen ) { *pbSuccess = false; return 0; } int nRes = m_sFile[nPos]; nRes = (nRes << 8) + m_sFile[ nPos + 1 ]; if ( nRes & 0x8000 ) nRes |= ~0xffff; return nRes; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
void resizeTable(HeaderTable& table, uint32_t newCapacity, uint32_t newMax) { table.setCapacity(newCapacity); // On resizing the table size (count of headers) remains the same or sizes // down; can not size up EXPECT_LE(table.size(), newMax); }
1
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
TfLiteStatus Relu6Prepare(TfLiteContext* context, TfLiteNode* node) { TFLITE_DCHECK(node->user_data != nullptr); Relu6OpData* data = static_cast<Relu6OpData*>(node->user_data); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TF_LITE_ENSURE(context, input != nullptr); if (input->type == kTfLiteInt8) { data->six_int8 = FloatToAsymmetricQuantizedInt8(6.0f, input->params.scale, input->params.zero_point); data->zero_int8 = input->params.zero_point; } else if (input->type == kTfLiteUInt8) { data->six_uint8 = FloatToAsymmetricQuantizedUInt8(6.0f, input->params.scale, input->params.zero_point); data->zero_uint8 = input->params.zero_point; } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
inline static bool jas_safe_size_mul3(size_t a, size_t b, size_t c, size_t *result) { size_t tmp; if (!jas_safe_size_mul(a, b, &tmp) || !jas_safe_size_mul(tmp, c, &tmp)) { return false; } if (result) { *result = tmp; } return true; }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) { ut64 sz = 2; if (evp && evp->value) { // evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur); // evp->value = r_bin_java_element_value_new (bin, offset+2); sz += r_bin_java_element_value_calc_size (evp->value); } return sz; }
1
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
safe
parse_memory(VALUE klass, VALUE data, VALUE encoding) { htmlParserCtxtPtr ctxt; if (NIL_P(data)) { rb_raise(rb_eArgError, "data cannot be nil"); } if (!(int)RSTRING_LEN(data)) { rb_raise(rb_eRuntimeError, "data cannot be empty"); } ctxt = htmlCreateMemoryParserCtxt(StringValuePtr(data), (int)RSTRING_LEN(data)); if (ctxt->sax) { xmlFree(ctxt->sax); ctxt->sax = NULL; } if (RTEST(encoding)) { xmlCharEncodingHandlerPtr enc = xmlFindCharEncodingHandler(StringValueCStr(encoding)); if (enc != NULL) { xmlSwitchToEncoding(ctxt, enc); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { rb_raise(rb_eRuntimeError, "Unsupported encoding %s", StringValueCStr(encoding)); } } } return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); }
0
C++
CWE-241
Improper Handling of Unexpected Data Type
The software does not handle or incorrectly handles when a particular element is not the expected type, e.g. it expects a digit (0-9) but is provided with a letter (A-Z).
https://cwe.mitre.org/data/definitions/241.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* start; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kStartTensor, &start)); const TfLiteTensor* limit; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kLimitTensor, &limit)); const TfLiteTensor* delta; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDeltaTensor, &delta)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, start, limit, delta, output)); } switch (output->type) { case kTfLiteInt32: { EvalImpl<int32_t>(start, delta, output); break; } case kTfLiteFloat32: { EvalImpl<float>(start, delta, output); break; } default: { context->ReportError(context, "Unsupported data type: %d", output->type); return kTfLiteError; } } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
static int sessionCookieDirective(MaState *state, cchar *key, cchar *value) { char *options, *option, *ovalue, *tok; if (!maTokenize(state, value, "%*", &options)) { return MPR_ERR_BAD_SYNTAX; } if (smatch(options, "disable")) { httpSetAuthSession(state->route->auth, 0); return 0; } else if (smatch(options, "enable")) { httpSetAuthSession(state->route->auth, 1); return 0; } for (option = maGetNextArg(options, &tok); option; option = maGetNextArg(tok, &tok)) { option = ssplit(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (!ovalue || *ovalue == '\0') continue; if (smatch(option, "visible")) { httpSetRouteSessionVisibility(state->route, scaselessmatch(ovalue, "visible")); } else if (smatch(option, "name")) { httpSetRouteCookie(state->route, ovalue); } else { mprLog("error appweb config", 0, "Unknown SessionCookie option %s", option); return MPR_ERR_BAD_SYNTAX; } } return 0; }
1
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
void Compute(OpKernelContext* context) override { // Only create one, if one does not exist already. Report status for all // other exceptions. If one already exists, it unrefs the new one. // An epsilon value of zero could cause performance issues and is therefore, // disallowed. const Tensor* epsilon_t; OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t)); float epsilon = epsilon_t->scalar<float>()(); OP_REQUIRES( context, epsilon > 0, errors::InvalidArgument("An epsilon value of zero is not allowed.")); const Tensor* num_streams_t; OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t)); int64_t num_streams = num_streams_t->scalar<int64>()(); OP_REQUIRES(context, num_streams >= 0, errors::InvalidArgument( "Num_streams input cannot be a negative integer")); auto result = new QuantileStreamResource(epsilon, max_elements_, num_streams); auto status = CreateResource(context, HandleFromInput(context, 0), result); if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES(context, false, status); } }
1
C++
CWE-681
Incorrect Conversion between Numeric Types
When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.
https://cwe.mitre.org/data/definitions/681.html
safe
TEST_F(QuantizedConv2DTest, Small32Bit) { const int stride = 1; TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D") .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Attr("out_type", DataTypeToEnum<qint32>::v()) .Attr("strides", {1, stride, stride, 1}) .Attr("padding", "SAME") .Finalize(node_def())); TF_ASSERT_OK(InitOp()); const int depth = 1; const int image_width = 4; const int image_height = 3; const int image_batch_count = 1; AddInputFromArray<quint8>( TensorShape({image_batch_count, image_height, image_width, depth}), {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120}); const int filter_size = 3; const int filter_count = 1; AddInputFromArray<quint8>( TensorShape({filter_size, filter_size, depth, filter_count}), {10, 40, 70, 20, 50, 80, 30, 60, 90}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); TF_ASSERT_OK(RunOpKernel()); const int expected_width = image_width; const int expected_height = image_height * filter_count; Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<qint32>( &expected, {10500, 15000, 18300, 9500, 23500, 31200, 35700, 17800, 18700, 23400, 26100, 12100}); test::ExpectTensorEqual<qint32>(expected, *GetOutput(0)); }
1
C++
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
static int crossOriginDirective(MaState *state, cchar *key, cchar *value) { HttpRoute *route; char *option, *ovalue, *tok; route = state->route; tok = sclone(value); while ((option = maGetNextArg(tok, &tok)) != 0) { option = ssplit(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (scaselessmatch(option, "origin")) { route->corsOrigin = sclone(ovalue); } else if (scaselessmatch(option, "credentials")) { route->corsCredentials = httpGetBoolToken(ovalue); } else if (scaselessmatch(option, "headers")) { route->corsHeaders = sclone(ovalue); } else if (scaselessmatch(option, "age")) { route->corsAge = atoi(ovalue); } else { mprLog("error appweb config", 0, "Unknown CrossOrigin option %s", option); return MPR_ERR_BAD_SYNTAX; } } #if KEEP if (smatch(route->corsOrigin, "*") && route->corsCredentials) { mprLog("error appweb config", 0, "CrossOrigin: Cannot use wildcard Origin if allowing credentials"); return MPR_ERR_BAD_STATE; } #endif /* Need the options method for pre-flight requests */ httpAddRouteMethods(route, "OPTIONS"); route->flags |= HTTP_ROUTE_CORS; return 0; }
1
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
def destroy Log.add_info(request, params.inspect) return unless request.post? @date = Date.parse(params[:date]) begin schedule = Schedule.find(params[:id]) rescue => evar Log.add_error(request, evar) @schedules = Schedule.get_user_day(@login_user, @date) render(:partial => 'timetable', :layout => false) return end unless schedule.check_user_auth(@login_user, 'w', true) Log.add_check(request, '[Schedule.check_user_auth]'+request.to_s) if @login_user.nil? check_login else flash[:notice] = 'ERROR:' + t('schedule.need_auth_to_edit_destroy') @schedules = Schedule.get_user_day(@login_user, @date) render(:partial => 'timetable', :layout => false) end return end schedule.destroy @schedules = Schedule.get_user_day(@login_user, @date) render(:partial => 'timetable', :layout => false) rescue => evar Log.add_error(request, evar) @schedules = Schedule.get_user_day(@login_user, @date) render(:partial => 'timetable', :layout => false) end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def remove(database, collection, selector, options = {}) with_node do |node| if safe? node.pipeline do node.remove(database, collection, selector, options) node.command("admin", { getlasterror: 1 }.merge(safety)) end else node.remove(database, collection, selector, options) end end end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def email_login raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email second_factor_token = params[:second_factor_token] second_factor_method = params[:second_factor_method].to_i token = params[:token] valid_token = !!EmailToken.valid_token_format?(token) user = EmailToken.confirmable(token)&.user if valid_token && user&.totp_enabled? if !second_factor_token.present? @second_factor_required = true @backup_codes_enabled = true if user&.backup_codes_enabled? return render layout: 'no_ember' elsif !user.authenticate_second_factor(second_factor_token, second_factor_method) RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 3, 1.minute).performed! @error = I18n.t('login.invalid_second_factor_code') return render layout: 'no_ember' end end if user = EmailToken.confirm(token) if login_not_approved_for?(user) @error = login_not_approved[:error] elsif payload = login_error_check(user) @error = payload[:error] else log_on_user(user) return redirect_to path("/") end else @error = I18n.t('email_login.invalid_token') end render layout: 'no_ember' end
0
Ruby
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
def legal?(str) !!str.match(/\A\h{24}\Z/i) end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def fence_device_form(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end @cur_resource = get_resource_by_id(params[:resource], get_cib_dom(session)) if @cur_resource.instance_of?(ClusterEntity::Primitive) and @cur_resource.stonith @resource_agents = getFenceAgents(session, @cur_resource.agentname) @existing_resource = true @fenceagent = @resource_agents[@cur_resource.type] erb :fenceagentform else "Can't find fence device" end end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
def create exists = true if params.has_key?(:inflated_object) params[:name] ||= params[:inflated_object].name # We can only get here if we're admin or the validator. Only # allow creating admin clients if we're already an admin. if @auth_user.admin params[:admin] ||= params[:inflated_object].admin else params[:admin] = false end end begin Chef::ApiClient.cdb_load(params[:name]) rescue Chef::Exceptions::CouchDBNotFound exists = false end raise Conflict, "Client already exists" if exists @client = Chef::ApiClient.new @client.name(params[:name]) @client.admin(params[:admin]) if params[:admin] @client.create_keys @client.cdb_save self.status = 201 headers['Location'] = absolute_url(:client, @client.name) display({ :uri => absolute_url(:client, @client.name), :private_key => @client.private_key }) end
0
Ruby
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
vulnerable
def check_owner return if (params[:id].nil? or params[:id].empty? or @login_user.nil?) address = Address.find(params[:id]) if !@login_user.admin?(User::AUTH_ADDRESSBOOK) and address.owner_id != @login_user.id Log.add_check(request, '[check_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') end end
0
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
vulnerable
def convert_autorequire(autorequire) autorequire = autorequire.first return autorequire if autorequire == "false" autorequire.inspect end
1
Ruby
CWE-88
Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
The software constructs a string for a command to executed by a separate component in another control sphere, but it does not properly delimit the intended arguments, options, or switches within that command string.
https://cwe.mitre.org/data/definitions/88.html
safe
it "drops the collection" do database.should_receive(:command).with(drop: :users) collection.drop end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "returns true" do session.should be_safe end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def getAllSettings(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) end ret = {} if cib_dom cib_dom.elements.each('/cib/configuration/crm_config//nvpair') { |e| ret[e.attributes['name']] = e.attributes['value'] } end return ret end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
def test_new_attribute_interpolation assert_equal("<a href='12'>bar</a>\n", render('%a(href="1#{1 + 1}") bar')) assert_equal("<a href='2: 2, 3: 3'>bar</a>\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3})) assert_equal(%Q{<a href='1\#{1 + 1}'>bar</a>\n}, render('%a(href="1\#{1 + 1}") bar')) end def test_truthy_new_attributes assert_equal("<a href='href'>bar</a>\n", render("%a(href) bar", :format => :xhtml)) assert_equal("<a bar='baz' href>bar</a>\n", render("%a(href bar='baz') bar", :format => :html5)) assert_equal("<a href>bar</a>\n", render("%a(href=true) bar")) assert_equal("<a>bar</a>\n", render("%a(href=false) bar")) end def test_new_attribute_parsing assert_equal("<a a2='b2'>bar</a>\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'})) assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #' assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #' assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a='foo"bar') bar})) assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="foo'bar") bar})) assert_equal("<a a:b='foo'>bar</a>\n", render("%a(a:b='foo') bar")) assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = 'foo' b = 'bar') bar")) assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'})) assert_equal("<a a='foo'>(b='bar')</a>\n", render("%a(a='foo')(b='bar')")) assert_equal("<a a='foo)bar'>baz</a>\n", render("%a(a='foo)bar') baz")) assert_equal("<a a='foo'>baz</a>\n", render("%a( a = 'foo' ) baz")) end def test_new_attribute_escaping assert_equal(%Q{<a a='foo " bar'>bar</a>\n}, render(%q{%a(a="foo \" bar") bar})) assert_equal(%Q{<a a='foo \\" bar'>bar</a>\n}, render(%q{%a(a="foo \\\\\" bar") bar}))
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def test_from_bad_octal test_cases = [ "00000006,44\000", # bogus character "00000006789\000", # non-octal digit "+0000001234\000", # positive sign "-0000001000\000", # negative sign "0x000123abc\000", # radix prefix ] test_cases.each do |val| header_s = @tar_header.to_s # overwrite the size field header_s[124, 12] = val io = TempIO.new header_s assert_raises ArgumentError do new_header = Gem::Package::TarHeader.from io end end end
1
Ruby
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
def set_certs(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end ssl_cert = (params['ssl_cert'] || '').strip ssl_key = (params['ssl_key'] || '').strip if ssl_cert.empty? and !ssl_key.empty? return [400, 'cannot save ssl certificate without ssl key'] end if !ssl_cert.empty? and ssl_key.empty? return [400, 'cannot save ssl key without ssl certificate'] end if !ssl_cert.empty? and !ssl_key.empty? ssl_errors = verify_cert_key_pair(ssl_cert, ssl_key) if ssl_errors and !ssl_errors.empty? return [400, ssl_errors.join] end begin write_file_lock(CRT_FILE, 0700, ssl_cert) write_file_lock(KEY_FILE, 0700, ssl_key) rescue => e # clean the files if we ended in the middle # the files will be regenerated on next pcsd start FileUtils.rm(CRT_FILE, {:force => true}) FileUtils.rm(KEY_FILE, {:force => true}) return [400, "cannot save ssl files: #{e}"] end end if params['cookie_secret'] cookie_secret = params['cookie_secret'].strip if !cookie_secret.empty? begin write_file_lock(COOKIE_FILE, 0700, cookie_secret) rescue => e return [400, "cannot save cookie secret: #{e}"] end end end return [200, 'success'] end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
it "returns the living socket" do cluster.socket_for(:write).should eq socket end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "sets the generation time" do expect(object_id.generation_time).to eq(time) end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def download(url, remote_headers = {}) headers = remote_headers. reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}") begin file = OpenURI.open_uri(process_uri(url.to_s), headers) rescue StandardError => e raise CarrierWave::DownloadError, "could not download file: #{e.message}" end CarrierWave::Downloader::RemoteFile.new(file) end
0
Ruby
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
it "initializes with the string's bytes" do expect(object_id.to_s).to eq(string) end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def diff(path, identifier_from, identifier_to=nil) hg_args = %w|rhdiff| if identifier_to hg_args << '-r' << hgrev(identifier_to) << '-r' << hgrev(identifier_from) else hg_args << '-c' << hgrev(identifier_from) end unless path.blank? p = scm_iconv(@path_encoding, 'UTF-8', path) hg_args << CGI.escape(hgtarget(p)) end diff = [] hg *hg_args do |io| io.each_line do |line| diff << line end end diff rescue HgCommandAborted nil # means not found end
0
Ruby
NVD-CWE-noinfo
null
null
null
vulnerable
def selected_ids return @selected_ids if @selected_ids ids = default_ids_hash #types NOT ignored - get ids that are selected hash_keys.each do |col| ids[col] = Array(taxonomy.send(col)) end #types that ARE ignored - get ALL ids for object Array(taxonomy.ignore_types).each do |taxonomy_type| ids["#{taxonomy_type.tableize.singularize}_ids"] = taxonomy_type.constantize.pluck(:id) end ids["#{opposite_taxonomy_type}_ids"] = Array(taxonomy.send("#{opposite_taxonomy_type}_ids")) @selected_ids = ids end
0
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def lookup_server(client) port = client.addr(false)[1] @servers.find do |server| server.to_io && server.to_io.addr[1] == port end end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
it "raises an exception" do expect { session.current_database }.to raise_exception end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def need_ring1_address?() out, errout, retval = run_cmd(PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL) if retval != 0 return false else udpu_transport = false rrp = false out.each { |line| # support both corosync-objctl and corosync-cmapctl format if /^\s*totem\.transport(\s+.*)?=\s*udpu$/.match(line) udpu_transport = true elsif /^\s*totem\.rrp_mode(\s+.*)?=\s*(passive|active)$/.match(line) rrp = true end } # on rhel6 ring1 address is required regardless of transport # it has to be added to cluster.conf in order to set up ring1 # in corosync by cman return ((ISRHEL6 and rrp) or (rrp and udpu_transport)) end end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
it "should find a user by first name and last name" do @cur_user.stub(:pref).and_return(:activity_user => 'Billy Elliot') controller.instance_variable_set(:@current_user, @cur_user) User.should_receive(:where).with(:first_name => 'Billy', :last_name => "Elliot").and_return([@user]) User.should_receive(:where).with(:first_name => 'Elliot', :last_name => "Billy").and_return([@user]) controller.send(:activity_user).should == 1 end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def login(username, password) session.cluster.login(name, username, password) end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
it "should collapse all comments and emails on Contact" do where_stub = double where_stub.should_receive(:update_all).with(:state => "Collapsed") Comment.should_receive(:where).and_return(where_stub) xhr :get, :timeline, :id => "1,2,3,4+", :state => "Collapsed" end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def get_resource_agents_avail(session) code, result = send_cluster_request_with_token( session, params[:cluster], 'get_avail_resource_agents' ) return {} if 200 != code begin ra = JSON.parse(result) if (ra["noresponse"] == true) or (ra["notauthorized"] == "true") or (ra["notoken"] == true) or (ra["pacemaker_not_running"] == true) return {} else return ra end rescue JSON::ParserError return {} end end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
def clean_text(text) text.gsub(/[\u0000-\u0008\u000b-\u000c\u000e-\u001F\u007f]/, ".".freeze) end
0
Ruby
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
it "yields a new session" do session.with(new_options) do |new_session| new_session.should_not eql session end end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def set_image Log.add_info(request, params.inspect) return unless request.post? created = false if params[:id].blank? @item = Item.new_info(0) @item.attributes = params.require(:item).permit(Item::PERMIT_BASE) @item.user_id = @login_user.id @item.title = t('paren.no_title') [:image0, :image1].each do |img| next if params[img].nil? or params[img][:file].size == 0 @item.save! created = true break end else @item = Item.find(params[:id]) end modified = false item_images = @item.images_without_content [:image0, :image1].each do |img| next if params[img].nil? or params[img][:file].nil? or params[img][:file].size == 0 image = Image.new image.item_id = @item.id image.file = params[img][:file] image.title = params[img][:title] image.memo = params[img][:memo] image.xorder = item_images.length image.save! modified = true item_images << image end if modified and !created @item.update_attribute(:updated_at, Time.now) end render(:partial => 'ajax_item_image', :layout => false) rescue => evar Log.add_error(request, evar) @image = Image.new @image.errors.add_to_base(evar.to_s[0, 256]) render(:partial => 'ajax_item_image', :layout => false) end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def update_header_menus_order Log.add_info(request, params.inspect) return unless request.post? header_menus = params[:header_menus_order] yaml = ApplicationHelper.get_config_yaml unless yaml[:general]['header_menus'].nil? yaml[:general]['header_menus'].sort! { |h_menu_a, h_menu_b| idx_a = header_menus.index h_menu_a[0] idx_a = 100 if idx_a.nil? idx_b = header_menus.index h_menu_b[0] idx_b = 101 if idx_b.nil? idx_a - idx_b } ApplicationHelper.save_config_yaml(yaml) end render(:text => '') end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def cat(path, identifier=nil) p = CGI.escape(scm_iconv(@path_encoding, 'UTF-8', path)) hg 'rhcat', "-r#{CGI.escape(hgrev(identifier))}", '--', hgtarget(p) do |io| io.binmode io.read end rescue HgCommandAborted nil # means not found end
1
Ruby
NVD-CWE-noinfo
null
null
null
safe
it "returns default error message for spoofed media type" do build_validator file = File.new(fixture_file("5k.png"), "rb") @dummy.avatar.assign(file) detector = mock("detector", :spoofed? => true) Paperclip::MediaTypeSpoofDetector.stubs(:using).returns(detector) @validator.validate(@dummy) assert_equal "has an extension that does not match its contents", @dummy.errors[:avatar].first end
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def exclude_from_group Log.add_info(request, params.inspect) return unless request.post? if params[:group_id].blank? render(:partial => 'ajax_groups', :layout => false) return end group_id = params[:group_id] begin @user = User.find(params[:id]) unless @user.nil? if @user.exclude_from(group_id) @user.save if @user.id == @login_user.id @login_user = @user end end end rescue => evar Log.add_error(request, evar) end render(:partial => 'ajax_groups', :layout => false) end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
it "yields a new session" do session.with(new_options) do |new_session| new_session.should_not eql session end end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "returns a session" do session.with(new_options).should be_a Moped::Session end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "has an empty list of secondaries" do cluster.secondaries.should be_empty end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "removes the socket" do cluster.should_receive(:remove).with(dead_server) cluster.socket_for :write end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def test_html5_data_attributes_without_hyphenation assert_equal("<div data-author_id='123' data-biz='baz' data-foo='bar'></div>\n", render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}", :hyphenate_data_attrs => false)) assert_equal("<div data-one_plus_one='2'></div>\n", render("%div{:data => {:one_plus_one => 1+1}}", :hyphenate_data_attrs => false)) assert_equal("<div data-foo='Here&#x0027;s a \"quoteful\" string.'></div>\n", render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def delete_statistics_group Log.add_info(request, params.inspect) return unless request.post? group_id = params[:group_id] SqlHelper.validate_token([group_id]) if group_id.blank? @group_ids = Research.get_statistics_groups render(:partial => 'ajax_statistics_groups', :layout => false) return end @group_ids = Research.delete_statistics_group(group_id) render(:partial => 'ajax_statistics_groups', :layout => false) end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def unfold(string) string.gsub(/[\r\n \t]+/m, ' ') end
1
Ruby
CWE-93
Improper Neutralization of CRLF Sequences ('CRLF Injection')
The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.
https://cwe.mitre.org/data/definitions/93.html
safe
def apply_auth(credentials) unless auth == credentials logouts = auth.keys - credentials.keys logouts.each do |database| logout database end credentials.each do |database, (username, password)| login(database, username, password) unless auth[database] == [username, password] end end self end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def test_update_invalid Medium.any_instance.stubs(:valid?).returns(false) put :update, {:id => @model, :medium => {:name => nil}}, set_session_user assert_template 'edit' end
1
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
safe
def remove_node(session, new_nodename, all=false) if all # we check for a quorum loss warning in remote_remove_nodes out, stderror, retval = run_cmd( session, PCS, "cluster", "node", "remove", new_nodename, "--force" ) else out, stderror, retval = run_cmd( session, PCS, "cluster", "localnode", "remove", new_nodename ) end $logger.info("Removing #{new_nodename} from pcs_settings.conf") corosync_nodes = get_corosync_nodes() pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text()) pcs_config.update_cluster($cluster_name, corosync_nodes) sync_config = Cfgsync::PcsdSettings.from_text(pcs_config.text()) # on version conflict just go on, config will be corrected eventually # by displaying the cluster in the web UI Cfgsync::save_sync_new_version( sync_config, corosync_nodes, $cluster_name, true ) return retval, out + stderror end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
def secondary? @secondary end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def known_addresses [].tap do |addresses| addresses.concat seeds addresses.concat dynamic_seeds addresses.concat servers.map { |server| server.address } end.uniq end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def command(command) session.context.command name, command end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f \"#{envelope_from.to_s.shellescape}\"" if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") self.class.call(settings[:location], arguments, mail) end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def self.add_statistics_group(group_id) yaml = Research.get_config_yaml yaml = Hash.new if yaml.nil? if yaml[:statistics].nil? yaml[:statistics] = Hash.new end groups = yaml[:statistics][:groups] if groups.nil? yaml[:statistics][:groups] = group_id ary = [group_id.to_s] else ary = groups.split('|') ary << group_id ary.compact! ary.delete('') yaml[:statistics][:groups] = ary.join('|') end Research.save_config_yaml(yaml) return ary end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def split_path(request) # Reparse the configuration if necessary. readconfig mount_name, path = request.key.split(File::Separator, 2) raise(ArgumentError, "Cannot find file: Invalid mount '#{mount_name}'") unless mount_name =~ %r{^[-\w]+$} return nil unless mount = find_mount(mount_name, request.environment) if mount.name == "modules" and mount_name != "modules" # yay backward-compatibility path = "#{mount_name}/#{path}" end if path == "" path = nil elsif path # Remove any double slashes that might have occurred path = path.gsub(/\/+/, "/") end return mount, path end
1
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
safe
it "queries the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) session.query(query) end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
it "drops the index" do indexes.create name: 1 indexes.drop(name: 1).should be_true end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def piped_category_name(category_id) return "-" unless category_id category = Category.find_by(id: category_id) return "#{category_id}" unless category categories = [category.name] while category.parent_category_id && category = category.parent_category categories << category.name end categories.reverse.join("|") end
0
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
it "raises a query failure exception for invalid queries" do lambda do users.find("age" => { "$in" => nil }).first end.should raise_exception(Moped::Errors::QueryFailure) end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def supplied_file_content_types @supplied_file_content_types ||= MIME::Types.type_for(@name).collect(&:content_type) end
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def build_gem_lines(conservative_versioning) @deps.map do |d| name = d.name.dump requirement = if conservative_versioning ", \"#{conservative_version(@definition.specs[d.name][0])}\"" else ", #{d.requirement.as_list.map(&:dump).join(", ")}" end if d.groups != Array(:default) group = d.groups.size == 1 ? ", :group => #{d.groups.first.inspect}" : ", :groups => #{d.groups.inspect}" end source = ", :source => \"#{d.source}\"" unless d.source.nil? git = ", :git => \"#{d.git}\"" unless d.git.nil? branch = ", :branch => \"#{d.branch}\"" unless d.branch.nil? %(gem #{name}#{requirement}#{group}#{source}#{git}#{branch}) end.join("\n")
0
Ruby
CWE-88
Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
The software constructs a string for a command to executed by a separate component in another control sphere, but it does not properly delimit the intended arguments, options, or switches within that command string.
https://cwe.mitre.org/data/definitions/88.html
vulnerable
def logout(database) cluster.auth.delete database.to_s end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
it "updates a hostgroup with a parent parameter, allows empty values" do child = FactoryGirl.create(:hostgroup, :parent => @base) as_admin do assert_equal "original", child.parameters["x"] end post :update, {"id" => child.id, "hostgroup" => {"name" => child.name, :group_parameters_attributes => {"0" => {:name => "x", :value => "", :_destroy => ""}, "1" => {:name => "y", :value => "overridden", :_destroy => ""}}}}, set_session_user assert_redirected_to hostgroups_url as_admin do child.reload assert_equal "overridden", child.parameters["y"] assert_equal "", child.parameters["x"] end end
1
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
safe
def create Log.add_info(request, params.inspect) return unless request.post? @address = Address.new(params.require(:address).permit(Address::PERMIT_BASE)) @address = AddressbookHelper.arrange_per_scope(@address, @login_user, params[:scope], params[:groups], params[:teams]) if @address.nil? flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') return end begin @address.save! rescue render(:controller => 'addressbook', :action => 'edit', :layout => (!request.xhr?)) return end flash[:notice] = t('msg.register_success') if request.xhr? render(:partial => 'common/flash_notice', :layout => false) else list render(:action => 'list') end end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def add_constraint_set_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end case params["c_type"] when "ord" retval, error = add_order_set_constraint( session, params["resources"].values, params["force"], !params['disable_autocorrect'] ) else return [400, "Unknown constraint type: #{params["c_type"]}"] end
0
Ruby
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
def api_endpoint(uri) host = uri.host begin res = @dns.getresource "_rubygems._tcp.#{host}", Resolv::DNS::Resource::IN::SRV rescue Resolv::ResolvError => e verbose "Getting SRV record failed: #{e}" uri else target = res.target.to_s.strip if URI("http://" + target).host.end_with?(".#{host}") return URI.parse "#{uri.scheme}://#{target}#{uri.path}" end uri end end
1
Ruby
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
safe
it 'should escape the content of removed `xmp` elements' do Sanitize.fragment('<xmp>hello! <script>alert(0)</script></xmp>') .must_equal 'hello! &lt;script&gt;alert(0)&lt;/script&gt;' end
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
it "handles Symbol keys with underscore and tailing '='" do cl = subject.build_command_line("true", :abc_def= => "ghi") expect(cl).to eq "true --abc-def=ghi" end
0
Ruby
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
def add_user( user, role ) check_write_access! unless role.kind_of? Role role = Role.get_by_title(role) end if role.global #only nonglobal roles may be set in a project raise SaveError, "tried to set global role '#{role_title}' for user '#{user}' in project '#{self.name}'" end unless user.kind_of? User user = User.get_by_login(user) end logger.debug "adding user: #{user.login}, #{role.title}" ProjectUserRoleRelationship.create( :project => self, :user => user, :role => role ) end
1
Ruby
CWE-275
Permission Issues
Weaknesses in this category are related to improper assignment or handling of permissions.
https://cwe.mitre.org/data/definitions/275.html
safe
it "sets the current database" do session.should_receive(:set_current_database).with(:admin) session.use :admin end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def package_index valid_http_methods :get required_parameters :project, :repository, :arch, :package # read access permission check if params[:package] == "_repository" prj = DbProject.get_by_name params[:project], use_source=false else pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false end pass_to_backend end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def test_extract_symlink_parent skip 'symlink not supported' if Gem.win_platform? package = Gem::Package.new @gem tgz_io = util_tar_gz do |tar| tar.mkdir 'lib', 0755 tar.add_symlink 'lib/link', '../..', 0644 tar.add_file 'lib/link/outside.txt', 0644 do |io| io.write 'hi' end end # Extract into a subdirectory of @destination; if this test fails it writes # a file outside destination_subdir, but we want the file to remain inside # @destination so it will be cleaned up. destination_subdir = File.join @destination, 'subdir' FileUtils.mkdir_p destination_subdir e = assert_raises Gem::Package::PathError do package.extract_tar_gz tgz_io, destination_subdir end assert_equal("installing into parent path lib/link/outside.txt of " + "#{destination_subdir} is not allowed", e.message) end
1
Ruby
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
def nodes_in_branch(branch, options={}) hg_args = ['rhlog', '--template={node}\n', "--rhbranch=#{CGI.escape(branch)}"] hg_args << "--from=#{CGI.escape(branch)}" hg_args << '--to=0' hg_args << "--limit=#{options[:limit]}" if options[:limit] hg(*hg_args) { |io| io.readlines.map { |e| e.chomp } } end
1
Ruby
NVD-CWE-noinfo
null
null
null
safe
it "does not modify the original session" do session.with(database: "other") do |safe| session.options[:database].should eq "moped_test" end end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def self.using(file, name) new(file, name) end
0
Ruby
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def self.get_for(user_id, date_s) SqlHelper.validate_token([user_id, date_s]) begin con = "(user_id=#{user_id.to_i}) and (date='#{date_s}')" return Timecard.where(con).first rescue end return nil end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
it "returns a new Query" do Moped::Query.should_receive(:new). with(collection, selector).and_return(query) collection.find(selector).should eq query end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
it "returns the count" do database.stub(command: { "n" => 4 }) query.count.should eq 4 end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def test_api_endpoint_ignores_trans_domain_values_that_end_with_original_in_path uri = URI.parse "http://example.com/foo" target = MiniTest::Mock.new target.expect :target, "evil.com/a.example.com" dns = MiniTest::Mock.new dns.expect :getresource, target, [String, Object] fetch = Gem::RemoteFetcher.new nil, dns assert_equal URI.parse("http://example.com/foo"), fetch.api_endpoint(uri) target.verify dns.verify end
1
Ruby
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
safe
def sanitize(params) return [] if params.nil? || params.empty? params.collect do |k, v| [sanitize_key(k), sanitize_value(v)] end end
0
Ruby
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
it "processes the block" do node.ensure_connected do node.command("admin", ping: 1) end.should eq("ok" => 1) end
1
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def initialize(data = nil, time = nil) if data @data = data elsif time @data = @@generator.generate(time.to_i) else @data = @@generator.next end end
0
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def entries(path=nil, identifier=nil, options={}) p1 = scm_iconv(@path_encoding, 'UTF-8', path) manifest = hg('rhmanifest', "-r#{CGI.escape(hgrev(identifier))}", '--', CGI.escape(without_leading_slash(p1.to_s))) do |io| output = io.read.force_encoding('UTF-8') begin parse_xml(output)['rhmanifest']['repository']['manifest'] rescue end end path_prefix = path.blank? ? '' : with_trailling_slash(path) entries = Entries.new as_ary(manifest['dir']).each do |e| n = scm_iconv('UTF-8', @path_encoding, CGI.unescape(e['name'])) p = "#{path_prefix}#{n}" entries << Entry.new(:name => n, :path => p, :kind => 'dir') end as_ary(manifest['file']).each do |e| n = scm_iconv('UTF-8', @path_encoding, CGI.unescape(e['name'])) p = "#{path_prefix}#{n}" lr = Revision.new(:revision => e['revision'], :scmid => e['node'], :identifier => e['node'], :time => Time.at(e['time'].to_i)) entries << Entry.new(:name => n, :path => p, :kind => 'file', :size => e['size'].to_i, :lastrev => lr) end entries rescue HgCommandAborted nil # means not found end
1
Ruby
NVD-CWE-noinfo
null
null
null
safe
def test_column_names_are_escaped conn = ActiveRecord::Base.connection classname = conn.class.name[/[^:]*$/] badchar = { 'SQLite3Adapter' => '"', 'MysqlAdapter' => '`', 'Mysql2Adapter' => '`', 'PostgreSQLAdapter' => '"', 'OracleAdapter' => '"', }.fetch(classname) { raise "need a bad char for #{classname}" } quoted = conn.quote_column_name "foo#{badchar}bar" assert_equal("#{badchar}foo#{badchar * 2}bar#{badchar}", quoted) end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def do_confirm Log.add_info(request, params.inspect) return unless request.post? @research = Research.find(params[:research_id]) @research.update_attribute(:status, Research::U_STATUS_COMMITTED) render(:action => 'show_receipt') rescue => evar Log.add_error(request, evar) render(:action => 'edit_page') end
1
Ruby
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def one_time_password otp_username = $redis.get "otp_#{params[:token]}" if otp_username && user = User.find_by_username(otp_username) log_on_user(user) $redis.del "otp_#{params[:token]}" return redirect_to path("/") else @error = I18n.t('user_api_key.invalid_token') end render layout: 'no_ember' end
0
Ruby
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
def filter_archived(list, user, archived: true) list = list.joins(<<~SQL) LEFT JOIN group_archived_messages gm ON gm.topic_id = topics.id LEFT JOIN user_archived_messages um ON um.user_id = #{user.id.to_i} AND um.topic_id = topics.id SQL list = if archived list.where("um.user_id IS NOT NULL OR gm.topic_id IS NOT NULL") else list.where("um.user_id IS NULL AND gm.topic_id IS NULL") end list end
0
Ruby
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
it "stores the selector" do query.selector.should eq selector end
0
Ruby
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
it "updates the first matching document" do users.insert(documents) users.find(scope: scope).update("$set" => { "updated" => true }) users.find(scope: scope, updated: true).count.should eq 1 end
1
Ruby
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def user_with_viewer_rights_should_fail_to_edit_a_domain setup_users get :edit, {:id => Domain.first.id} assert @response.status == '403 Forbidden' end
0
Ruby
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable