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 |
---|---|---|---|---|---|---|---|
SPL_METHOD(DirectoryIterator, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index = 0;
if (intern->u.dir.dirp) {
php_stream_rewinddir(intern->u.dir.dirp);
}
spl_filesystem_dir_read(intern TSRMLS_CC);
} | 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 |
static inline void find_entity_for_char(
unsigned int k,
enum entity_charset charset,
const entity_stage1_row *table,
const unsigned char **entity,
size_t *entity_len,
unsigned char *old,
size_t oldlen,
size_t *cursor)
{
unsigned stage1_idx = ENT_STAGE1_INDEX(k);
const entity_stage3_row *c;
if (stage1_idx > 0x1D) {
*entity = NULL;
*entity_len = 0;
return;
}
c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
if (!c->ambiguous) {
*entity = (const unsigned char *)c->data.ent.entity;
*entity_len = c->data.ent.entity_len;
} else {
/* peek at next char */
size_t cursor_before = *cursor;
int status = SUCCESS;
unsigned next_char;
if (!(*cursor < oldlen))
goto no_suitable_2nd;
next_char = get_next_char(charset, old, oldlen, cursor, &status);
if (status == FAILURE)
goto no_suitable_2nd;
{
const entity_multicodepoint_row *s, *e;
s = &c->data.multicodepoint_table[1];
e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
/* we could do a binary search but it's not worth it since we have
* at most two entries... */
for ( ; s <= e; s++) {
if (s->normal_entry.second_cp == next_char) {
*entity = s->normal_entry.entity;
*entity_len = s->normal_entry.entity_len;
return;
}
}
}
no_suitable_2nd:
*cursor = cursor_before;
*entity = (const unsigned char *)
c->data.multicodepoint_table[0].leading_entry.default_entity;
*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
}
} | 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 |
static int inet_sk_reselect_saddr(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
__be32 old_saddr = inet->inet_saddr;
__be32 daddr = inet->inet_daddr;
struct flowi4 fl4;
struct rtable *rt;
__be32 new_saddr;
struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
/* Query new route. */
rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if, sk->sk_protocol,
inet->inet_sport, inet->inet_dport, sk, false);
if (IS_ERR(rt))
return PTR_ERR(rt);
sk_setup_caps(sk, &rt->dst);
new_saddr = rt->rt_src;
if (new_saddr == old_saddr)
return 0;
if (sysctl_ip_dynaddr > 1) {
printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n",
__func__, &old_saddr, &new_saddr);
}
inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
/*
* XXX The only one ugly spot where we need to
* XXX really change the sockets identity after
* XXX it has entered the hashes. -DaveM
*
* Besides that, it does not check for connection
* uniqueness. Wait for troubles.
*/
__sk_prot_rehash(sk);
return 0;
} | 1 | C | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | safe |
static int bson_string_is_db_ref( const unsigned char *string, const int length ) {
int result = 0;
if( length >= 4 ) {
if( string[1] == 'r' && string[2] == 'e' && string[3] == 'f' )
result = 1;
}
else if( length >= 3 ) {
if( string[1] == 'i' && string[2] == 'd' )
result = 1;
else if( string[1] == 'd' && string[2] == 'b' )
result = 1;
}
return result;
} | 0 | 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 | vulnerable |
win_goto(win_T *wp)
{
#ifdef FEAT_CONCEAL
win_T *owp = curwin;
#endif
#ifdef FEAT_PROP_POPUP
if (ERROR_IF_ANY_POPUP_WINDOW)
return;
if (popup_is_popup(wp))
{
emsg(_(e_not_allowed_to_enter_popup_window));
return;
}
#endif
if (text_or_buf_locked())
{
beep_flush();
return;
}
if (wp->w_buffer != curbuf)
reset_VIsual_and_resel();
else if (VIsual_active)
wp->w_cursor = curwin->w_cursor;
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_enter(wp, TRUE);
#ifdef FEAT_CONCEAL
// Conceal cursor line in previous window, unconceal in current window.
if (win_valid(owp) && owp->w_p_cole > 0 && !msg_scrolled)
redrawWinline(owp, owp->w_cursor.lnum);
if (curwin->w_p_cole > 0 && !msg_scrolled)
need_cursor_line_redraw = TRUE;
#endif
} | 1 | C | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
static bool glfs_check_config(const char *cfgstring, char **reason)
{
char *path;
glfs_t *fs = NULL;
glfs_fd_t *gfd = NULL;
gluster_server *hosts = NULL; /* gluster server defination */
bool result = true;
path = strchr(cfgstring, '/');
if (!path) {
if (asprintf(reason, "No path found") == -1)
*reason = NULL;
result = false;
goto done;
}
path += 1; /* get past '/' */
fs = tcmu_create_glfs_object(path, &hosts);
if (!fs) {
tcmu_err("tcmu_create_glfs_object failed\n");
goto done;
}
gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS);
if (!gfd) {
if (asprintf(reason, "glfs_open failed: %m") == -1)
*reason = NULL;
result = false;
goto unref;
}
if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) {
if (asprintf(reason, "glfs_access file not present, or not writable") == -1)
*reason = NULL;
result = false;
goto unref;
}
goto done;
unref:
gluster_cache_refresh(fs, path);
done:
if (gfd)
glfs_close(gfd);
gluster_free_server(&hosts);
return result;
} | 0 | 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 | vulnerable |
static unsigned int stack_maxrandom_size(void)
{
unsigned int max = 0;
if ((current->flags & PF_RANDOMIZE) &&
!(current->personality & ADDR_NO_RANDOMIZE)) {
max = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT;
}
return max;
} | 0 | C | 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 |
struct nfs_client *nfs4_init_client(struct nfs_client *clp,
const struct nfs_client_initdata *cl_init)
{
char buf[INET6_ADDRSTRLEN + 1];
const char *ip_addr = cl_init->ip_addr;
struct nfs_client *old;
int error;
if (clp->cl_cons_state == NFS_CS_READY)
/* the client is initialised already */
return clp;
/* Check NFS protocol revision and initialize RPC op vector */
clp->rpc_ops = &nfs_v4_clientops;
if (clp->cl_minorversion != 0)
__set_bit(NFS_CS_INFINITE_SLOTS, &clp->cl_flags);
__set_bit(NFS_CS_DISCRTRY, &clp->cl_flags);
__set_bit(NFS_CS_NO_RETRANS_TIMEOUT, &clp->cl_flags);
error = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_GSS_KRB5I);
if (error == -EINVAL)
error = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_UNIX);
if (error < 0)
goto error;
/* If no clientaddr= option was specified, find a usable cb address */
if (ip_addr == NULL) {
struct sockaddr_storage cb_addr;
struct sockaddr *sap = (struct sockaddr *)&cb_addr;
error = rpc_localaddr(clp->cl_rpcclient, sap, sizeof(cb_addr));
if (error < 0)
goto error;
error = rpc_ntop(sap, buf, sizeof(buf));
if (error < 0)
goto error;
ip_addr = (const char *)buf;
}
strlcpy(clp->cl_ipaddr, ip_addr, sizeof(clp->cl_ipaddr));
error = nfs_idmap_new(clp);
if (error < 0) {
dprintk("%s: failed to create idmapper. Error = %d\n",
__func__, error);
goto error;
}
__set_bit(NFS_CS_IDMAP, &clp->cl_res_state);
error = nfs4_init_client_minor_version(clp);
if (error < 0)
goto error;
error = nfs4_discover_server_trunking(clp, &old);
if (error < 0)
goto error;
if (clp != old) {
clp->cl_preserve_clid = true;
/*
* Mark the client as having failed initialization so other
* processes walking the nfs_client_list in nfs_match_client()
* won't try to use it.
*/
nfs_mark_client_ready(clp, -EPERM);
}
clear_bit(NFS_CS_TSM_POSSIBLE, &clp->cl_flags);
nfs_put_client(clp);
return old;
error:
nfs_mark_client_ready(clp, error);
nfs_put_client(clp);
return ERR_PTR(error);
} | 0 | C | NVD-CWE-noinfo | null | null | null | vulnerable |
init_pyfribidi (void)
{
PyObject *module = Py_InitModule ("_pyfribidi", PyfribidiMethods);
PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL);
PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR);
PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON);
} | 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 |
void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del(&pin->m_list);
hlist_del(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
} | 0 | 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 | vulnerable |
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
} | 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 |
static int ext4_split_unwritten_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path,
int flags)
{
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= EXT4_EXT_MARK_UNINIT2;
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, path, map, split_flag, flags);
} | 1 | C | NVD-CWE-noinfo | null | null | null | safe |
def parse_yaml_query(yaml_content):
"""Parses the given YAML string to attempt to extract a query.
Args:
yaml_content: A string containing YAML content.
Returns:
On success, the processed MLQuery object.
"""
logger.debug("Attempting to parse YAML content:\n%s" % yaml_content)
return parse_query(yaml.safe_load(yaml_content)) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def test_can_read_token_from_headers(self):
"""Tests that Sydent correct extracts an auth token from request headers"""
self.sydent.run()
request, _ = make_request(
self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details"
)
request.requestHeaders.addRawHeader(
b"Authorization", b"Bearer " + self.test_token.encode("ascii")
)
token = tokenFromRequest(request)
self.assertEqual(token, self.test_token) | 0 | Python | 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 profile():
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [LC('en')]
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if feature_support['oauth'] and config.config_login_type == 2:
oauth_status = get_oauth_status()
local_oauth_check = oauth_check
else:
oauth_status = None
local_oauth_check = {}
if request.method == "POST":
change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
return render_title_template("user_edit.html",
translations=translations,
profile=1,
languages=languages,
content=current_user,
kobo_support=kobo_support,
title=_(u"%(name)s's profile", name=current_user.name),
page="me",
registered_oauth=local_oauth_check,
oauth_status=oauth_status) | 0 | Python | 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 test_inappropriate_type_comments(self):
"""Tests for inappropriately-placed type comments.
These should be silently ignored with type comments off,
but raise SyntaxError with type comments on.
This is not meant to be exhaustive.
"""
def check_both_ways(source):
ast.parse(source, type_comments=False)
with self.assertRaises(SyntaxError):
ast.parse(source, type_comments=True)
check_both_ways("pass # type: int\n")
check_both_ways("foo() # type: int\n")
check_both_ways("x += 1 # type: int\n")
check_both_ways("while True: # type: int\n continue\n")
check_both_ways("while True:\n continue # type: int\n")
check_both_ways("try: # type: int\n pass\nfinally:\n pass\n")
check_both_ways("try:\n pass\nfinally: # type: int\n pass\n") | 1 | Python | 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 |
def format_time(self, data):
"""
A hook to control how times are formatted.
Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).
Default is ``iso-8601``, which looks like "03:02:14".
"""
if self.datetime_formatting == 'rfc-2822':
return format_time(data)
return data.isoformat() | 1 | Python | 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 host_passes(self, host_state, filter_properties):
context = filter_properties['context']
scheduler_hints = filter_properties.get('scheduler_hints') or {}
me = host_state.host
affinity_uuids = scheduler_hints.get('different_host', [])
if isinstance(affinity_uuids, basestring):
affinity_uuids = [affinity_uuids]
if affinity_uuids:
return not any([i for i in affinity_uuids
if self._affinity_host(context, i) == me])
# With no different_host key
return True | 0 | Python | 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 decompile(self):
self.writeln("** Decompiling APK...", clr.OKBLUE)
with ZipFile(self.file) as zipped:
try:
dex = self.tempdir + "/" + self.apk.package + ".dex"
with open(dex, "wb") as classes:
classes.write(zipped.read("classes.dex"))
except Exception as e:
sys.exit(self.writeln(str(e), clr.WARNING))
dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir)
os.system(dec)
return self.tempdir | 0 | Python | 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 test_no_content_length(self):
# wtf happens when there's no content-length
to_send = tobytes(
"GET /no_content_length HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: 0\r\n"
"\r\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line = fp.readline() # status line
line, headers, response_body = read_http(fp)
content_length = headers.get("content-length")
self.assertEqual(content_length, None)
self.assertEqual(response_body, tobytes("abcdefghi"))
# remote closed connection (despite keepalive header)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def test_keepalive_http11_connclose(self):
# specifying Connection: close explicitly
data = "Don't keep me alive"
s = tobytes(
"GET / HTTP/1.1\n"
"Connection: close\n"
"Content-Length: %d\n"
"\n"
"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertEqual(response.getheader("connection"), "close") | 0 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | vulnerable |
def serialize(self, bundle, format='application/json', options={}):
"""
Given some data and a format, calls the correct method to serialize
the data and returns the result.
"""
desired_format = None
for short_format, long_format in self.content_types.items():
if format == long_format:
if hasattr(self, "to_%s" % short_format):
desired_format = short_format
break
if desired_format is None:
raise UnsupportedFormat("The format indicated '%s' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
serialized = getattr(self, "to_%s" % desired_format)(bundle, options)
return serialized | 1 | Python | 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_student_progress_url(request, course_id):
"""
Get the progress url of a student.
Limited to staff access.
Takes query paremeter unique_student_identifier and if the student exists
returns e.g. {
'progress_url': '/../...'
}
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
user = get_student_from_identifier(request.GET.get('unique_student_identifier'))
progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id})
response_payload = {
'course_id': course_id.to_deprecated_string(),
'progress_url': progress_url,
}
return JsonResponse(response_payload) | 0 | Python | 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 | vulnerable |
def feed_unread_books():
off = request.args.get("offset") or 0
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True)
return render_xml_template('feed.xml', entries=result, pagination=pagination) | 0 | Python | 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 testDuplicateSrc(self):
x = [-4, -3, -2, -1, 0, 1, 2, 3]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Destination and source format must determine a permutation"):
op = nn_ops.data_format_dim_map(x, src_format="1233", dst_format="4321")
with test_util.use_gpu():
self.evaluate(op) | 1 | Python | 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 |
def host_passes(self, host_state, filter_properties):
context = filter_properties['context']
scheduler_hints = filter_properties.get('scheduler_hints') or {}
me = host_state.host
affinity_uuids = scheduler_hints.get('different_host', [])
if isinstance(affinity_uuids, basestring):
affinity_uuids = [affinity_uuids]
if affinity_uuids:
all_hosts = self._all_hosts(context)
return not any([i for i in affinity_uuids
if all_hosts.get(i) == me])
# With no different_host key
return True | 1 | Python | 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_funcdef(self):
tree = self.parse(funcdef)
self.assertEqual(tree.body[0].type_comment, "() -> int")
self.assertEqual(tree.body[1].type_comment, "() -> None")
tree = self.classic_parse(funcdef)
self.assertEqual(tree.body[0].type_comment, None)
self.assertEqual(tree.body[1].type_comment, None) | 1 | Python | 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 |
def test_create_class_from_xml_string_xxe():
xml = """<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
]>
<lolz>&lol1;</lolz>
"""
with raises(EntitiesForbidden) as err:
create_class_from_xml_string(NameID, xml) | 1 | Python | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | safe |
def auth_ldap_server(self):
return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"] | 0 | Python | 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 _request(self, method, path, queries=(), body=None, ensure_encoding=True,
log_request_body=True, ignore_prefix=False): | 1 | Python | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def set_multi(self, mapping, server_key, serialize=True, timeout=0):
"""
Sets multiple key/value pairs in memcache.
:param mapping: dictonary of keys and values to be set in memcache
:param servery_key: key to use in determining which server in the ring
is used
:param serialize: if True, value is pickled before sending to memcache
:param timeout: ttl for memcache
"""
server_key = md5hash(server_key)
if timeout > 0:
timeout += time.time()
msg = ''
for key, value in mapping.iteritems():
key = md5hash(key)
flags = 0
if serialize:
value = pickle.dumps(value, PICKLE_PROTOCOL)
flags |= PICKLE_FLAG
msg += ('set %s %d %d %s noreply\r\n%s\r\n' %
(key, flags, timeout, len(value), value))
for (server, fp, sock) in self._get_conns(server_key):
try:
sock.sendall(msg)
self._return_conn(server, fp, sock)
return
except Exception, e:
self._exception_occurred(server, e) | 0 | Python | 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 |
def publish(request, user_id=None):
initial = None
if user_id: # todo: move to form
user_to = get_object_or_404(User, pk=user_id)
initial = {'users': [user_to.st.nickname]}
user = request.user
tform = TopicForPrivateForm(
user=user, data=post_data(request))
cform = CommentForm(
user=user, data=post_data(request))
tpform = TopicPrivateManyForm(
user=user, data=post_data(request), initial=initial)
if (is_post(request) and
all([tform.is_valid(), cform.is_valid(), tpform.is_valid()]) and
not request.is_limited()):
if not user.st.update_post_hash(tform.get_topic_hash()):
return redirect(
request.POST.get('next', None) or
tform.category.get_absolute_url())
# wrap in transaction.atomic?
topic = tform.save()
cform.topic = topic
comment = cform.save()
comment_posted(comment=comment, mentions=None)
tpform.topic = topic
tpform.save_m2m()
TopicNotification.bulk_create(
users=tpform.get_users(), comment=comment)
return redirect(topic.get_absolute_url())
return render(
request=request,
template_name='spirit/topic/private/publish.html',
context={
'tform': tform,
'cform': cform,
'tpform': tpform}) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def test_get_sale_records_features_csv(self):
"""
Test that the response from get_sale_records is in csv format.
"""
for i in range(2):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i),
course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor,
invoice=self.sale_invoice_1,
invoice_item=self.invoice_item,
mode_slug='honor'
)
course_registration_code.save()
url = reverse(
'get_sale_records',
kwargs={'course_id': self.course.id.to_deprecated_string()}
)
response = self.client.post(url + '/csv', {})
self.assertEqual(response['Content-Type'], 'text/csv') | 1 | Python | 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 _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha("%s%s%s" % (cnonce, iso_now, password)).digest()
).strip() | 0 | Python | 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 __setstate__(self, state):
"""Restore from pickled state."""
self.__dict__ = state
self._lock = threading.Lock()
self._descriptor_cache = weakref.WeakKeyDictionary()
self._key_for_call_stats = self._get_key_for_call_stats() | 0 | Python | CWE-667 | Improper Locking | The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors. | https://cwe.mitre.org/data/definitions/667.html | vulnerable |
def _has_sneaky_javascript(self, style):
"""
Depending on the browser, stuff like ``e x p r e s s i o n(...)``
can get interpreted, or ``expre/* stuff */ssion(...)``. This
checks for attempt to do stuff like this.
Typically the response will be to kill the entire style; if you
have just a bit of Javascript in the style another rule will catch
that and remove only the Javascript from the style; this catches
more sneaky attempts.
"""
style = self._substitute_comments('', style)
style = style.replace('\\', '')
style = _substitute_whitespace('', style)
style = style.lower()
if 'javascript:' in style:
return True
if 'expression(' in style:
return True
if '@import' in style:
return True
if '</noscript' in style:
# e.g. '<noscript><style><a title="</noscript><img src=x onerror=alert(1)>">'
return True
if _looks_like_tag_content(style):
# e.g. '<math><style><img src=x onerror=alert(1)></style></math>'
return True
return False | 1 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
def check_ssh_passwd_need(host):
"""
Check whether access to host need password
"""
ssh_options = "-o StrictHostKeyChecking=no -o EscapeChar=none -o ConnectTimeout=15"
ssh_cmd = "ssh {} -T -o Batchmode=yes {} true".format(ssh_options, host)
rc, _, _ = get_stdout_stderr(ssh_cmd)
return rc != 0 | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def initSession(self, expire_on_commit=True):
self.session = self.session_factory()
self.session.expire_on_commit = expire_on_commit
self.update_title_sort(self.config) | 0 | Python | 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 _get_element_ptr_tuplelike(parent, key):
typ = parent.typ
assert isinstance(typ, TupleLike)
if isinstance(typ, StructType):
assert isinstance(key, str)
subtype = typ.members[key]
attrs = list(typ.tuple_keys())
index = attrs.index(key)
annotation = key
else:
assert isinstance(key, int)
subtype = typ.members[key]
attrs = list(range(len(typ.members)))
index = key
annotation = None
# generated by empty() + make_setter
if parent.value == "~empty":
return IRnode.from_list("~empty", typ=subtype)
if parent.value == "multi":
assert parent.encoding != Encoding.ABI, "no abi-encoded literals"
return parent.args[index]
ofst = 0 # offset from parent start
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
member_t = typ.members[attrs[index]]
for i in range(index):
member_abi_t = typ.members[attrs[i]].abi_type
ofst += member_abi_t.embedded_static_size()
return _getelemptr_abi_helper(parent, member_t, ofst)
if parent.location.word_addressable:
for i in range(index):
ofst += typ.members[attrs[i]].storage_size_in_words
elif parent.location.byte_addressable:
for i in range(index):
ofst += typ.members[attrs[i]].memory_bytes_required
else:
raise CompilerPanic(f"bad location {parent.location}") # pragma: notest
return IRnode.from_list(
add_ofst(parent, ofst),
typ=subtype,
location=parent.location,
encoding=parent.encoding,
annotation=annotation,
) | 0 | Python | 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 | vulnerable |
def render_POST(self, request):
"""
Register with the Identity Server
"""
send_cors(request)
args = get_args(request, ('matrix_server_name', 'access_token'))
hostname = args['matrix_server_name'].lower()
if not is_valid_hostname(hostname):
request.setResponseCode(400)
return {
'errcode': 'M_INVALID_PARAM',
'error': 'matrix_server_name must be a valid hostname'
}
result = yield self.client.get_json(
"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s"
% (
hostname,
urllib.parse.quote(args['access_token']),
),
1024 * 5,
)
if 'sub' not in result:
raise Exception("Invalid response from homeserver")
user_id = result['sub']
tok = yield issueToken(self.sydent, user_id)
# XXX: `token` is correct for the spec, but we released with `access_token`
# for a substantial amount of time. Serve both to make spec-compliant clients
# happy.
defer.returnValue({
"access_token": tok,
"token": tok,
}) | 1 | Python | 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 create_access(request, topic_id):
topic_private = TopicPrivate.objects.for_create_or_404(topic_id, request.user)
form = TopicPrivateInviteForm(
topic=topic_private.topic,
data=post_data(request))
if form.is_valid():
form.save()
notify_access(user=form.get_user(), topic_private=topic_private)
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next', topic_private.get_absolute_url())) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def formatType(self):
format_type = self.type.lower()
if format_type == 'amazon':
return u"Amazon"
elif format_type.startswith("amazon_"):
return u"Amazon.{0}".format(format_type[7:])
elif format_type == "isbn":
return u"ISBN"
elif format_type == "doi":
return u"DOI"
elif format_type == "douban":
return u"Douban"
elif format_type == "goodreads":
return u"Goodreads"
elif format_type == "babelio":
return u"Babelio"
elif format_type == "google":
return u"Google Books"
elif format_type == "kobo":
return u"Kobo"
elif format_type == "litres":
return u"ЛитРес"
elif format_type == "issn":
return u"ISSN"
elif format_type == "isfdb":
return u"ISFDB"
if format_type == "lubimyczytac":
return u"Lubimyczytac"
else:
return self.type | 0 | Python | 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 test_change_response_class_to_text():
mw = _get_mw()
req = SplashRequest('http://example.com/', magic_response=True)
req = mw.process_request(req, None)
# Such response can come when downloading a file,
# or returning splash:html(): the headers say it's binary,
# but it can be decoded so it becomes a TextResponse.
resp = TextResponse('http://mysplash.example.com/execute',
headers={b'Content-Type': b'application/pdf'},
body=b'ascii binary data',
encoding='utf-8')
resp2 = mw.process_response(req, resp, None)
assert isinstance(resp2, TextResponse)
assert resp2.url == 'http://example.com/'
assert resp2.headers == {b'Content-Type': [b'application/pdf']}
assert resp2.body == b'ascii binary data' | 0 | Python | 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 command_dispatch(request):
"""
Xtheme command dispatch view.
:param request: A request
:type request: django.http.HttpRequest
:return: A response
:rtype: django.http.HttpResponse
"""
command = request.POST.get("command")
if command:
response = handle_command(request, command)
if response:
return response
raise Problem("Error! Unknown command: `%r`" % command) | 0 | Python | 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 glob_to_regex(glob):
"""Converts a glob to a compiled regex object.
The regex is anchored at the beginning and end of the string.
Args:
glob (str)
Returns:
re.RegexObject
"""
res = ""
for c in glob:
if c == "*":
res = res + ".*"
elif c == "?":
res = res + "."
else:
res = res + re.escape(c)
# \A anchors at start of string, \Z at end of string
return re.compile(r"\A" + res + r"\Z", re.IGNORECASE) | 0 | Python | CWE-331 | Insufficient Entropy | The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | vulnerable |
def test_account_info_env_var_overrides_xdg_config_home(self):
with WindowsSafeTempDir() as d:
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
XDG_CONFIG_HOME_ENV_VAR: d,
B2_ACCOUNT_INFO_ENV_VAR: os.path.join(d, 'b2_account_info'),
}
)
expected_path = os.path.abspath(os.path.join(d, 'b2_account_info'))
actual_path = os.path.abspath(account_info.filename)
assert expected_path == actual_path | 0 | Python | CWE-367 | Time-of-check Time-of-use (TOCTOU) Race Condition | The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state. | https://cwe.mitre.org/data/definitions/367.html | vulnerable |
def test_after_start_response_http11_close(self):
to_send = tobytes(
"GET /after_start_response HTTP/1.1\n" "Connection: close\n\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 0 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | vulnerable |
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant."""
self.assert_admin(context)
# ensure that we're a member of that tenant
tenant_id = user.get('tenantId')
self.identity_api.add_user_to_tenant(context, tenant_id, user_id)
return self.update_user(context, user_id, user) | 1 | Python | 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 save_cover(img, book_path):
content_type = img.headers.get('content-type')
if use_IM:
if content_type not in ('image/jpeg', 'image/png', 'image/webp', 'image/bmp'):
log.error("Only jpg/jpeg/png/webp/bmp files are supported as coverfile")
return False, _("Only jpg/jpeg/png/webp/bmp files are supported as coverfile")
# convert to jpg because calibre only supports jpg
if content_type != 'image/jpg':
try:
if hasattr(img, 'stream'):
imgc = Image(blob=img.stream)
else:
imgc = Image(blob=io.BytesIO(img.content))
imgc.format = 'jpeg'
imgc.transform_colorspace("rgb")
img = imgc
except (BlobError, MissingDelegateError):
log.error("Invalid cover file content")
return False, _("Invalid cover file content")
else:
if content_type not in 'image/jpeg':
log.error("Only jpg/jpeg files are supported as coverfile")
return False, _("Only jpg/jpeg files are supported as coverfile")
if config.config_use_google_drive:
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
ret, message = save_cover_from_filestorage(tmp_dir, "uploaded_cover.jpg", img)
if ret is True:
gd.uploadFileToEbooksFolder(os.path.join(book_path, 'cover.jpg').replace("\\","/"),
os.path.join(tmp_dir, "uploaded_cover.jpg"))
log.info("Cover is saved on Google Drive")
return True, None
else:
return False, message
else:
return save_cover_from_filestorage(os.path.join(config.config_calibre_dir, book_path), "cover.jpg", img) | 0 | Python | 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 test_file(self, tmpdir):
filename = tmpdir / 'foo'
filename.ensure()
url = QUrl.fromLocalFile(str(filename))
req = QNetworkRequest(url)
reply = filescheme.handler(req, None, None)
assert reply is None | 1 | Python | 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 _testLabelsBroadcast(self, uniform_labels_gradient):
labels = np.array([[0., 0., 0., 1.]]).astype(np.float16)
logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16)
self._testXent2D(labels, logits, with_placeholders=True)
labels = np.array([[1.]]).astype(np.float16)
logits = np.array([[1.], [2.]]).astype(np.float16)
self._testXent2D(labels, logits, with_placeholders=True)
labels = np.array([[0.], [2.], [0.25]]).astype(np.float16)
logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.],
[1., 2., 3., 4.]]).astype(np.float16)
self._testXent2D(
labels,
logits,
with_placeholders=True,
expected_gradient=uniform_labels_gradient) | 1 | Python | CWE-354 | Improper Validation of Integrity Check Value | The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. | https://cwe.mitre.org/data/definitions/354.html | safe |
def getresponse(self):
mapper = routes.Mapper()
server = rserver.API(mapper)
# NOTE(markwash): we need to pass through context auth information if
# we have it.
if 'X-Auth-Token' in self.req.headers:
api = utils.FakeAuthMiddleware(server)
else:
api = context.UnauthenticatedContextMiddleware(server)
webob_res = self.req.get_response(api)
return utils.FakeHTTPResponse(status=webob_res.status_int,
headers=webob_res.headers,
data=webob_res.body) | 1 | Python | 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 innerfn(fn):
global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func
whitelisted.append(fn)
allowed_http_methods_for_whitelisted_func[fn] = methods
if allow_guest:
guest_methods.append(fn)
if xss_safe:
xss_safe_methods.append(fn)
return fn | 0 | Python | 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 check_against_blacklist(
ip_address: IPAddress, ip_whitelist: Optional[IPSet], ip_blacklist: IPSet | 1 | Python | 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 set_user_password(self, context, user_id, user):
return self.update_user(context, user_id, user) | 1 | Python | 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 mysql_starts_with(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"{value}%") | 0 | Python | 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 commit(self):
"""Commit transaction
"""
if not self.txn_active:
return
if self.files is not None:
with open(os.path.join(self.path, 'files'), 'wb') as fd:
for path_hash, item in self.files.items():
# Discard cached files with the newest mtime to avoid
# issues with filesystem snapshots and mtime precision
item = msgpack.unpackb(item)
if item[0] < 10 and bigint_to_int(item[3]) < self._newest_mtime:
msgpack.pack((path_hash, item), fd)
self.config.set('cache', 'manifest', hexlify(self.manifest.id).decode('ascii'))
self.config.set('cache', 'timestamp', self.manifest.timestamp)
self.config.set('cache', 'key_type', str(self.key.TYPE))
with open(os.path.join(self.path, 'config'), 'w') as fd:
self.config.write(fd)
self.chunks.write(os.path.join(self.path, 'chunks').encode('utf-8'))
os.rename(os.path.join(self.path, 'txn.active'),
os.path.join(self.path, 'txn.tmp'))
shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
self.txn_active = False | 1 | Python | 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 parse_line(s):
s = s.rstrip()
r = re.sub(REG_LINE_GPERF, '', s)
if r != s: return r
r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)
if r != s: return r
r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\1)', s)
if r != s: return r
r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)
if r != s: return r
r = re.sub(REG_ENTRY, '{\\1, \\2, \\3}', s)
if r != s: return r
r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\1, \\2}', s)
if r != s: return r
r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)
if r != s: return r
r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)
if r != s: return r
r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)
if r != s: return r
r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s)
if r != s: return r
return s | 0 | Python | 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 |
def test_reset_date(self):
self.test_change_due_date()
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
) | 0 | Python | 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 | vulnerable |
def make_sydent(test_config={}):
"""Create a new sydent
Args:
test_config (dict): any configuration variables for overriding the default sydent
config
"""
# Use an in-memory SQLite database. Note that the database isn't cleaned up between
# tests, so by default the same database will be used for each test if changed to be
# a file on disk.
if "db" not in test_config:
test_config["db"] = {"db.file": ":memory:"}
else:
test_config["db"].setdefault("db.file", ":memory:")
reactor = ResolvingMemoryReactorClock()
return Sydent(reactor=reactor, cfg=parse_config_dict(test_config), use_tls_for_federation=False) | 1 | Python | 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 | safe |
def test_get_student_progress_url_nostudent(self):
""" Test that the endpoint 400's when requesting an unknown email. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url)
self.assertEqual(response.status_code, 400) | 1 | Python | 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 __init__(
self,
reactor: IReactorPluggableNameResolver,
ip_whitelist: Optional[IPSet],
ip_blacklist: IPSet, | 1 | Python | 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 makeHTTPPageGetterFactory(protocolClass, method, host, path):
"""
Make a L{ClientFactory} that can be used with
L{client.HTTPPageGetter} and its subclasses.
@param protocolClass: The protocol class
@type protocolClass: A subclass of L{client.HTTPPageGetter}
@param method: the HTTP method
@param host: the host
@param path: The URI path
@return: A L{ClientFactory}.
"""
factory = ClientFactory.forProtocol(protocolClass)
factory.method = method
factory.host = host
factory.path = path
factory.scheme = b"http"
factory.port = 0
factory.headers = {}
factory.agent = b"User/Agent"
factory.cookies = {}
return factory | 1 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
def testRaggedCountSparseOutputBadSplitsStart(self):
splits = [1, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Splits must start with 0"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 1 | Python | 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_list_instructor_tasks_running(self, act):
""" Test list of all running tasks. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks) | 0 | Python | 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 | vulnerable |
def _load_yamlconfig(self, configfile):
yamlconfig = None
try:
if self._recent_pyyaml():
# https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
# only for 5.1+
yamlconfig = yaml.load(open(configfile), Loader=yaml.FullLoader)
else:
yamlconfig = yaml.load(open(configfile))
except yaml.YAMLError as exc:
logger.error("Error in configuration file {0}:".format(configfile))
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
raise PystemonConfigException("error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
for includes in yamlconfig.get("includes", []):
try:
logger.debug("loading include '{0}'".format(includes))
yamlconfig.update(yaml.load(open(includes)))
except Exception as e:
raise PystemonConfigException("failed to load '{0}': {1}".format(includes, e))
return yamlconfig | 0 | Python | 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 test_reset_student_attempts_nonsense(self):
""" Test failure with both unique_student_identifier and all_students. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'all_students': True,
})
self.assertEqual(response.status_code, 400) | 0 | Python | 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 | vulnerable |
def test_big_arrays(self):
L = (1 << 31) + 100000
a = np.empty(L, dtype=np.uint8)
with tempdir() as tmpdir:
tmp = open(os.path.join(tmpdir, "file.npz"), "w")
np.savez(tmp, a=a)
del a
npfile = np.load(tmp)
a = npfile['a']
npfile.close() | 1 | Python | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | safe |
def test_after_start_response_http10(self):
to_send = "GET /after_start_response HTTP/1.0\r\n\r\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
in_path = self._normalize_path(in_path, self.get_jail_path())
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail)
self._copy_file(in_path, out_path) | 0 | Python | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | vulnerable |
def table_xchange_author_title():
vals = request.get_json().get('xchange')
if vals:
for val in vals:
modif_date = False
book = calibre_db.get_book(val)
authors = book.title
book.authors = calibre_db.order_authors([book])
author_names = []
for authr in book.authors:
author_names.append(authr.name.replace('|', ','))
title_change = handle_title_on_edit(book, " ".join(author_names))
input_authors, authorchange, renamed = handle_author_on_edit(book, authors)
if authorchange or title_change:
edited_books_id = book.id
modif_date = True
if config.config_use_google_drive:
gdriveutils.updateGdriveCalibreFromLocal()
if edited_books_id:
helper.update_dir_structure(edited_books_id, config.config_calibre_dir, input_authors[0],
renamed_author=renamed)
if modif_date:
book.last_modified = datetime.utcnow()
try:
calibre_db.session.commit()
except (OperationalError, IntegrityError) as e:
calibre_db.session.rollback()
log.error_or_exception("Database error: %s", e)
return json.dumps({'success': False})
if config.config_use_google_drive:
gdriveutils.updateGdriveCalibreFromLocal()
return json.dumps({'success': True})
return "" | 0 | Python | 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 delete(self, req, image_id):
self._enforce(req, 'delete_image')
image = self._get_image(req.context, image_id)
if image['protected']:
msg = _("Unable to delete as image %(image_id)s is protected"
% locals())
raise webob.exc.HTTPForbidden(explanation=msg)
status = 'deleted'
if image['location']:
if CONF.delayed_delete:
status = 'pending_delete'
self.store_api.schedule_delayed_delete_from_backend(
image['location'], id)
else:
self.store_api.safe_delete_from_backend(image['location'],
req.context, id)
try:
self.db_api.image_update(req.context, image_id, {'status': status})
self.db_api.image_destroy(req.context, image_id)
except (exception.NotFound, exception.Forbidden):
msg = ("Failed to find image %(image_id)s to delete" % locals())
LOG.info(msg)
raise webob.exc.HTTPNotFound()
else:
self.notifier.info('image.delete', image) | 0 | Python | 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 mysql_insensitive_starts_with(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"{value}%")) | 0 | Python | 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 try_ldap_login(login, password):
""" Connect to a LDAP directory to verify user login/passwords"""
result = "Wrong login/password"
s = Server(config.LDAPURI, port=config.LDAPPORT,
use_ssl=False, get_info=ALL)
# 1. connection with service account to find the user uid
uid = useruid(s, login)
if uid:
# 2. Try to bind the user to the LDAP
c = Connection(s, user = uid , password = password, auto_bind = True)
c.open()
c.bind()
result = c.result["description"] # "success" if bind is ok
c.unbind()
return result | 0 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
def __init__(
self,
*,
resource_group: str,
location: str,
application_name: str,
owner: str,
client_id: Optional[str],
client_secret: Optional[str],
app_zip: str,
tools: str,
instance_specific: str,
third_party: str,
arm_template: str,
workbook_data: str,
create_registration: bool,
migrations: List[str],
export_appinsights: bool,
log_service_principal: bool,
multi_tenant_domain: str,
upgrade: bool,
subscription_id: Optional[str],
admins: List[UUID] | 0 | Python | 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 | vulnerable |
def testMaxPoolGradWithArgmaxEagerShapeErrors(self):
with context.eager_mode():
inp = array_ops.ones((1, 1, 1, 1))
# Test invalid grad shape
grad = array_ops.ones((1, 1, 1, 2))
argmax = array_ops.zeros((1, 1, 1, 1), dtype=dtypes.int64)
with self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
gen_nn_ops.max_pool_grad_with_argmax(
inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
padding="VALID")
# max_pool_grad_grad_with_argmax is only implemented for GPUs
if test.is_gpu_available():
with self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
gen_nn_ops.max_pool_grad_grad_with_argmax(
inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
padding="VALID")
# Test invalid argmax shape
grad = array_ops.ones((1, 1, 1, 1))
argmax = array_ops.ones((1, 1, 1, 2), dtype=dtypes.int64)
with self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
gen_nn_ops.max_pool_grad_with_argmax(
inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
padding="VALID")
# max_pool_grad_grad_with_argmax is only implemented for GPUs
if test.is_gpu_available():
with self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
gen_nn_ops.max_pool_grad_grad_with_argmax(
inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
padding="VALID") | 1 | Python | CWE-354 | Improper Validation of Integrity Check Value | The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. | https://cwe.mitre.org/data/definitions/354.html | safe |
def sentences_victim(self, type, data = None, sRun = 1, column = 0):
if sRun == 2:
return self.sql_insert(self.prop_sentences_victim(type, data))
elif sRun == 3:
return self.sql_one_row(self.prop_sentences_victim(type, data), column)
else:
return self.sql_execute(self.prop_sentences_victim(type, data)) | 0 | Python | 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 test_visitor(self):
class CustomVisitor(self.asdl.VisitorBase):
def __init__(self):
super().__init__()
self.names_with_seq = []
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value)
def visitSum(self, sum):
for t in sum.types:
self.visit(t)
def visitConstructor(self, cons):
for f in cons.fields:
if f.seq:
self.names_with_seq.append(cons.name)
v = CustomVisitor()
v.visit(self.types['mod'])
self.assertEqual(v.names_with_seq, ['Module', 'Interactive', 'Suite']) | 0 | Python | 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 | vulnerable |
def testRaggedCountSparseOutputEmptySplits(self):
splits = []
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Must provide at least 2 elements for the splits argument"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 1 | Python | 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 | safe |
def add_security_headers(resp):
resp.headers['Content-Security-Policy'] = "default-src 'self' 'unsafe-inline' 'unsafe-eval';"
if request.endpoint == "editbook.edit_book":
resp.headers['Content-Security-Policy'] += "img-src * data:"
resp.headers['X-Content-Type-Options'] = 'nosniff'
resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
resp.headers['X-XSS-Protection'] = '1; mode=block'
resp.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
# log.debug(request.full_path)
return resp | 0 | Python | 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 | vulnerable |
def table_get_locale():
locale = babel.list_translations() + [LC('en')]
ret = list()
current_locale = get_locale()
for loc in locale:
ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)})
return json.dumps(ret) | 0 | Python | 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 get_federation_http_client(self) -> MatrixFederationHttpClient:
"""
An HTTP client for federation.
"""
tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory) | 1 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | safe |
def show_student_extensions(request, course_id):
"""
Shows all of the due date extensions granted to a particular student in a
particular course.
"""
student = require_student_from_identifier(request.POST.get('student'))
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
return JsonResponse(dump_student_extensions(course, student)) | 1 | Python | 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 test_broken_chunked_encoding_missing_chunk_end(self):
control_line = "20;\r\n" # 20 hex = 32 dec
s = "This string has 32 characters.\r\n"
to_send = "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
to_send += control_line + s
# garbage in input
to_send += "garbage"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
# receiver caught garbage and turned it into a 400
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(b"Chunk not properly terminated" in response_body)
self.assertEqual(
sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"]
)
self.assertEqual(headers["content-type"], "text/plain")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None, | 0 | Python | 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 sanitize_path(path):
"""Make absolute (with leading slash) to prevent access to other data.
Preserves an potential trailing slash."""
trailing_slash = "/" if path.endswith("/") else ""
path = posixpath.normpath(path)
new_path = "/"
for part in path.split("/"):
if not part or part in (".", ".."):
continue
new_path = posixpath.join(new_path, part)
trailing_slash = "" if new_path.endswith("/") else trailing_slash
return new_path + trailing_slash | 0 | Python | CWE-21 | DEPRECATED: Pathname Traversal and Equivalence Errors | This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706). | https://cwe.mitre.org/data/definitions/21.html | vulnerable |
def get(self, location, connection=None):
location = location.store_location
if not connection:
connection = self.get_connection(location)
try:
resp_headers, resp_body = connection.get_object(
container=location.container, obj=location.obj,
resp_chunk_size=self.CHUNKSIZE)
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
else:
raise
class ResponseIndexable(glance.store.Indexable):
def another(self):
try:
return self.wrapped.next()
except StopIteration:
return ''
length = int(resp_headers.get('content-length', 0))
return (ResponseIndexable(resp_body, length), length) | 1 | Python | 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 stmt(self, stmt, msg=None):
mod = ast.Module([stmt], [])
self.mod(mod, msg) | 1 | Python | 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 |
def is_valid_matrix_server_name(string: str) -> bool:
"""Validate that the given string is a valid Matrix server name.
A string is a valid Matrix server name if it is one of the following, plus
an optional port:
a. IPv4 address
b. IPv6 literal (`[IPV6_ADDRESS]`)
c. A valid hostname
:param string: The string to validate
:type string: str
:return: Whether the input is a valid Matrix server name
:rtype: bool
"""
try:
host, port = parse_server_name(string)
except ValueError:
return False
valid_ipv4_addr = isIPAddress(host)
valid_ipv6_literal = host[0] == "[" and host[-1] == "]" and isIPv6Address(host[1:-1])
return valid_ipv4_addr or valid_ipv6_literal or is_valid_hostname(host) | 1 | Python | 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 create_win_temp_dir(prefix, inner_dir=None, tmp_dir=None):
"""
create temp dir starting with 'prefix' in 'tmp_dir' or
'tempfile.gettempdir'; if 'inner_dir' is specified, it should be
created inside
"""
tmp_dir_path = find_valid_temp_dir(prefix, tmp_dir)
if tmp_dir_path:
if inner_dir:
tmp_dir_path = os.path.join(tmp_dir_path, inner_dir)
if not os.path.isdir(tmp_dir_path):
os.mkdir(tmp_dir_path, 0o700)
else:
tmp_dir_path = create_temp_dir(prefix, inner_dir, tmp_dir)
return tmp_dir_path | 1 | Python | CWE-269 | Improper Privilege Management | The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def toggle_archived(book_id):
is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id))
if is_archived:
remove_synced_book(book_id)
return "" | 0 | Python | 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 testMustPassTensorArgumentToDLPack(self):
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"The argument to `to_dlpack` must be a TF tensor, not Python object"):
dlpack.to_dlpack([1]) | 1 | Python | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | safe |
def language_overview():
if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all":
order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1
charlist = list()
languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True)
for lang in languages:
upper_lang = lang[0].name[0].upper()
if upper_lang not in charlist:
charlist.append(upper_lang)
return render_title_template('languages.html', languages=languages,
charlist=charlist, title=_(u"Languages"), page="langlist",
data="language", order=order_no)
else:
abort(404) | 0 | Python | 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 test_get_files_from_storage(self):
content = b"test_get_files_from_storage"
name = storage.save(
"tmp/s3file/test_get_files_from_storage", ContentFile(content)
)
files = S3FileMiddleware.get_files_from_storage(
[os.path.join(storage.aws_location, name)]
)
file = next(files)
assert file.read() == content | 0 | Python | 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 test_is_valid_hostname(self):
"""Tests that the is_valid_hostname function accepts only valid
hostnames (or domain names), with optional port number.
"""
self.assertTrue(is_valid_hostname("example.com"))
self.assertTrue(is_valid_hostname("EXAMPLE.COM"))
self.assertTrue(is_valid_hostname("ExAmPlE.CoM"))
self.assertTrue(is_valid_hostname("example.com:4242"))
self.assertTrue(is_valid_hostname("localhost"))
self.assertTrue(is_valid_hostname("localhost:9000"))
self.assertTrue(is_valid_hostname("a.b:1234"))
self.assertFalse(is_valid_hostname("example.com:65536"))
self.assertFalse(is_valid_hostname("example.com:0"))
self.assertFalse(is_valid_hostname("example.com:a"))
self.assertFalse(is_valid_hostname("example.com:04242"))
self.assertFalse(is_valid_hostname("example.com: 4242"))
self.assertFalse(is_valid_hostname("example.com/example.com"))
self.assertFalse(is_valid_hostname("example.com#example.com")) | 0 | Python | 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 test_func_type_input(self):
def parse_func_type_input(source):
return ast.parse(source, "<unknown>", "func_type")
# Some checks below will crash if the returned structure is wrong
tree = parse_func_type_input("() -> int")
self.assertEqual(tree.argtypes, [])
self.assertEqual(tree.returns.id, "int")
tree = parse_func_type_input("(int) -> List[str]")
self.assertEqual(len(tree.argtypes), 1)
arg = tree.argtypes[0]
self.assertEqual(arg.id, "int")
self.assertEqual(tree.returns.value.id, "List")
self.assertEqual(tree.returns.slice.value.id, "str")
tree = parse_func_type_input("(int, *str, **Any) -> float")
self.assertEqual(tree.argtypes[0].id, "int")
self.assertEqual(tree.argtypes[1].id, "str")
self.assertEqual(tree.argtypes[2].id, "Any")
self.assertEqual(tree.returns.id, "float")
with self.assertRaises(SyntaxError):
tree = parse_func_type_input("(int, *str, *Any) -> float")
with self.assertRaises(SyntaxError):
tree = parse_func_type_input("(int, **str, Any) -> float")
with self.assertRaises(SyntaxError):
tree = parse_func_type_input("(**int, **str) -> float") | 1 | Python | 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 |
def read_config(self, config, **kwargs):
# FIXME: federation_domain_whitelist needs sytests
self.federation_domain_whitelist = None # type: Optional[dict]
federation_domain_whitelist = config.get("federation_domain_whitelist", None)
if federation_domain_whitelist is not None:
# turn the whitelist into a hash for speed of lookup
self.federation_domain_whitelist = {}
for domain in federation_domain_whitelist:
self.federation_domain_whitelist[domain] = True
ip_range_blacklist = config.get("ip_range_blacklist", [])
# Attempt to create an IPSet from the given ranges
try:
self.ip_range_blacklist = IPSet(ip_range_blacklist)
except Exception as e:
raise ConfigError("Invalid range(s) provided in ip_range_blacklist: %s" % e)
# Always blacklist 0.0.0.0, ::
self.ip_range_blacklist.update(["0.0.0.0", "::"])
# The federation_ip_range_blacklist is used for backwards-compatibility
# and only applies to federation and identity servers. If it is not given,
# default to ip_range_blacklist.
federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", ip_range_blacklist
)
try:
self.federation_ip_range_blacklist = IPSet(federation_ip_range_blacklist)
except Exception as e:
raise ConfigError(
"Invalid range(s) provided in federation_ip_range_blacklist: %s" % e
)
# Always blacklist 0.0.0.0, ::
self.federation_ip_range_blacklist.update(["0.0.0.0", "::"])
federation_metrics_domains = config.get("federation_metrics_domains") or []
validate_config(
_METRICS_FOR_DOMAINS_SCHEMA,
federation_metrics_domains,
("federation_metrics_domains",),
)
self.federation_metrics_domains = set(federation_metrics_domains) | 1 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | safe |
def test_create_security_group_quota_limit(self):
req = fakes.HTTPRequest.blank('/v2/fake/os-security-groups')
for num in range(1, FLAGS.quota_security_groups):
name = 'test%s' % num
sg = security_group_template(name=name)
res_dict = self.controller.create(req, {'security_group': sg})
self.assertEqual(res_dict['security_group']['name'], name)
sg = security_group_template()
self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create,
req, {'security_group': sg}) | 1 | Python | 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 show_book(book_id):
entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True)
if entries:
read_book = entries[1]
archived_book = entries[2]
entry = entries[0]
entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED
entry.is_archived = archived_book
for index in range(0, len(entry.languages)):
entry.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[
index].lang_code)
cc = get_cc_columns(filter_config_custom_read=True)
book_in_shelfs = []
shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all()
for sh in shelfs:
book_in_shelfs.append(sh.shelf)
entry.tags = sort(entry.tags, key=lambda tag: tag.name)
entry.ordered_authors = calibre_db.order_authors([entry])
entry.kindle_list = check_send_to_kindle(entry)
entry.reader_list = check_read_formats(entry)
entry.audioentries = []
for media_format in entry.data:
if media_format.format.lower() in constants.EXTENSIONS_AUDIO:
entry.audioentries.append(media_format.format.lower())
return render_title_template('detail.html',
entry=entry,
cc=cc,
is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest',
title=entry.title,
books_shelfs=book_in_shelfs,
page="book")
else:
log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible")
flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"),
category="error")
return redirect(url_for("web.index")) | 0 | Python | 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 test_notfilelike_http11(self):
to_send = "GET /notfilelike HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body) | 0 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.