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 |
---|---|---|---|---|---|---|---|
it "should escape evil haxxor attemptes" do
Mail.defaults do
delivery_method :sendmail, :arguments => nil
end
mail = Mail.new do
from '"foo\";touch /tmp/PWNED;\""@blah.com'
to '[email protected]'
subject 'invalid RFC2822'
end
Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail',
"-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"",
'[email protected]',
mail)
mail.deliver!
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 "should reject non-whitelist extensions even if a valid extension is present" do
@request.stubs(:request_extensions).returns [{ "oid" => "peach",
"value" => "meh",
"critical" => false },
{ "oid" => "subjectAltName",
"value" => "DNS:foo",
"critical" => true }]
expect { @ca.sign(@name) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/request extensions that are not permitted/
)
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 next_client
throw :shutdown if @shutdown
begin
servers = @servers.reject &:closed?
clients = @clients.reject &:closed?
Moped.logger.debug "replica_set: selecting on connections"
readable, _, errors = Kernel.select(servers + clients, nil, clients, @timeout)
rescue IOError, Errno::EBADF, TypeError
# Looks like we hit a bad file descriptor or closed connection.
Moped.logger.debug "replica_set: io error, retrying"
retry
end
return unless readable || errors
errors.each do |client|
client.close
@clients.delete client
end
clients, servers = readable.partition { |s| s.class == TCPSocket }
servers.each do |server|
Moped.logger.debug "replica_set: accepting new client for #{server.port}"
@clients << server.accept
end
Moped.logger.debug "replica_set: closing dead clients"
closed, open = clients.partition &:eof?
closed.each { |client| @clients.delete client }
if client = open.shift
Moped.logger.debug "replica_set: finding server for client"
server = lookup_server(client)
Moped.logger.debug "replica_set: sending client #{client.inspect} to #{server.port}"
return server, client
else
nil
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 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 package '#{self.name}'"
end
unless user.kind_of? User
user = User.get_by_login(user.to_s)
end
PackageUserRoleRelationship.create(
:package => 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 |
def spec.full_name # so the spec is buildable
"malicious-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 send(force=false)
nodes_txt = @nodes.join(', ')
@configs.each { |cfg|
$logger.info(
"Sending config '#{cfg.class.name}' version #{cfg.version} #{cfg.hash}"\
+ " to nodes: #{nodes_txt}"
)
}
data = self.prepare_request_data(@configs, @cluster_name, force)
node_response = {}
threads = []
@nodes.each { |node|
threads << Thread.new {
code, out = send_request_with_token(
@session, node, 'set_configs', true, data, true, nil, 30,
@additional_tokens
)
if 200 == code
begin
node_response[node] = JSON.parse(out)
rescue JSON::ParserError
end
elsif 404 == code
node_response[node] = {'status' => 'not_supported'}
else
begin
response = JSON.parse(out)
if true == response['notauthorized'] or true == response['notoken']
node_response[node] = {'status' => 'notauthorized'}
end
rescue JSON::ParserError
end
end
if not node_response.key?(node)
node_response[node] = {'status' => 'error'}
end
# old pcsd returns this instead of 404 if pacemaker isn't running there
if node_response[node]['pacemaker_not_running']
node_response[node] = {'status' => 'not_supported'}
end
}
}
threads.each { |t| t.join }
node_response.each { |node, response|
$logger.info("Sending config response from #{node}: #{response}")
}
return node_response
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 self.get_default_for(user_id, xtype=nil)
SqlHelper.validate_token([user_id, xtype])
con = []
con << "(user_id=#{user_id.to_i})"
con << '(is_default=1)'
con << "(xtype='#{xtype}')" unless xtype.blank?
where = ''
unless con.nil? or con.empty?
where = 'where ' + con.join(' and ')
end
mail_accounts = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')
if mail_accounts.nil? or mail_accounts.empty?
return nil
else
return mail_accounts.first
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 send_nodes_request_with_token(session, nodes, request, post=false, data={}, remote=true, raw_data=nil)
out = ""
code = 0
$logger.info("SNRWT: " + request)
# If we're removing nodes, we don't send this to one of the nodes we're
# removing, unless we're removing all nodes
if request == "/remove_nodes"
new_nodes = nodes.dup
data.each {|k,v|
if new_nodes.include? v
new_nodes.delete v
end
}
if new_nodes.length > 0
nodes = new_nodes
end
end
for node in nodes
$logger.info "SNRWT Node: #{node} Request: #{request}"
code, out = send_request_with_token(
session, node, request, post, data, remote, raw_data
)
# try next node if:
# - current node does not support the request (old version of pcsd?) (404)
# - an exception or other error occurred (5xx)
# - we don't have a token for the node (401, notoken)
# - we didn't get a response form the node (e.g. an exception occurred)
# - pacemaker is not running on the node
# do not try next node if
# - node returned 400 - it means the request cannot be processed because of
# invalid arguments or another known issue, no node would be able to
# process the request (e.g. removing a non-existing resource)
# - node returned 403 - permission denied, no node should allow to process
# the request
log = "SNRWT Node #{node} Request #{request}"
if (404 == code) or (code >= 500 and code <= 599)
$logger.info("#{log}: HTTP code #{code}")
next
end
if (401 == code) or ('{"notoken":true}' == out)
$logger.info("#{log}: Bad or missing token")
next
end
if '{"pacemaker_not_running":true}' == out
$logger.info("#{log}: Pacemaker not running")
next
end
if '{"noresponse":true}' == out
$logger.info("#{log}: No response")
next
end
$logger.info("#{log}: HTTP code #{code}")
break
end
return code, out
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 reject a non-critical extension that isn't on the whitelist" do
@request.stubs(:request_extensions).returns [{ "oid" => "peach",
"value" => "meh",
"critical" => false }]
expect { @ca.sign(@name) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/request extensions that are not permitted/
)
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 test_update_invalid
Domain.any_instance.stubs(:valid?).returns(false)
put :update, {:id => @model.to_param, :domain => {:name => @model.name }}, 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 setup
@namespace = "theplaylist"
@store = Redis::Store.new :namespace => @namespace, :marshalling => false # TODO remove mashalling option
@client = @store.instance_variable_get(:@client)
@rabbit = "bunny"
@default_store = Redis::Store.new
@other_namespace = 'other'
@other_store = Redis::Store.new :namespace => @other_namespace
end | 0 | Ruby | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def replica_set_seeds
[ENV["MONGOHQ_REPL_1_URL"], ENV["MONGOHQ_REPL_2_URL"]]
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 auth_seeds
[ENV["MONGOHQ_SINGLE_URL"]]
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 get_mail_attachment
Log.add_info(request, params.inspect)
attached_id = params[:id].to_i
mail_attach = MailAttachment.find_by_id(attached_id)
if mail_attach.nil?
redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')
return
end
email = Email.find_by_id(mail_attach.email_id)
if email.nil? or email.user_id != @login_user.id
render(:text => '')
return
end
mail_attach_name = mail_attach.name
agent = request.env['HTTP_USER_AGENT']
unless agent.nil?
ie_ver = nil
agent.scan(/\sMSIE\s?(\d+)[.](\d+)/){|m|
ie_ver = m[0].to_i + (0.1 * m[1].to_i)
}
mail_attach_name = CGI::escape(mail_attach_name) unless ie_ver.nil?
end
filepath = mail_attach.get_path
if FileTest.exist?(filepath)
send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')
else
send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+mail_attach_name+'"')
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 extract_tar_gz io, destination_dir, pattern = "*" # :nodoc:
open_tar_gz io do |tar|
tar.each do |entry|
next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH
destination = install_location entry.full_name, destination_dir
FileUtils.rm_rf destination
mkdir_options = {}
mkdir_options[:mode] = entry.header.mode if entry.directory?
mkdir =
if entry.directory? then
destination
else
File.dirname destination
end
mkdir_p_safe mkdir, mkdir_options, destination_dir, entry.full_name
File.open destination, 'wb' do |out|
out.write entry.read
FileUtils.chmod entry.header.mode, destination
end if entry.file?
File.symlink(entry.header.linkname, destination) if entry.symlink?
verbose destination
end
end
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 skip_node?(node)
node.text? || node.cdata?
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 "returns the same hash" do
Moped::BSON::ObjectId.from_data(bytes).hash.should eq Moped::BSON::ObjectId.from_data(bytes).hash
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 forwarded_for
@env[FORWARDED_FOR]
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 create
File.open(resource[:path], "w", mode) { |f| f << expected_content }
end | 1 | 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 | safe |
it "inserts a document" do
users.find(scope: scope).upsert("$inc" => { counter: 1 })
users.find(scope: scope).one["counter"].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 format_text(text, wrap, indent=0)
result = []
work = text.dup
while work.length > wrap do
if work =~ /^(.{0,#{wrap}})[ \n]/ then
result << $1.rstrip
work.slice!(0, $&.length)
else
result << work.slice!(0, wrap)
end
end
result << work if work.length.nonzero?
result.join("\n").gsub(/^/, " " * indent)
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 "returns the number of matching document" do
users.insert(documents)
users.find(scope: scope).count.should eq 2
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 hg(*args, &block)
# as of hg 4.4.1, early parsing of bool options is not terminated at '--'
if args.any? { |s| s =~ HG_EARLY_BOOL_ARG }
raise HgCommandArgumentError, "malicious command argument detected"
end
if args.take_while { |s| s != '--' }.any? { |s| s =~ HG_EARLY_LIST_ARG }
raise HgCommandArgumentError, "malicious command argument detected"
end
repo_path = root_url || url
full_args = ['-R', repo_path, '--encoding', 'utf-8']
full_args << '--config' << "extensions.redminehelper=#{HG_HELPER_EXT}"
full_args << '--config' << 'diff.git=false'
full_args += args
ret = shellout(
self.class.sq_bin + ' ' + full_args.map { |e| shell_quote e.to_s }.join(' '),
&block
)
if $? && $?.exitstatus != 0
raise HgCommandAborted, "hg exited with non-zero status: #{$?.exitstatus}"
end
ret
end | 1 | Ruby | NVD-CWE-noinfo | null | null | null | safe |
def update_auth
Log.add_info(request, params.inspect)
return unless request.post?
auth = nil
if params[:check_auth_all] == '1'
auth = User::AUTH_ALL
else
auth_selected = params[:auth_selected]
unless auth_selected.nil? or auth_selected.empty?
auth = '|' + auth_selected.join('|') + '|'
end
if auth_selected.nil? or !auth_selected.include?(User::AUTH_USER)
user_admin_err = false
user_admins = User.where("auth like '%|#{User::AUTH_USER}|%' or auth='#{User::AUTH_ALL}'").to_a
if user_admins.nil? or user_admins.empty?
user_admin_err = true
elsif user_admins.length == 1
if user_admins.first.id.to_s == params[:id]
user_admin_err = true
end
end
if user_admin_err
render(:text => t('user.no_user_auth'))
return
end
end
end
begin
user = User.find(params[:id])
rescue => evar
Log.add_error(request, evar)
end
if user.nil?
render(:text => t('msg.already_deleted', :name => User.model_name.human))
else
user.update_attribute(:auth, auth)
if user.id == @login_user.id
@login_user = user
end
render(:text => '')
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 gate_process
HistoryHelper.keep_last(request)
@login_user = User.find(session[:login_user_id])
begin
if @login_user.nil? \
or @login_user.time_zone.nil? or @login_user.time_zone.empty?
unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty?
Time.zone = THETIS_USER_TIMEZONE_DEFAULT
end
else
Time.zone = @login_user.time_zone
end
rescue => evar
logger.fatal(evar.to_s)
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 filter_archived(list, user, archived: true)
# Executing an extra query instead of a sub-query because it is more
# efficient for the PG planner. Caution should be used when changing the
# query here as it can easily lead to an inefficient query.
group_ids = group_with_messages_ids(user)
list = list.joins(<<~SQL)
LEFT JOIN group_archived_messages gm
ON gm.topic_id = topics.id
#{group_ids.present? ? "AND gm.group_id IN (#{group_ids.join(",")})" : ""}
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 "adds the credentials to the auth cache" do
cluster.login("admin", "username", "password")
cluster.auth.should eq("admin" => ["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 |
def sanitize(html, options = {})
return unless html
return html if html.empty?
Loofah.fragment(html).tap do |fragment|
remove_xpaths(fragment, XPATHS_TO_REMOVE)
end.text(options)
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 add_holidays
Log.add_info(request, params.inspect)
return unless request.post?
holidays = params[:thetisBoxEdit]
unless holidays.nil?
holidays.split("\n").each do |holiday|
tokens = holiday.split(',')
date = DateTime.parse(tokens.shift.strip)
date += date.offset # 2011-01-01 09:00:00 +0900 (==> 2011-01-01 00:00:00 UTC)
name = tokens.join(',').strip
schedule = Schedule.new
schedule.xtype = Schedule::XTYPE_HOLIDAY
schedule.scope = Schedule::SCOPE_ALL
schedule.title = name
schedule.start = date
schedule.end = date
schedule.allday = true
schedule.save!
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 edit_page
# Saved contents of Login User
begin
@research = Research.where("user_id=#{@login_user.id}").first
rescue
end
if @research.nil?
@research = Research.new
else
# Already accepted?
if [email protected]? and @research.status != 0
render(:action => 'show_receipt')
return
end
end
# Specifying page
@page = '01'
unless params[:page].blank?
@page = params[:page]
SqlHelper.validate_token([@page])
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 |
it "fails when user is suspended" do
user.update!(
suspended_till: 2.days.from_now,
suspended_at: Time.zone.now
)
get "/session/email-login/#{email_token.token}"
expect(response.status).to eq(200)
expect(CGI.unescapeHTML(response.body)).to include(I18n.t("login.suspended",
date: I18n.l(user.suspended_till, format: :date_only)
))
end | 0 | Ruby | NVD-CWE-noinfo | null | null | null | vulnerable |
def self.count_ack_users(item_id)
SqlHelper.validate_token([item_id])
return Comment.where("(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").count
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 initialize(image_path, colors=16, depth=8)
output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-`
@lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?)
end | 0 | Ruby | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
it "syncs each seed node" do
server = Moped::Server.allocate
Moped::Server.should_receive(:new).with("127.0.0.1:27017").and_return(server)
cluster.should_receive(:sync_server).with(server).and_return([])
cluster.sync
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.password_reset_via_token(token, password)
# check token
user = by_reset_token(token)
return if !user
# reset password
user.update!(password: password)
# delete token
Token.find_by(action: 'PasswordReset', name: token).destroy
user
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 |
def kill
session.execute kill_cursor_op
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 supplied_content_type
@content_type
end | 1 | 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 | safe |
it "does not automatically approve users if must_approve_users is true" do
SiteSetting.must_approve_users = true
invite = Fabricate(:invite, email: '[email protected]')
user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test')
expect(user.approved).to eq(false)
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 "should reject a wildcard subject" do
@request.content.stubs(:subject).
returns(OpenSSL::X509::Name.new([["CN", "*.local"]]))
expect { @ca.check_internal_signing_policies('*.local', @request, false) }.to raise_error(
Puppet::SSL::CertificateAuthority::CertificateSigningError,
/subject contains a wildcard/
)
end | 1 | 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 | safe |
def generation_time
::Time.at(to_bson.unpack("N")[0]).utc
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 "should should be a subclass of Base" do
Puppet::FileServing::Content.superclass.should equal(Puppet::FileServing::Base)
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 remove_application(user_ids)
return if user_ids.nil? or user_ids.empty?
SqlHelper.validate_token([user_ids])
con = ["(xtype='#{Comment::XTYPE_APPLY}')"]
con << "(item_id=#{self.item_id})"
user_con_a = []
user_ids.each do |user_id|
user_con_a << "(user_id=#{user_id})"
end
con << '(' + user_con_a.join(' or ') + ')'
Comment.destroy_all(con.join(' and '))
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 verify_active_session
if !request.post? && params[:status].blank? && User.unscoped.exists?(session[:user].presence)
warning _("You have already logged in")
redirect_back_or_to hosts_path
return
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 request(args = {})
{ :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v|
args[k] ||= v
end
['test', :find, args[:key], args]
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 _extend_marshalling(options)
@marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory
extend Marshalling if @marshalling
end | 0 | Ruby | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
it "raises with a valid SSRF attack" do
@api_key = "-attacker.net/test/?"
@gibbon.api_key = @api_key
expect {@gibbon.try.retrieve}.to raise_error(Gibbon::MailChimpError, /SSRF attempt/)
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 |
def resource_start(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
stdout, stderr, retval = run_cmd(
session, PCS, "resource", "enable", params[:resource]
)
if retval == 0
return JSON.generate({"success" => "true"})
else
return JSON.generate({"error" => "true", "stdout" => stdout, "stderror" => stderr})
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 get_group_users
Log.add_info(request, params.inspect)
begin
@folder = Folder.find(params[:id])
rescue => evar
Log.add_error(request, evar)
end
@group_id = nil
if !params[:thetisBoxSelKeeper].nil?
@group_id = params[:thetisBoxSelKeeper].split(':').last
elsif !params[:group_id].nil? and !params[:group_id].empty?
@group_id = params[:group_id]
end
@users = Group.get_users @group_id
render(:partial => 'ajax_select_users', :layout => false)
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 post_label
Log.add_info(request, params.inspect)
return unless request.post?
if params[:txaPostLabel].empty? or params[:post_to].empty?
render(:text => '')
return
end
params[:post_to].each do |user_id|
user = User.find(user_id)
toy = Toy.new
toy.xtype = Toy::XTYPE_POSTLABEL
toy.message = params[:txaPostLabel]
toy.user_id = user.id
toy.posted_by = @login_user.id
toy.x, toy.y = DesktopsHelper.find_empty_block(user)
toy.save!
end
flash[:notice] = t('msg.post_success')
render(:partial => 'common/flash_notice', :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 'returns correct link' do
data = {
cutoff: false,
user: 'Julia Nguyen',
comment: 'Hello',
typename: 'typename',
type: 'type_comment_moment',
typeid: 1,
commentable_id: 1
}
expect(comment_link(uniqueid, data)).to eq('<a id="uniqueid" href="/moments/1">Julia Nguyen commented "Hello" on typename</a>')
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 "creates a new cursor" do
cursor = mock(Moped::Cursor, next: nil)
Moped::Cursor.should_receive(:new).
with(session, query.operation).and_return(cursor)
query.each
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 'logs in correctly' do
post "/session/email-login/#{email_token.token}", params: {
second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,
second_factor_method: UserSecondFactor.methods[:totp]
}
expect(response).to redirect_to("/")
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 replica_set_database
ENV["MONGOHQ_REPL_NAME"]
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 __bson_load__(io)
from_data(io.read(12))
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 "creates an index with the provided name" do
indexes.create(key, name: "custom_index_name")
indexes[key]["name"].should eq "custom_index_name"
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 get_current_node_name()
stdout, stderror, retval = run_cmd(
PCSAuth.getSuperuserSession, CRM_NODE, "-n"
)
if retval == 0 and stdout.length > 0
return stdout[0].chomp()
end
return ""
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 self.destroy(host)
client = host.gsub("..",".")
dir = File.join(Puppet[:reportdir], client)
if File.exists?(dir)
Dir.entries(dir).each do |file|
next if ['.','..'].include?(file)
file = File.join(dir, file)
File.unlink(file) if File.file?(file)
end
Dir.rmdir(dir)
end
end | 0 | 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 | vulnerable |
def login(username, password)
session.cluster.login(name, username, password)
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 add_statistics_group
Log.add_info(request, params.inspect)
current_id = params[:current_id]
if !params[:thetisBoxSelKeeper].nil?
group_id = params[:thetisBoxSelKeeper].split(':').last
end
if group_id.nil? or group_id.empty?
@group_ids = Research.get_statistics_groups
render(:partial => 'ajax_statistics_groups', :layout => false)
return
end
unless current_id.nil? or current_id.empty?
Research.delete_statistics_group current_id
end
@group_ids = Research.add_statistics_group group_id
render(:partial => 'ajax_statistics_groups', :layout => false)
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 socket_for(mode)
if options[:retain_socket]
@socket ||= cluster.socket_for(mode)
else
cluster.socket_for(mode)
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 |
it "logs out" do
lambda do
session.command dbStats: 1
end.should_not raise_exception
session.logout
lambda do
session.command dbStats: 1
end.should raise_exception(Moped::Errors::OperationFailure)
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 test_update_valid
Subnet.any_instance.stubs(:valid?).returns(true)
put :update, {:id => Subnet.first, :subnet => {:network => '192.168.100.10'}}, set_session_user
assert_equal '192.168.100.10', Subnet.first.network
assert_redirected_to subnets_url
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 initialize(servers)
@timeout = 0.1
@servers = servers
@clients = []
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 check_action_permission!(skip_source = nil)
super(skip_source)
# only perform the following check, if we are called from
# BsRequest.permission_check_change_state! (that is, if
# skip_source is set to true). Always executing this check
# would be a regression, because this code is also executed
# if a new request is created (which could fail if User.current
# cannot modify the source_package).
return unless skip_source
target_project = Project.get_by_name(self.target_project)
return unless target_project && target_project.is_a?(Project)
target_package = target_project.packages.find_by_name(self.target_package)
initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')
return if target_package || !initialize_devel_package
source_package = Package.get_by_project_and_name(source_project, self.source_package)
return if !source_package || User.current.can_modify?(source_package)
msg = 'No permission to initialize the source package as a devel package'
raise PostRequestNoPermission, msg
end | 0 | Ruby | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
def get_local_node_id()
if ISRHEL6
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, "cluster.cman"
)
if retval != 0
return ""
end
match = /cluster\.nodename=(.*)/.match(out.join("\n"))
if not match
return ""
end
local_node_name = match[1]
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession,
CMAN_TOOL, "nodes", "-F", "id", "-n", local_node_name
)
if retval != 0
return ""
end
return out[0].strip()
end
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession,
COROSYNC_CMAPCTL, "-g", "runtime.votequorum.this_node_id"
)
if retval != 0
return ""
else
return out[0].split(/ = /)[1].strip()
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 query(database, collection, selector, options = {})
operation = Protocol::Query.new(database, collection, selector, options)
process operation do |reply|
if reply.flags.include? :query_failure
raise Errors::QueryFailure.new(operation, reply.documents.first)
end
reply
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 |
it "returns the result of the block" do
session.with(new_options) { false }.should eq false
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 verify_signature(string, signature)
if signature.nil?
fail InvalidSignature, "missing \"signature\" param"
elsif signature != generate_signature(string)
fail InvalidSignature, "provided signature does not match the calculated signature"
end
end | 0 | Ruby | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.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 | 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 set_auth_groups
Log.add_info(request, params.inspect)
return unless request.post?
@folder = Folder.find(params[:id])
if Folder.check_user_auth(@folder.id, @login_user, 'w', true)
read_groups = []
write_groups = []
groups_auth = params[:groups_auth]
unless groups_auth.nil?
groups_auth.each do |auth_param|
user_id = auth_param.split(':').first
auths = auth_param.split(':').last.split('+')
if auths.include?('r')
read_groups << user_id
end
if auths.include?('w')
write_groups << user_id
end
end
end
@folder.set_read_groups(read_groups)
@folder.set_write_groups(write_groups)
@folder.save
flash[:notice] = t('msg.register_success')
else
flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
end
@groups = Group.where(nil).to_a
render(:partial => 'ajax_auth_groups', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_auth_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 check_action_permission!(skip_source = nil)
super(skip_source)
# only perform the following check, if we are called from
# BsRequest.permission_check_change_state! (that is, if
# skip_source is set to true). Always executing this check
# would be a regression, because this code is also executed
# if a new request is created (which could fail if User.current
# cannot modify the source_package).
return unless skip_source
target_project = Project.get_by_name(self.target_project)
return unless target_project && target_project.is_a?(Project)
target_package = target_project.packages.find_by_name(self.target_package)
initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')
return if target_package || !initialize_devel_package
opts = { follow_project_links: false }
source_package = Package.get_by_project_and_name!(source_project,
self.source_package,
opts)
return if User.current.can_modify?(source_package)
msg = 'No permission to initialize the source package as a devel package'
raise PostRequestNoPermission, msg
end | 1 | Ruby | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
def activity_user
user = current_user.pref[:activity_user]
if user && user != "all_users"
user = if user =~ /@/ # email
User.where(:email => user).first
else # first_name middle_name last_name any_name
name_query = if user.include?(" ")
user.name_permutations.map{ |first, last|
User.where(:first_name => first, :last_name => last)
}.map(&:to_a).flatten.first
else
[User.where(:first_name => user), User.where(:last_name => user)].map(&:to_a).flatten.first
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 default_ids_hash(populate_values = false)
ids = HashWithIndifferentAccess.new
hash_keys.each do |col|
ids[col] = populate_values ? Array(self.send(col)).uniq : []
end
ids
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 __bson_dump__(io, key)
io << Types::OBJECT_ID
io << key
io << NULL_BYTE
io << data
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 "drops the index that matches the key" do
indexes[name: 1].should be_nil
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 "insert multiple documents" do
documents = [
{ "_id" => Moped::BSON::ObjectId.new, "scope" => scope },
{ "_id" => Moped::BSON::ObjectId.new, "scope" => scope }
]
session[:users].insert(documents)
session[:users].find(scope: scope).entries.should eq documents
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 "should redeem the invite if invited by non staff but not approve" do
SiteSetting.must_approve_users = true
inviter = invite.invited_by
user = invite_redeemer.redeem
expect(user.name).to eq(name)
expect(user.username).to eq(username)
expect(user.invited_by).to eq(inviter)
expect(inviter.notifications.count).to eq(1)
expect(user.approved).to eq(false)
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 "yields a session" do
session.with(new_options) do |new_session|
new_session.should be_a Moped::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 list
Log.add_info(request, params.inspect)
con = []
@group_id = nil
if !params[:thetisBoxSelKeeper].nil?
@group_id = params[:thetisBoxSelKeeper].split(':').last
elsif !params[:group_id].blank?
@group_id = params[:group_id]
end
SqlHelper.validate_token([@group_id])
unless @group_id.nil?
if @group_id == '0'
con << "((groups like '%|0|%') or (groups is null))"
else
con << SqlHelper.get_sql_like([:groups], "|#{@group_id}|")
end
end
where = ''
unless con.empty?
where = ' where ' + con.join(' and ')
end
order_by = nil
@sort_col = params[:sort_col]
@sort_type = params[:sort_type]
if @sort_col.blank? or @sort_type.blank?
@sort_col = 'id'
@sort_type = 'ASC'
end
SqlHelper.validate_token([@sort_col, @sort_type])
order_by = ' order by ' + @sort_col + ' ' + @sort_type
sql = 'select distinct Equipment.* from equipment Equipment'
sql << where + order_by
@equipment_pages, @equipment, @total_num = paginate_by_sql(Equipment, sql, 20)
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 "is not possible to take account over with the #{strategy} forgery protection strategy" do
user = create(:user, email: '[email protected]', password: 'password')
post '/login', params: "spree_user[email][email protected]&spree_user[password]=password"
begin
put '/users/123456', params: 'user[email][email protected]'
rescue
# testing that the account is not compromised regardless of any raised
# exception
end
expect(user.reload.email).to eq('[email protected]')
end | 1 | Ruby | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def remove_application(user_ids)
return if user_ids.nil? or user_ids.empty?
SqlHelper.validate_token([user_ids])
con = ["(xtype='#{Comment::XTYPE_APPLY}')"]
con << "(item_id=#{self.item_id})"
user_con_a = []
user_ids.each do |user_id|
user_con_a << "(user_id=#{user_id})"
end
con << '(' + user_con_a.join(' or ') + ')'
Comment.destroy_all(con.join(' and '))
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 ===(other)
return to_str === other.to_str if other.respond_to?(:to_str)
super
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 send_password
Log.add_info(request, params.inspect)
begin
users = User.where("email='#{params[:thetisBoxEdit]}'").to_a
rescue => evar
end
if users.nil? or users.empty?
Log.add_error(request, evar)
flash[:notice] = 'ERROR:' + t('email.address_not_found')
else
user_passwords_h = {}
users.each do |user|
newpass = UsersHelper.generate_password
user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))
user_passwords_h[user] = newpass
end
NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
flash[:notice] = t('email.sent')
end
render(:controller => 'login', :action => 'index')
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 update_order
Log.add_info(request, params.inspect)
mail_account_id = params[:mail_account_id]
order_ary = params[:mail_filters_order]
@mail_account = MailAccount.find_by_id(mail_account_id)
if @mail_account.user_id != @login_user.id
render(:text => 'ERROR:' + t('msg.need_to_be_owner'))
return
end
filters = MailFilter.get_for(mail_account_id)
# filters must be ordered by xorder ASC.
filters.sort! { |filter_a, filter_b|
id_a = filter_a.id.to_s
id_b = filter_b.id.to_s
idx_a = order_ary.index(id_a)
idx_b = order_ary.index(id_b)
if idx_a.nil? or idx_b.nil?
idx_a = filters.index(id_a)
idx_b = filters.index(id_b)
end
idx_a - idx_b
}
idx = 1
filters.each do |filter|
next if filter.mail_account_id != mail_account_id.to_i
filter.update_attribute(:xorder, idx)
idx += 1
end
render(:text => '')
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 send_cluster_request_with_token(session, cluster_name, request, post=false, data={}, remote=true, raw_data=nil)
$logger.info("SCRWT: " + request)
nodes = get_cluster_nodes(cluster_name)
return send_nodes_request_with_token(
session, nodes, request, post, data, remote, raw_data
)
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 scope_allowed_attributes(attributes)
Rails::Html::WhiteListSanitizer.allowed_attributes = attributes
yield Rails::Html::WhiteListSanitizer.new
ensure
Rails::Html::WhiteListSanitizer.allowed_attributes = nil
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 origins(*args, &blk)
@origins = args.flatten.collect do |n|
case n
when Regexp,
/^https?:\/\//,
'file://' then n
when '*' then @public_resources = true; n
else Regexp.compile("^[a-z][a-z0-9.+-]*:\\\/\\\/#{Regexp.quote(n)}")
end
end.flatten | 0 | Ruby | NVD-CWE-noinfo | null | null | null | vulnerable |
it "delegates to #with" do
session.should_receive(:with).with(new_options).and_return(new_session)
session.new(new_options)
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 redeem the invite if invited by non staff and approve if email in auto_approve_email_domains setting" do
SiteSetting.must_approve_users = true
SiteSetting.auto_approve_email_domains = "example.com"
user = invite_redeemer.redeem
expect(user.name).to eq(name)
expect(user.username).to eq(username)
expect(user.approved).to eq(true)
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 |
def create_field(name, value, charset)
value = unfold(value) if value.is_a?(String) || value.is_a?(Mail::Multibyte::Chars)
begin
new_field(name, value, charset)
rescue Mail::Field::ParseError => e
field = Mail::UnstructuredField.new(name, value)
field.errors << [name, value, e]
field
end
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 query
Log.add_info(request, '') # Not to show passwords.
unless @login_user.admin?(User::AUTH_ZEPTAIR)
render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
return
end
target_user = nil
user_id = params[:user_id]
zeptair_id = params[:zeptair_id]
group_id = params[:group_id]
SqlHelper.validate_token([user_id, zeptair_id, group_id])
unless user_id.blank?
target_user = User.find(user_id)
end
unless zeptair_id.blank?
target_user = User.where("zeptair_id=#{zeptair_id}").first
end
if target_user.nil?
if group_id.blank?
sql = 'select distinct Item.* from items Item, attachments Attachment'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << ' order by Item.user_id ASC'
else
group_ids = [group_id]
if params[:recursive] == 'true'
group_ids += Group.get_childs(group_id, true, false)
end
groups_con = []
group_ids.each do |grp_id|
groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{grp_id}|")
end
sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
sql << ' order by Item.user_id ASC'
end
@post_items = Item.find_by_sql(sql)
else
@post_item = ZeptairPostHelper.get_item_for(target_user)
end
rescue => evar
Log.add_error(request, evar)
render(:text => 'ERROR:' + t('msg.system_error'))
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 logout
session.cluster.logout(name)
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 connect(host, port, timeout)
@sock = TCPSocket.connect host, port, timeout
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 "should expand all comments and emails on a specific contact" do
comment = double(Comment)
Comment.should_receive(:find).with("1").and_return(comment)
comment.should_receive(:update_attribute).with(:state, 'Expanded')
xhr :get, :timeline, :type => "comment", :id => "1", :state => "Expanded"
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_node_status(session, cib_dom)
node_status = {
:cluster_name => $cluster_name,
:groups => [],
:constraints => {
# :rsc_location => [],
# :rcs_colocation => [],
# :rcs_order => []
},
:cluster_settings => {},
:need_ring1_address => need_ring1_address?,
:is_cman_with_udpu_transport => is_cman_with_udpu_transport?,
:acls => get_acls(session, cib_dom),
:username => session[:username],
:fence_levels => get_fence_levels(session, cib_dom),
:node_attr => node_attrs_to_v2(get_node_attributes(session, cib_dom)),
:nodes_utilization => get_nodes_utilization(cib_dom),
:known_nodes => []
}
nodes = get_nodes_status()
known_nodes = []
nodes.each { |_, node_list|
known_nodes.concat node_list
}
node_status[:known_nodes] = known_nodes.uniq
nodes.each do |k,v|
node_status[k.to_sym] = v
end
if cib_dom
node_status[:groups] = get_resource_groups(cib_dom)
node_status[:constraints] = getAllConstraints(cib_dom.elements['/cib/configuration/constraints'])
end
node_status[:cluster_settings] = getAllSettings(session, cib_dom)
return node_status
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_store_axml
User.current = users( :Iggy )
original = @project.to_axml
#project is given as axml
axml = Xmlhash.parse(
"<project name='home:Iggy'>
<title>Iggy's Home Project</title>
<description>dummy</description>
<debuginfo>
<disable repository='10.0' arch='i586'/>
</debuginfo>
<url></url>
<disable/>
</project>"
)
@project.update_from_xml(axml)
assert_equal 0, @project.type_flags('build').size
assert_equal 1, @project.type_flags('debuginfo').size
@project.update_from_xml(Xmlhash.parse(original))
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 |
def hash
[ip_address, port].hash
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 check_owner
return if params[:id].nil? or params[:id].empty? or @login_user.nil?
email = Email.find(params[:id])
if !@login_user.admin?(User::AUTH_MAIL) and email.user_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 initialize
# Generate and cache 3 bytes of identifying information from the current
# machine.
@machine_id = Digest::MD5.digest(Socket.gethostname).unpack("N")[0]
@mutex = Mutex.new
@counter = 0
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 "has an empty list of secondaries" do
cluster.secondaries.should be_empty
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 |
Subsets and Splits