code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
public void buildFrameInOneGo() throws IOException {
buffer = ByteBuffer.wrap(new byte[] { 1, 0, 0, 0, 0, 0, 3, 1, 2, 3, end() });
builder = new FrameBuilder(channel, buffer);
Frame frame = builder.readFrame();
assertThat(frame).isNotNull();
assertThat(frame.type).isEqualTo(1);
assertThat(frame.channel).isEqualTo(0);
assertThat(frame.getPayload()).hasSize(3);
} | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The product 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 |
public void protocolMismatchHeader() throws IOException {
ByteBuffer[] buffers = new ByteBuffer[] {
ByteBuffer.wrap(new byte[] { 'A' }),
ByteBuffer.wrap(new byte[] { 'A', 'M', 'Q' }),
ByteBuffer.wrap(new byte[] { 'A', 'N', 'Q', 'P' }),
ByteBuffer.wrap(new byte[] { 'A', 'M', 'Q', 'P' }),
ByteBuffer.wrap(new byte[] { 'A', 'M', 'Q', 'P', 1, 1, 8 }),
ByteBuffer.wrap(new byte[] { 'A', 'M', 'Q', 'P', 1, 1, 8, 0 }),
ByteBuffer.wrap(new byte[] { 'A', 'M', 'Q', 'P', 1, 1, 9, 1 })
};
String[] messages = new String[] {
"Invalid AMQP protocol header from server: read only 1 byte(s) instead of 4",
"Invalid AMQP protocol header from server: read only 3 byte(s) instead of 4",
"Invalid AMQP protocol header from server: expected character 77, got 78",
"Invalid AMQP protocol header from server",
"Invalid AMQP protocol header from server",
"AMQP protocol version mismatch; we are version 0-9-1, server is 0-8",
"AMQP protocol version mismatch; we are version 0-9-1, server sent signature 1,1,9,1"
};
for (int i = 0; i < buffers.length; i++) {
builder = new FrameBuilder(channel, buffers[i]);
try {
builder.readFrame();
fail("protocol header not correct, exception should have been thrown");
} catch (MalformedFrameException e) {
assertThat(e.getMessage()).isEqualTo(messages[i]);
}
}
} | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The product 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 |
public void buildFramesInOneGo() throws IOException {
byte[] frameContent = new byte[] { 1, 0, 0, 0, 0, 0, 3, 1, 2, 3, end() };
int nbFrames = 13;
byte[] frames = new byte[frameContent.length * nbFrames];
for (int i = 0; i < nbFrames; i++) {
for (int j = 0; j < frameContent.length; j++) {
frames[i * frameContent.length + j] = frameContent[j];
}
}
buffer = ByteBuffer.wrap(frames);
builder = new FrameBuilder(channel, buffer);
int frameCount = 0;
Frame frame;
while ((frame = builder.readFrame()) != null) {
assertThat(frame).isNotNull();
assertThat(frame.type).isEqualTo(1);
assertThat(frame.channel).isEqualTo(0);
assertThat(frame.getPayload()).hasSize(3);
frameCount++;
}
assertThat(frameCount).isEqualTo(nbFrames);
} | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The product 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 |
protected DocumentBuilder getDocumentBuilder(
) throws ServiceException {
DocumentBuilder documentBuilder = null;
DocumentBuilderFactory documentBuilderFactory = null;
try {
documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new ServiceException(e);
}
return documentBuilder;
} | 0 | Java | CWE-611 | Improper Restriction of XML External Entity Reference | The product 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 | vulnerable |
public static void unzip(InputStream is, File dest) throws IOException {
try (ZipInputStream zis = new ZipInputStream(is)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
File file = new File(dest, name);
if (entry.isDirectory()) {
FileUtils.forceMkdir(file);
} else {
File parentFile = file.getParentFile();
FileUtils.forceMkdir(parentFile);
try (OutputStream os = Files.newOutputStream(file.toPath())) {
IOUtils.copy(zis, os);
}
}
}
}
} | 0 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 |
private static void addExtraKexAlgorithms(CryptoWishList cwl) {
String[] oldKexAlgorithms = cwl.kexAlgorithms;
List<String> kexAlgorithms = new ArrayList<>(oldKexAlgorithms.length + 1);
for (String algo : oldKexAlgorithms)
{
if (!algo.equals(EXT_INFO_C))
kexAlgorithms.add(algo);
}
kexAlgorithms.add(EXT_INFO_C);
cwl.kexAlgorithms = kexAlgorithms.toArray(new String[0]);
} | 0 | Java | CWE-354 | Improper Validation of Integrity Check Value | The product 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 | vulnerable |
public void configAviatorEvaluator() {
// 配置AviatorEvaluator使用LRU缓存编译后的表达式
AviatorEvaluator.getInstance()
.useLRUExpressionCache(AVIATOR_LRU_CACHE_SIZE)
.addFunction(new StrEqualFunction());
// 配置自定义aviator函数
AviatorEvaluator.getInstance().addOpFunction(OperatorType.BIT_OR, new AbstractFunction() {
@Override
public AviatorObject call(final Map<String, Object> env, final AviatorObject arg1,
final AviatorObject arg2) {
try {
Object value1 = arg1.getValue(env);
Object value2 = arg2.getValue(env);
Object currentValue = value1 == null ? value2 : value1;
if (arg1.getAviatorType() == AviatorType.String) {
return new AviatorString(String.valueOf(currentValue));
} else {
return AviatorDouble.valueOf(currentValue);
}
} catch (Exception e) {
log.error(e.getMessage());
}
return arg1.bitOr(arg2, env);
}
@Override
public String getName() {
return OperatorType.BIT_OR.getToken();
}
});
AviatorEvaluator.getInstance().addFunction(new StrContainsFunction());
AviatorEvaluator.getInstance().addFunction(new ObjectExistsFunction());
AviatorEvaluator.getInstance().addFunction(new StrMatchesFunction());
} | 0 | Java | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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 |
public R update(FriendLinkDO friendLink) {
friendLinkService.update(friendLink);
redisTemplate.delete(CacheKey.INDEX_LINK_KEY);
return R.ok();
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public R save(FriendLinkDO friendLink) {
if (friendLinkService.save(friendLink) > 0) {
redisTemplate.delete(CacheKey.INDEX_LINK_KEY);
return R.ok();
}
return R.error();
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Integer getIsOpen() {
return isOpen;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setLinkName(String linkName) {
this.linkName = linkName;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Date getCreateTime() {
return createTime;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setUpdateUserId(Long updateUserId) {
this.updateUserId = updateUserId;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Integer getId() {
return id;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public String getLinkName() {
return linkName;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Date getUpdateTime() {
return updateTime;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setSort(Integer sort) {
this.sort = sort;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setId(Integer id) {
this.id = id;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setLinkUrl(String linkUrl) {
this.linkUrl = linkUrl;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Long getUpdateUserId() {
return updateUserId;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public String getLinkUrl() {
return linkUrl;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Integer getSort() {
return sort;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public Long getCreateUserId() {
return createUserId;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setIsOpen(Integer isOpen) {
this.isOpen = isOpen;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | 0 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
public static CBORObject RandomCBORMap(IRandomGenExtended rand, int depth) {
int x = rand.GetInt32(100);
int count = (x < 80) ? 2 : ((x < 93) ? 1 : ((x < 98) ? 0 : 10));
CBORObject cborRet = CBORObject.NewMap();
for (var i = 0; i < count; ++i) {
CBORObject key = RandomCBORObject(rand, depth + 1);
CBORObject value = RandomCBORObject(rand, depth + 1);
cborRet[key] = value;
}
return cborRet;
} | 0 | Java | CWE-407 | Inefficient Algorithmic Complexity | An algorithm in a product has an inefficient worst-case computational complexity that may be detrimental to system performance and can be triggered by an attacker, typically using crafted manipulations that ensure that the worst case is being reached. | https://cwe.mitre.org/data/definitions/407.html | vulnerable |
private static bool ByteArraysEqual(byte[] arr1, byte[] arr2) {
if (arr1 == null) {
return arr2 == null;
}
if (arr2 == null) {
return false;
}
if (arr1.Length != arr2.Length) {
return false;
}
for (var i = 0; i < arr1.Length; ++i) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
} | 0 | Java | CWE-407 | Inefficient Algorithmic Complexity | An algorithm in a product has an inefficient worst-case computational complexity that may be detrimental to system performance and can be triggered by an attacker, typically using crafted manipulations that ensure that the worst case is being reached. | https://cwe.mitre.org/data/definitions/407.html | vulnerable |
private <T> T runAsAuthenticated( Callable<T> runnable )
{
final AuthenticationInfo authInfo = AuthenticationInfo.create().principals( RoleKeys.AUTHENTICATED ).user( User.ANONYMOUS ).build();
return ContextBuilder.from( this.context.get() ).
authInfo( authInfo ).
repositoryId( SystemConstants.SYSTEM_REPO_ID ).
branch( SecurityConstants.BRANCH_SECURITY ).build().
callWith( runnable );
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private void createSession( final AuthenticationInfo authInfo )
{
final Session session = this.context.get().getLocalScope().getSession();
if ( session != null )
{
session.setAttribute( authInfo );
}
if ( this.sessionTimeout != null )
{
setSessionTimeout();
}
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private IdProviders getSortedIdProviders()
{
IdProviders idProviders = securityService.get().getIdProviders();
return IdProviders.from( idProviders.stream().
sorted( Comparator.comparing( u -> u.getKey().toString() ) ).
collect( Collectors.toList() ) );
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private <T> T runAsAuthenticated( Callable<T> runnable )
{
final AuthenticationInfo authInfo = AuthenticationInfo.create().principals( RoleKeys.AUTHENTICATED ).user( User.ANONYMOUS ).build();
return ContextBuilder.from( this.context.get() ).
authInfo( authInfo ).
repositoryId( SystemConstants.SYSTEM_REPO_ID ).
branch( SecurityConstants.BRANCH_SECURITY ).build().
callWith( runnable );
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private void createSession( final AuthenticationInfo authInfo )
{
final Session session = this.context.get().getLocalScope().getSession();
if ( session != null )
{
session.setAttribute( authInfo );
}
if ( this.sessionTimeout != null )
{
setSessionTimeout();
}
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private IdProviders getSortedIdProviders()
{
IdProviders idProviders = securityService.get().getIdProviders();
return IdProviders.from( idProviders.stream().
sorted( Comparator.comparing( u -> u.getKey().toString() ) ).
collect( Collectors.toList() ) );
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private boolean isStackFrameNotWhitelisted(StackTraceElement ste) {
return isCallNotWhitelisted(ste.getClassName());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private boolean isStackFrameNotWhitelisted(StackFrame sf) {
return isCallNotWhitelisted(sf.getClassName());
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
private boolean isCallNotWhitelisted(String call) {
return SecurityConstants.STACK_BLACKLIST.stream().anyMatch(call::startsWith)
|| (SecurityConstants.STACK_WHITELIST.stream().noneMatch(call::startsWith)
&& (configuration == null || !(configuration.whitelistedClassNames().contains(call)
|| configuration.trustedPackages().stream().anyMatch(pm -> pm.matches(call)))));
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
def _configure_templating(cls, app):
tempdir = app.config["PYLOAD_API"].get_cachedir()
cache_path = os.path.join(tempdir, "jinja")
os.makedirs(cache_path, exist_ok=True)
app.create_jinja_environment()
# NOTE: enable auto escape for all file extensions (including .js)
# maybe this will break .txt rendering, but we don't render this kind of files actually
# that does not change 'default_for_string=False' (by default)
app.jinja_env.autoescape = jinja2.select_autoescape(default=True)
app.jinja_env.bytecode_cache = jinja2.FileSystemBytecodeCache(cache_path)
for fn in cls.JINJA_TEMPLATE_FILTERS:
app.add_template_filter(fn)
for fn in cls.JINJA_TEMPLATE_GLOBALS:
app.add_template_global(fn)
for fn in cls.JINJA_CONTEXT_PROCESSORS:
app.context_processor(fn) | 1 | Python | CWE-319 | Cleartext Transmission of Sensitive Information | The product transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors. | https://cwe.mitre.org/data/definitions/319.html | safe |
def _configure_session(cls, app):
tempdir = app.config["PYLOAD_API"].get_cachedir()
cache_path = os.path.join(tempdir, "flask")
os.makedirs(cache_path, exist_ok=True)
app.config["SESSION_FILE_DIR"] = cache_path
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_COOKIE_NAME"] = "pyload_session"
app.config["SESSION_COOKIE_SECURE"] = app.config["PYLOAD_API"].get_config_value("webui", "use_ssl")
app.config["SESSION_PERMANENT"] = False
session_lifetime = max(app.config["PYLOAD_API"].get_config_value("webui", "session_lifetime"), 1) * 60
app.config["PERMANENT_SESSION_LIFETIME"] = session_lifetime | 1 | Python | CWE-319 | Cleartext Transmission of Sensitive Information | The product transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors. | https://cwe.mitre.org/data/definitions/319.html | safe |
def _configure_handlers(cls, app):
"""
Register app handlers.
"""
for exc, fn in cls.FLASK_ERROR_HANDLERS:
app.register_error_handler(exc, fn)
@app.after_request
def deny_iframe(response):
response.headers["X-Frame-Options"] = "DENY"
return response | 1 | Python | CWE-1021 | Improper Restriction of Rendered UI Layers or Frames | The web application does not restrict or incorrectly restricts frame objects or UI layers that belong to another application or domain, which can lead to user confusion about which interface the user is interacting with. | https://cwe.mitre.org/data/definitions/1021.html | safe |
def deny_iframe(response):
response.headers["X-Frame-Options"] = "DENY"
return response | 1 | Python | CWE-1021 | Improper Restriction of Rendered UI Layers or Frames | The web application does not restrict or incorrectly restricts frame objects or UI layers that belong to another application or domain, which can lead to user confusion about which interface the user is interacting with. | https://cwe.mitre.org/data/definitions/1021.html | safe |
def get_events(self, uuid):
"""
Lists occurred events, may be affected to changes in the future.
:param uuid:
:return: list of `Events`
"""
events = self.pyload.event_manager.get_events(uuid)
new_events = []
def conv_dest(d):
return (Destination.QUEUE if d == "queue" else Destination.COLLECTOR).value
for e in events:
event = EventInfo()
event.eventname = e[0]
if e[0] in ("update", "remove", "insert"):
event.id = e[3]
event.type = (
ElementType.PACKAGE if e[2] == "pack" else ElementType.FILE
).value
event.destination = conv_dest(e[1])
elif e[0] == "order":
if e[1]:
event.id = e[1]
event.type = (
ElementType.PACKAGE if e[2] == "pack" else ElementType.FILE
)
event.destination = conv_dest(e[3])
elif e[0] == "reload":
event.destination = conv_dest(e[1])
new_events.append(event)
return new_events | 1 | Python | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | safe |
def user_exists(self, username):
"""
Check if a user actually exists in the database.
:param username:
:return: boolean
"""
return self.pyload.db.user_exists(username) | 1 | Python | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | safe |
def user_exists(self, user):
self.c.execute("SELECT name FROM users WHERE name=?", (user,))
return self.c.fetchone() is not None | 1 | Python | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | safe |
def is_authenticated(session=flask.session):
api = flask.current_app.config["PYLOAD_API"]
user = session.get("name")
authenticated = session.get("authenticated")
return authenticated and api.user_exists(user) | 1 | Python | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | safe |
def cast(self, typ, value):
"""
cast value to given format.
"""
if typ == "int":
return int(value)
elif typ == "float":
return float(value)
elif typ == "str":
return "" if value is None else str(value)
elif typ == "bytes":
return b"" if value is None else bytes(value)
elif typ == "bool":
value = "" if value is None else str(value)
return value.lower() in ("1", "true", "on", "yes", "y")
elif typ == "time":
default_value = "0:00"
value = "" if value is None else str(value)
if not value:
value = default_value
elif ":" not in value:
value += ":00"
hours, seconds = value.split(":", 1)
if (
hours.isnumeric()
and seconds.isnumeric()
and 0 <= int(hours) <= 23
and 0 <= int(seconds) <= 59
):
pass
else:
value = default_value
return value
elif typ in ("file", "folder"):
return (
""
if value in (None, "")
else os.path.realpath(os.path.expanduser(os.fsdecode(value)))
)
else:
return value | 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 init_handle(self):
"""
sets common options to curl handle.
"""
self.c.setopt(pycurl.FOLLOWLOCATION, 1)
self.c.setopt(pycurl.MAXREDIRS, 10)
self.c.setopt(pycurl.CONNECTTIMEOUT, 30)
self.c.setopt(pycurl.NOSIGNAL, 1)
self.c.setopt(pycurl.NOPROGRESS, 1)
if hasattr(pycurl, "AUTOREFERER"):
self.c.setopt(pycurl.AUTOREFERER, 1)
self.c.setopt(pycurl.SSL_VERIFYPEER, 1)
self.c.setopt(pycurl.LOW_SPEED_TIME, 60)
self.c.setopt(pycurl.LOW_SPEED_LIMIT, 5)
if hasattr(pycurl, "USE_SSL"):
self.c.setopt(pycurl.USE_SSL, pycurl.USESSL_TRY)
# self.c.setopt(pycurl.VERBOSE, 1)
# self.c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_1)
self.c.setopt(
pycurl.USERAGENT,
b"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0",
)
if pycurl.version_info()[7]:
self.c.setopt(pycurl.ENCODING, b"gzip, deflate")
self.c.setopt(
pycurl.HTTPHEADER,
[
b"Accept: */*",
b"Accept-Language: en-US,en",
b"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
b"Connection: keep-alive",
b"Keep-Alive: 300",
b"Expect:",
],
) | 1 | Python | CWE-295 | Improper Certificate Validation | The product does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def set_interface(self, options):
options = {
k: v.encode() if hasattr(v, "encode") else v for k, v in options.items()
}
interface, proxy, ipv6 = (
options["interface"],
options["proxies"],
options["ipv6"],
)
if interface and interface.lower() != "none":
self.c.setopt(pycurl.INTERFACE, interface)
if proxy:
if proxy["type"] == "http":
self.c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_HTTP)
elif proxy["type"] == "https":
self.c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_HTTPS)
self.c.setopt(pycurl.PROXY_SSL_VERIFYPEER, 0)
elif proxy["type"] == "socks4":
self.c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS4)
elif proxy["type"] == "socks5":
self.c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
self.c.setopt(pycurl.PROXY, proxy["host"])
self.c.setopt(pycurl.PROXYPORT, int(proxy["port"]))
if proxy["username"]:
user = proxy["username"]
pw = proxy["password"]
self.c.setopt(pycurl.PROXYUSERPWD, f"{user}:{pw}".encode())
if ipv6:
self.c.setopt(pycurl.IPRESOLVE, pycurl.IPRESOLVE_WHATEVER)
else:
self.c.setopt(pycurl.IPRESOLVE, pycurl.IPRESOLVE_V4)
if "auth" in options:
self.c.setopt(pycurl.USERPWD, options["auth"])
if "timeout" in options:
self.c.setopt(pycurl.LOW_SPEED_TIME, int(options["timeout"]))
if "ssl_verify" in options:
self.c.setopt(pycurl.SSL_VERIFYPEER, 1 if options["ssl_verify"] else 0) | 1 | Python | CWE-295 | Improper Certificate Validation | The product does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def get_options(self):
"""
returns options needed for pycurl.
"""
return {
"interface": self.iface(),
"proxies": self.get_proxies(),
"ipv6": self.pyload.config.get("download", "ipv6"),
"ssl_verify": self.pyload.config.get("general", "ssl_verify"),
} | 1 | Python | CWE-295 | Improper Certificate Validation | The product does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def info():
api = flask.current_app.config["PYLOAD_API"]
conf = api.get_config_dict()
extra = os.uname() if hasattr(os, "uname") else tuple()
context = {
"python": sys.version,
"os": " ".join((os.name, sys.platform) + extra),
"version": api.get_server_version(),
"folder": PKGDIR,
"config_folder": api.get_userdir(),
"download": conf["general"]["storage_folder"]["value"],
"freespace": format.size(api.free_space()),
"webif": conf["webui"]["port"]["value"],
"language": conf["general"]["language"]["value"],
}
return render_template("info.html", **context) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def login():
user = flask.request.form["username"]
password = flask.request.form["password"]
api = flask.current_app.config["PYLOAD_API"]
user_info = api.check_auth(user, password)
sanitized_user = user.replace("\n", "\\n").replace("\r", "\\r")
if not user_info:
log.error(f"Login failed for user '{sanitized_user}'")
return jsonify(False)
s = set_session(user_info)
log.info(f"User '{sanitized_user}' successfully logged in")
flask.flash("Logged in successfully")
return jsonify(s) | 1 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The product 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 login():
api = flask.current_app.config["PYLOAD_API"]
next = get_redirect_url(fallback=flask.url_for("app.dashboard"))
if flask.request.method == "POST":
user = flask.request.form["username"]
password = flask.request.form["password"]
user_info = api.check_auth(user, password)
sanitized_user = user.replace("\n", "\\n").replace("\r", "\\r")
if not user_info:
log.error(f"Login failed for user '{sanitized_user}'")
return render_template("login.html", next=next, errors=True)
set_session(user_info)
log.info(f"User '{sanitized_user}' successfully logged in")
flask.flash("Logged in successfully")
if is_authenticated():
return flask.redirect(next)
if api.get_config_value("webui", "autologin"):
allusers = api.get_all_userdata()
if len(allusers) == 1: # TODO: check if localhost
user_info = list(allusers.values())[0]
set_session(user_info)
# NOTE: Double-check authentication here because if session[name] is empty,
# next login_required redirects here again and all loop out.
if is_authenticated():
return flask.redirect(next)
return render_template("login.html", next=next) | 1 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The product 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 _configure_session(cls, app):
tempdir = app.config["PYLOAD_API"].get_cachedir()
cache_path = os.path.join(tempdir, "flask")
os.makedirs(cache_path, exist_ok=True)
app.config["SESSION_FILE_DIR"] = cache_path
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_COOKIE_NAME"] = "pyload_session"
app.config["SESSION_COOKIE_SAMESITE"] = "None"
app.config["SESSION_COOKIE_SECURE"] = app.config["PYLOAD_API"].get_config_value("webui", "use_ssl")
app.config["SESSION_PERMANENT"] = False
session_lifetime = max(app.config["PYLOAD_API"].get_config_value("webui", "session_lifetime"), 1) * 60
app.config["PERMANENT_SESSION_LIFETIME"] = session_lifetime | 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 _configure_session(cls, app):
tempdir = app.config["PYLOAD_API"].get_cachedir()
cache_path = os.path.join(tempdir, "flask")
os.makedirs(cache_path, exist_ok=True)
app.config["SESSION_FILE_DIR"] = cache_path
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_COOKIE_NAME"] = "pyload_session"
app.config["SESSION_COOKIE_SAMESITE"] = "Strict"
app.config["SESSION_COOKIE_SECURE"] = app.config["PYLOAD_API"].get_config_value("webui", "use_ssl")
app.config["SESSION_PERMANENT"] = False
session_lifetime = max(app.config["PYLOAD_API"].get_config_value("webui", "session_lifetime"), 1) * 60
app.config["PERMANENT_SESSION_LIFETIME"] = session_lifetime | 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 has_permission(self, request, view):
return request.user.is_superuser | 1 | Python | CWE-285 | Improper Authorization | The product does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/285.html | safe |
def clean(self):
super().clean()
if self.errors:
return self.cleaned_data
oldpassword = self.cleaned_data.get("oldpassword")
newpassword = self.cleaned_data.get("newpassword")
confirmation = self.cleaned_data.get("confirmation")
if newpassword and confirmation:
if oldpassword:
if newpassword != confirmation:
self.add_error("confirmation", _("Passwords mismatch"))
else:
password_validation.validate_password(
confirmation, self.instance)
else:
self.add_error("oldpassword", _("This field is required."))
elif newpassword or confirmation:
if not confirmation:
self.add_error("confirmation", _("This field is required."))
else:
self.add_error("newpassword", _("This field is required."))
return self.cleaned_data | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def test_update_password(self):
"""Password update
Two cases:
* The default admin changes his password (no associated Mailbox)
* A normal user changes his password
"""
self.ajax_post(reverse("core:user_profile"),
{"language": "en", "oldpassword": "password",
"newpassword": "12345Toi", "confirmation": "12345Toi"})
self.client.logout()
self.assertEqual(
self.client.login(username="admin", password="12345Toi"), True
)
self.assertEqual(
self.client.login(username="[email protected]", password="toto"), True
)
self.ajax_post(
reverse("core:user_profile"),
{"oldpassword": "toto",
"confirmation": "tutu"},
status=400
)
self.ajax_post(
reverse("core:user_profile"),
{"oldpassword": "toto",
"newpassword": "tutu", "confirmation": "tutu"},
status=400
)
self.ajax_post(
reverse("core:user_profile"),
{"language": "en", "oldpassword": "toto",
"newpassword": "Toto1234", "confirmation": "Toto1234"}
)
self.client.logout()
self.assertTrue(
self.client.login(username="[email protected]", password="Toto1234")
) | 1 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | safe |
def clean_identity(self):
v = self.cleaned_data["identity"]
if not TokenBucket.authorize_login_email(v):
raise forms.ValidationError("Too many attempts, please try later.")
try:
self.user = User.objects.get(email=v)
except User.DoesNotExist:
self.user = None
return v | 1 | Python | 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 | safe |
def test_it_handles_unknown_email(self):
form = {"identity": "[email protected]"}
r = self.client.post("/accounts/login/", form)
self.assertRedirects(r, "/accounts/login_link_sent/")
self.assertIn("auto-login", r.cookies)
# There should be no sent emails.
self.assertEqual(len(mail.outbox), 0) | 1 | Python | 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 | safe |
def test_it_handles_existing_users(self):
alice = User(username="alice", email="[email protected]")
alice.save()
form = {"identity": "[email protected]", "tz": ""}
r = self.client.post("/accounts/signup/", form)
self.assertContains(r, "check your email")
self.assertIn("auto-login", r.cookies)
# It should not send an email
self.assertEqual(len(mail.outbox), 0) | 1 | Python | 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 | safe |
def test_it_ignores_bad_tz(self):
form = {"identity": "[email protected]", "tz": "Foo/Bar"}
r = self.client.post("/accounts/signup/", form)
self.assertContains(r, "check your email")
self.assertIn("auto-login", r.cookies)
profile = Profile.objects.get()
self.assertEqual(profile.tz, "UTC") | 1 | Python | 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 | safe |
def test_it_works(self):
form = {"identity": "[email protected]", "tz": "Europe/Riga"}
r = self.client.post("/accounts/signup/", form)
self.assertContains(r, "check your email")
self.assertIn("auto-login", r.cookies)
# An user should have been created
user = User.objects.get()
# A profile should have been created
profile = Profile.objects.get()
self.assertEqual(profile.check_limit, 10000)
self.assertEqual(profile.sms_limit, 10000)
self.assertEqual(profile.call_limit, 10000)
self.assertEqual(profile.tz, "Europe/Riga")
# And email sent
self.assertEqual(len(mail.outbox), 1)
subject = "Log in to %s" % settings.SITE_NAME
self.assertEqual(mail.outbox[0].subject, subject)
# A project should have been created
project = Project.objects.get()
self.assertEqual(project.owner, user)
self.assertEqual(project.badge_key, user.username)
# And check should be associated with the new user
check = Check.objects.get()
self.assertEqual(check.name, "My First Check")
self.assertEqual(check.slug, "my-first-check")
self.assertEqual(check.project, project)
# A channel should have been created
channel = Channel.objects.get()
self.assertEqual(channel.project, project) | 1 | Python | 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 | safe |
def login(request):
form = forms.PasswordLoginForm()
magic_form = forms.EmailLoginForm()
if request.method == "POST":
if request.POST.get("action") == "login":
form = forms.PasswordLoginForm(request.POST)
if form.is_valid():
return _check_2fa(request, form.user)
else:
magic_form = forms.EmailLoginForm(request.POST)
if magic_form.is_valid():
redirect_url = request.GET.get("next")
if not _allow_redirect(redirect_url):
redirect_url = None
if magic_form.user:
profile = Profile.objects.for_user(magic_form.user)
profile.send_instant_login_link(redirect_url=redirect_url)
response = redirect("hc-login-link-sent")
# check_token looks for this cookie to decide if
# it needs to do the extra POST step.
response.set_cookie("auto-login", "1", max_age=300, httponly=True)
return response
if request.user.is_authenticated:
return _redirect_after_login(request)
bad_link = request.session.pop("bad_link", None)
ctx = {
"page": "login",
"form": form,
"magic_form": magic_form,
"bad_link": bad_link,
"registration_open": settings.REGISTRATION_OPEN,
"support_email": settings.SUPPORT_EMAIL,
}
return render(request, "accounts/login.html", ctx) | 1 | Python | 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 | safe |
def signup(request):
if not settings.REGISTRATION_OPEN:
return HttpResponseForbidden()
ctx = {}
form = forms.SignupForm(request.POST)
if form.is_valid():
email = form.cleaned_data["identity"]
if not User.objects.filter(email=email).exists():
tz = form.cleaned_data["tz"]
user = _make_user(email, tz)
profile = Profile.objects.for_user(user)
profile.send_instant_login_link()
else:
ctx = {"form": form}
response = render(request, "accounts/signup_result.html", ctx)
if "form" not in ctx:
response.set_cookie("auto-login", "1", max_age=300, httponly=True)
return response | 1 | Python | 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 | safe |
def _validate_model_name(name):
_original_validate_model_name(name)
if contains_path_separator(name):
raise MlflowException(
f"Invalid name: '{name}'. Registered model name cannot contain path separator",
INVALID_PARAMETER_VALUE,
) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def contains_path_separator(path):
"""
Returns True if a path contains a path separator, False otherwise.
"""
return any((sep in path) for sep in (os.path.sep, os.path.altsep) if sep is not None) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def test_create_registered_model_with_name_that_looks_like_path(store, tmp_path):
name = str(tmp_path.joinpath("test"))
with pytest.raises(
MlflowException, match=r"Registered model name cannot contain path separator"
):
store.get_registered_model(name) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def _validate_source(source: str, run_id: str) -> None:
if is_local_uri(source):
if run_id:
store = _get_tracking_store()
run = store.get_run(run_id)
source = pathlib.Path(local_file_uri_to_path(source)).resolve()
run_artifact_dir = pathlib.Path(local_file_uri_to_path(run.info.artifact_uri)).resolve()
if run_artifact_dir in [source, *source.parents]:
return
raise MlflowException(
f"Invalid model version source: '{source}'. To use a local path as a model version "
"source, the run_id request parameter has to be specified and the local path has to be "
"contained within the artifact directory of the run specified by the run_id.",
INVALID_PARAMETER_VALUE,
)
# There might be file URIs that are local but can bypass the above check. To prevent this, we
# disallow using file URIs as model version sources by default unless it's explicitly allowed
# by setting the MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE environment variable to True.
if not MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE.get() and is_file_uri(source):
raise MlflowException(
f"Invalid model version source: '{source}'. MLflow tracking server doesn't allow using "
"a file URI as a model version source for security reasons. To disable this check, set "
f"the {MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE.name} environment variable to "
"True.",
INVALID_PARAMETER_VALUE,
) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def is_file_uri(uri):
return urllib.parse.urlparse(uri).scheme == "file" | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def is_local_uri(uri):
"""Returns true if this is a local file path (/foo or file:/foo)."""
if uri == "databricks":
return False
if is_windows() and uri.startswith("\\\\"):
# windows network drive path looks like: "\\<server name>\path\..."
return False
parsed_uri = urllib.parse.urlparse(uri)
if parsed_uri.hostname and not (
parsed_uri.hostname == "."
or parsed_uri.hostname.startswith("localhost")
or parsed_uri.hostname.startswith("127.0.0.1")
):
return False
scheme = parsed_uri.scheme
if scheme == "" or scheme == "file":
return True
if is_windows() and len(scheme) == 1 and scheme.lower() == pathlib.Path(uri).drive.lower()[0]:
return True
return False | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def _init_server(backend_uri, root_artifact_uri, extra_env=None):
"""
Launch a new REST server using the tracking store specified by backend_uri and root artifact
directory specified by root_artifact_uri.
:returns A tuple (url, process) containing the string URL of the server and a handle to the
server process (a multiprocessing.Process object).
"""
mlflow.set_tracking_uri(None)
server_port = get_safe_port()
process = Popen(
[
sys.executable,
"-c",
f'from mlflow.server import app; app.run("{LOCALHOST}", {server_port})',
],
env={
**os.environ,
BACKEND_STORE_URI_ENV_VAR: backend_uri,
ARTIFACT_ROOT_ENV_VAR: root_artifact_uri,
**(extra_env or {}),
},
)
_await_server_up_or_die(server_port)
url = f"http://{LOCALHOST}:{server_port}"
_logger.info(f"Launching tracking server against backend URI {backend_uri}. Server URL: {url}")
return url, process | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_create_model_version_with_file_uri_env_var(tmp_path):
backend_uri = tmp_path.joinpath("file").as_uri()
url, process = _init_server(
backend_uri,
root_artifact_uri=tmp_path.as_uri(),
extra_env={"MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE": "true"},
)
try:
mlflow_client = MlflowClient(url)
name = "test"
mlflow_client.create_registered_model(name)
exp_id = mlflow_client.create_experiment("test")
run = mlflow_client.create_run(experiment_id=exp_id)
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": "file://123.456.789.123/path/to/source",
"run_id": run.info.run_id,
},
)
assert response.status_code == 200
finally:
_terminate_server(process) | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_create_model_version_with_path_source(mlflow_client):
name = "mode"
mlflow_client.create_registered_model(name)
exp_id = mlflow_client.create_experiment("test")
run = mlflow_client.create_run(experiment_id=exp_id)
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
"run_id": run.info.run_id,
},
)
assert response.status_code == 200
# run_id is not specified
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"]
# run_id is specified but source is not in the run's artifact directory
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": "/tmp",
"run_id": run.info.run_id,
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"] | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def test_is_local_uri():
assert is_local_uri("mlruns")
assert is_local_uri("./mlruns")
assert is_local_uri("file:///foo/mlruns")
assert is_local_uri("file:foo/mlruns")
assert is_local_uri("file://./mlruns")
assert is_local_uri("file://localhost/mlruns")
assert is_local_uri("file://localhost:5000/mlruns")
assert is_local_uri("file://127.0.0.1/mlruns")
assert is_local_uri("file://127.0.0.1:5000/mlruns")
assert not is_local_uri("file://myhostname/path/to/file")
assert not is_local_uri("https://whatever")
assert not is_local_uri("http://whatever")
assert not is_local_uri("databricks")
assert not is_local_uri("databricks:whatever")
assert not is_local_uri("databricks://whatever") | 1 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | safe |
def _validate_non_local_source_contains_relative_paths(source: str):
"""
Validation check to ensure that sources that are provided that conform to the schemes:
http, https, or mlflow-artifacts do not contain relative path designations that are intended
to access local file system paths on the tracking server.
Example paths that this validation function is intended to find and raise an Exception if
passed:
"mlflow-artifacts://host:port/../../../../"
"http://host:port/api/2.0/mlflow-artifacts/artifacts/../../../../"
"https://host:port/api/2.0/mlflow-artifacts/artifacts/../../../../"
"/models/artifacts/../../../"
"s3:/my_bucket/models/path/../../other/path"
"file://path/to/../../../../some/where/you/should/not/be"
"""
source_path = urllib.parse.urlparse(source).path
resolved_source = pathlib.Path(source_path).resolve().as_posix()
# NB: drive split is specifically for Windows since WindowsPath.resolve() will append the
# drive path of the pwd to a given path. We don't care about the drive here, though.
_, resolved_path = os.path.splitdrive(resolved_source)
if resolved_path != source_path:
raise MlflowException(
f"Invalid model version source: '{source}'. If supplying a source as an http, https, "
"local file path, ftp, objectstore, or mlflow-artifacts uri, an absolute path must be "
"provided without relative path references present. Please provide an absolute path.",
INVALID_PARAMETER_VALUE,
) | 1 | Python | CWE-23 | Relative Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/23.html | safe |
def _validate_source(source: str, run_id: str) -> None:
if is_local_uri(source):
if run_id:
store = _get_tracking_store()
run = store.get_run(run_id)
source = pathlib.Path(local_file_uri_to_path(source)).resolve()
run_artifact_dir = pathlib.Path(local_file_uri_to_path(run.info.artifact_uri)).resolve()
if run_artifact_dir in [source, *source.parents]:
return
raise MlflowException(
f"Invalid model version source: '{source}'. To use a local path as a model version "
"source, the run_id request parameter has to be specified and the local path has to be "
"contained within the artifact directory of the run specified by the run_id.",
INVALID_PARAMETER_VALUE,
)
# There might be file URIs that are local but can bypass the above check. To prevent this, we
# disallow using file URIs as model version sources by default unless it's explicitly allowed
# by setting the MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE environment variable to True.
if not MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE.get() and is_file_uri(source):
raise MlflowException(
f"Invalid model version source: '{source}'. MLflow tracking server doesn't allow using "
"a file URI as a model version source for security reasons. To disable this check, set "
f"the {MLFLOW_ALLOW_FILE_URI_AS_MODEL_VERSION_SOURCE.name} environment variable to "
"True.",
INVALID_PARAMETER_VALUE,
)
# Checks if relative paths are present in the source (a security threat). If any are present,
# raises an Exception.
_validate_non_local_source_contains_relative_paths(source) | 1 | Python | CWE-23 | Relative Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/23.html | safe |
def test_create_model_version_with_path_source(mlflow_client):
name = "model"
mlflow_client.create_registered_model(name)
exp_id = mlflow_client.create_experiment("test")
run = mlflow_client.create_run(experiment_id=exp_id)
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
"run_id": run.info.run_id,
},
)
assert response.status_code == 200
# run_id is not specified
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"]
# run_id is specified but source is not in the run's artifact directory
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": "/tmp",
"run_id": run.info.run_id,
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"] | 1 | Python | CWE-23 | Relative Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/23.html | safe |
def main():
args = parse_args()
_predict(
model_uri=args.model_uri,
input_path=args.input_path if args.input_path else None,
output_path=args.output_path if args.output_path else None,
content_type=args.content_type,
) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def main():
args = parse_args()
_predict(
model_uri=args.model_uri,
input_path=args.input_path if args.input_path else None,
output_path=args.output_path if args.output_path else None,
content_type=args.content_type,
) | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model-uri", required=True)
parser.add_argument("--input-path", required=False)
parser.add_argument("--output-path", required=False)
parser.add_argument("--content-type", required=True)
return parser.parse_args() | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model-uri", required=True)
parser.add_argument("--input-path", required=False)
parser.add_argument("--output-path", required=False)
parser.add_argument("--content-type", required=True)
return parser.parse_args() | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def predict(self, model_uri, input_path, output_path, content_type):
"""
Generate predictions using generic python model saved with MLflow. The expected format of
the input JSON is the Mlflow scoring format.
Return the prediction results as a JSON.
"""
local_path = _download_artifact_from_uri(model_uri)
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
local_uri = path_to_local_file_uri(local_path)
if self._env_manager != _EnvManager.LOCAL:
predict_cmd = [
"python",
_mlflow_pyfunc_backend_predict.__file__,
"--model-uri",
str(local_uri),
"--content-type",
shlex.quote(str(content_type)),
]
if input_path:
predict_cmd += ["--input-path", shlex.quote(str(input_path))]
if output_path:
predict_cmd += ["--output-path", shlex.quote(str(output_path))]
return self.prepare_env(local_path).execute(" ".join(predict_cmd))
else:
scoring_server._predict(local_uri, input_path, output_path, content_type) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def predict(self, model_uri, input_path, output_path, content_type):
"""
Generate predictions using generic python model saved with MLflow. The expected format of
the input JSON is the Mlflow scoring format.
Return the prediction results as a JSON.
"""
local_path = _download_artifact_from_uri(model_uri)
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
local_uri = path_to_local_file_uri(local_path)
if self._env_manager != _EnvManager.LOCAL:
predict_cmd = [
"python",
_mlflow_pyfunc_backend_predict.__file__,
"--model-uri",
str(local_uri),
"--content-type",
shlex.quote(str(content_type)),
]
if input_path:
predict_cmd += ["--input-path", shlex.quote(str(input_path))]
if output_path:
predict_cmd += ["--output-path", shlex.quote(str(output_path))]
return self.prepare_env(local_path).execute(" ".join(predict_cmd))
else:
scoring_server._predict(local_uri, input_path, output_path, content_type) | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def get_cmd(
model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None
) -> Tuple[str, Dict[str, str]]:
local_uri = path_to_local_file_uri(model_uri)
timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get()
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
if not is_windows():
args = [f"--timeout={timeout}"]
if port and host:
address = shlex.quote(f"{host}:{port}")
args.append(f"-b {address}")
elif host:
args.append(f"-b {shlex.quote(host)}")
if nworkers:
args.append(f"-w {nworkers}")
command = (
f"gunicorn {' '.join(args)} ${{GUNICORN_CMD_ARGS}}"
" -- mlflow.pyfunc.scoring_server.wsgi:app"
)
else:
args = []
if host:
args.append(f"--host={shlex.quote(host)}")
if port:
args.append(f"--port={port}")
command = (
f"waitress-serve {' '.join(args)} "
"--ident=mlflow mlflow.pyfunc.scoring_server.wsgi:app"
)
command_env = os.environ.copy()
command_env[_SERVER_MODEL_PATH] = local_uri
return command, command_env | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def get_cmd(
model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None
) -> Tuple[str, Dict[str, str]]:
local_uri = path_to_local_file_uri(model_uri)
timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get()
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
if not is_windows():
args = [f"--timeout={timeout}"]
if port and host:
address = shlex.quote(f"{host}:{port}")
args.append(f"-b {address}")
elif host:
args.append(f"-b {shlex.quote(host)}")
if nworkers:
args.append(f"-w {nworkers}")
command = (
f"gunicorn {' '.join(args)} ${{GUNICORN_CMD_ARGS}}"
" -- mlflow.pyfunc.scoring_server.wsgi:app"
)
else:
args = []
if host:
args.append(f"--host={shlex.quote(host)}")
if port:
args.append(f"--port={port}")
command = (
f"waitress-serve {' '.join(args)} "
"--ident=mlflow mlflow.pyfunc.scoring_server.wsgi:app"
)
command_env = os.environ.copy()
command_env[_SERVER_MODEL_PATH] = local_uri
return command, command_env | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def test_host_invalid_value():
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, ctx, model_input):
return model_input
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
python_model=MyModel(), artifact_path="test_model", registered_model_name="model"
)
with mock.patch("mlflow.models.cli.get_flavor_backend", return_value=PyFuncBackend({})):
with pytest.raises(ShellCommandException, match=r"Non-zero exit code: 1"):
CliRunner().invoke(
models_cli.serve,
["--model-uri", model_info.model_uri, "--host", "localhost & echo BUG"],
catch_exceptions=False,
) | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def test_host_invalid_value():
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, ctx, model_input):
return model_input
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
python_model=MyModel(), artifact_path="test_model", registered_model_name="model"
)
with mock.patch("mlflow.models.cli.get_flavor_backend", return_value=PyFuncBackend({})):
with pytest.raises(ShellCommandException, match=r"Non-zero exit code: 1"):
CliRunner().invoke(
models_cli.serve,
["--model-uri", model_info.model_uri, "--host", "localhost & echo BUG"],
catch_exceptions=False,
) | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def test_predict_check_output_path(iris_data, sk_model, tmp_path):
with mlflow.start_run():
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="impredicting")
model_registry_uri = "models:/impredicting/None"
input_json_path = tmp_path / "input.json"
input_csv_path = tmp_path / "input.csv"
output_json_path = tmp_path / "output.json"
x, _ = iris_data
with input_json_path.open("w") as f:
json.dump({"dataframe_split": pd.DataFrame(x).to_dict(orient="split")}, f)
pd.DataFrame(x).to_csv(input_csv_path, index=False)
prc = subprocess.run(
[
"mlflow",
"models",
"predict",
"-m",
model_registry_uri,
"-i",
input_json_path,
"-o",
f'{output_json_path}"; echo ThisIsABug! "',
"--env-manager",
"local",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env_with_tracking_uri(),
check=False,
text=True,
)
assert prc.returncode == 0
assert "ThisIsABug!" not in prc.stdout | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def test_predict_check_output_path(iris_data, sk_model, tmp_path):
with mlflow.start_run():
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="impredicting")
model_registry_uri = "models:/impredicting/None"
input_json_path = tmp_path / "input.json"
input_csv_path = tmp_path / "input.csv"
output_json_path = tmp_path / "output.json"
x, _ = iris_data
with input_json_path.open("w") as f:
json.dump({"dataframe_split": pd.DataFrame(x).to_dict(orient="split")}, f)
pd.DataFrame(x).to_csv(input_csv_path, index=False)
prc = subprocess.run(
[
"mlflow",
"models",
"predict",
"-m",
model_registry_uri,
"-i",
input_json_path,
"-o",
f'{output_json_path}"; echo ThisIsABug! "',
"--env-manager",
"local",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env_with_tracking_uri(),
check=False,
text=True,
)
assert prc.returncode == 0
assert "ThisIsABug!" not in prc.stdout | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def predict(self, ctx, model_input):
return model_input | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def predict(self, ctx, model_input):
return model_input | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def test_predict_check_content_type(iris_data, sk_model, tmp_path):
with mlflow.start_run():
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="impredicting")
model_registry_uri = "models:/impredicting/None"
input_json_path = tmp_path / "input.json"
input_csv_path = tmp_path / "input.csv"
output_json_path = tmp_path / "output.json"
x, _ = iris_data
with input_json_path.open("w") as f:
json.dump({"dataframe_split": pd.DataFrame(x).to_dict(orient="split")}, f)
pd.DataFrame(x).to_csv(input_csv_path, index=False)
# Throw errors for invalid content_type
prc = subprocess.run(
[
"mlflow",
"models",
"predict",
"-m",
model_registry_uri,
"-i",
input_json_path,
"-o",
output_json_path,
"-t",
"invalid",
"--env-manager",
"local",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env_with_tracking_uri(),
check=False,
)
assert prc.returncode != 0
assert "Unknown content type" in prc.stderr.decode("utf-8") | 1 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | safe |
def test_predict_check_content_type(iris_data, sk_model, tmp_path):
with mlflow.start_run():
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="impredicting")
model_registry_uri = "models:/impredicting/None"
input_json_path = tmp_path / "input.json"
input_csv_path = tmp_path / "input.csv"
output_json_path = tmp_path / "output.json"
x, _ = iris_data
with input_json_path.open("w") as f:
json.dump({"dataframe_split": pd.DataFrame(x).to_dict(orient="split")}, f)
pd.DataFrame(x).to_csv(input_csv_path, index=False)
# Throw errors for invalid content_type
prc = subprocess.run(
[
"mlflow",
"models",
"predict",
"-m",
model_registry_uri,
"-i",
input_json_path,
"-o",
output_json_path,
"-t",
"invalid",
"--env-manager",
"local",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env_with_tracking_uri(),
check=False,
)
assert prc.returncode != 0
assert "Unknown content type" in prc.stderr.decode("utf-8") | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def create_user():
content_type = request.headers.get("Content-Type")
if content_type == "application/x-www-form-urlencoded":
username = request.form["username"]
password = request.form["password"]
if store.has_user(username):
flash(f"Username has already been taken: {username}")
return alert(href=SIGNUP)
store.create_user(username, password)
flash(f"Successfully signed up user: {username}")
return alert(href=HOME)
elif content_type == "application/json":
username = _get_request_param("username")
password = _get_request_param("password")
user = store.create_user(username, password)
return make_response({"user": user.to_json()})
else:
message = (
"Invalid content type. Must be one of: "
"application/x-www-form-urlencoded, application/json"
)
return make_response(message, 400) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
def _get_request_json(flask_request=request):
_validate_content_type(flask_request, ["application/json"])
return flask_request.get_json(force=True, silent=True) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
def search_datasets_handler():
MAX_EXPERIMENT_IDS_PER_REQUEST = 20
_validate_content_type(request, ["application/json"])
experiment_ids = request.json.get("experiment_ids", [])
if not experiment_ids:
raise MlflowException(
message="SearchDatasets request must specify at least one experiment_id.",
error_code=INVALID_PARAMETER_VALUE,
)
if len(experiment_ids) > MAX_EXPERIMENT_IDS_PER_REQUEST:
raise MlflowException(
message=(
f"SearchDatasets request cannot specify more than {MAX_EXPERIMENT_IDS_PER_REQUEST}"
f" experiment_ids. Received {len(experiment_ids)} experiment_ids."
),
error_code=INVALID_PARAMETER_VALUE,
)
store = _get_tracking_store()
if hasattr(store, "_search_datasets"):
return {
"dataset_summaries": [
summary.to_dict() for summary in store._search_datasets(experiment_ids)
]
}
else:
return _not_implemented() | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
def _validate_content_type(flask_request, allowed_content_types: List[str]):
"""
Validates that the request content type is one of the allowed content types.
:param flask_request: Flask request object (flask.request)
:param allowed_content_types: A list of allowed content types
"""
if flask_request.method not in ["POST", "PUT"]:
return
if flask_request.content_type is None:
raise MlflowException(
message="Bad Request. Content-Type header is missing.",
error_code=INVALID_PARAMETER_VALUE,
)
# Remove any parameters e.g. "application/json; charset=utf-8" -> "application/json"
content_type = flask_request.content_type.split(";")[0]
if content_type not in allowed_content_types:
message = f"Bad Request. Content-Type must be one of {allowed_content_types}."
raise MlflowException(
message=message,
error_code=INVALID_PARAMETER_VALUE,
) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
def test_can_block_post_request_with_invalid_content_type():
request = mock.MagicMock()
request.method = "POST"
request.content_type = "text/plain"
request.get_json = mock.MagicMock()
request.get_json.return_value = {"name": "hello"}
with pytest.raises(MlflowException, match=r"Bad Request. Content-Type"):
_get_request_message(CreateExperiment(), flask_request=request) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
def test_can_parse_post_json_with_unknown_fields():
request = mock.MagicMock()
request.method = "POST"
request.content_type = "application/json"
request.get_json = mock.MagicMock()
request.get_json.return_value = {"name": "hello", "WHAT IS THIS FIELD EVEN": "DOING"}
msg = _get_request_message(CreateExperiment(), flask_request=request)
assert msg.name == "hello" | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.