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 |
---|---|---|---|---|---|---|---|
public boolean isScanOnBoot() {
return scanOnBoot.isOn();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void violationMessagesAreEscaped() {
assertThat(ConstraintViolations.format(validator.validate(new InjectionExample()))).containsExactly(
" ${'value'}",
"${'property'} ${'value'}",
"${'property'}[${'key'}] ${'value'}",
"${'property'}[1] ${'value'}"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
} | 0 | Java | 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 |
private static void validateHeaderNameElement(byte value) {
switch (value) {
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
case 0x00:
case '\t':
case '\n':
case 0x0b:
case '\f':
case '\r':
case ' ':
case ',':
case ':':
case ';':
case '=':
throw new IllegalArgumentException(
"a header name cannot contain the following prohibited characters: =,;: \\t\\r\\n\\v\\f: " +
value);
default:
// Check to see if the character is not an ASCII character, or invalid
if (value < 0) {
throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " + value);
}
}
} | 1 | Java | 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 |
public void testQuoteWorkingDirectoryAndExecutable()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/local/bin" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd /usr/local/bin && chmod", executable );
} | 0 | Java | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
protected void deactivateConversationContext(HttpServletRequest request) {
ConversationContext conversationContext = httpConversationContext();
if (conversationContext.isActive()) {
// Only deactivate the context if one is already active, otherwise we get Exceptions
if (conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
if (!lazyConversationContext.isInitialized()) {
// if this lazy conversation has not been touched yet, just deactivate it
lazyConversationContext.deactivate();
return;
}
}
boolean isTransient = conversationContext.getCurrentConversation().isTransient();
if (ConversationLogger.LOG.isTraceEnabled()) {
if (isTransient) {
ConversationLogger.LOG.cleaningUpTransientConversation();
} else {
ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
}
}
conversationContext.invalidate();
conversationContext.deactivate();
if (isTransient) {
conversationDestroyedEvent.fire(request);
}
}
} | 0 | Java | 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 | vulnerable |
public void setXMLReader(XMLReader reader) {
this.xmlReader = reader;
} | 1 | Java | 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 |
public static void serializeToStream(final OutputStream os, final Object payload) throws IOException {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(os);
oos.writeObject(payload);
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException ignore) {
// empty catch block
}
}
}
} | 0 | Java | 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 |
public String getHeader(String name) {
//logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
//logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
} | 0 | Java | 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 |
private static FileBoolean state(String name) {
return new FileBoolean(new File(getBaseDir(),name));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public HexStringConfidentialKey(String id, int length) {
super(id);
if (length%2!=0)
throw new IllegalArgumentException("length must be even: "+length);
this.length = length;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void testValidGroupIds() {
testInvalidGroupId("John-Doe",false);
testInvalidGroupId("Jane/Doe",false);
testInvalidGroupId("John.Doe",false);
testInvalidGroupId("Jane#Doe", false);
testInvalidGroupId("John@Döe.com", false);
testInvalidGroupId("JohnDoé", false);
} | 1 | Java | 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 |
private void testGeneration()
throws Exception
{
//
// ECDSA generation test
//
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Signature s = Signature.getInstance("ECDSA", "BC");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
EllipticCurve curve = new EllipticCurve(
new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECParameterSpec ecSpec = new ECParameterSpec(
curve,
ECPointUtil.decodePoint(curve, Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n
1); // h
g.initialize(ecSpec, new SecureRandom());
KeyPair p = g.generateKeyPair();
PrivateKey sKey = p.getPrivate();
PublicKey vKey = p.getPublic();
s.initSign(sKey);
s.update(data);
byte[] sigBytes = s.sign();
s = Signature.getInstance("ECDSA", "BC");
s.initVerify(vKey);
s.update(data);
if (!s.verify(sigBytes))
{
fail("ECDSA verification failed");
}
testKeyFactory((ECPublicKey)vKey, (ECPrivateKey)sKey);
testSerialise((ECPublicKey)vKey, (ECPrivateKey)sKey);
} | 0 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
public void handle(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
// Parse the incoming request as XML
SAXReader xmlReader = XML.getSafeSaxReader();
Document doc = xmlReader.read(request.getInputStream());
Element env = doc.getRootElement();
Element body = env.element("body");
// First handle any new subscriptions
List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>();
List<Element> elements = body.elements("subscribe");
for (Element e : elements)
{
requests.add(new SubscriptionRequest(e.attributeValue("topic")));
}
ServletLifecycle.beginRequest(request);
try
{
ServletContexts.instance().setRequest(request);
Manager.instance().initializeTemporaryConversation();
ServletLifecycle.resumeConversation(request);
for (SubscriptionRequest req : requests)
{
req.subscribe();
}
// Then handle any unsubscriptions
List<String> unsubscribeTokens = new ArrayList<String>();
elements = body.elements("unsubscribe");
for (Element e : elements)
{
unsubscribeTokens.add(e.attributeValue("token"));
}
for (String token : unsubscribeTokens)
{
RemoteSubscriber subscriber = SubscriptionRegistry.instance().
getSubscription(token);
if (subscriber != null)
{
subscriber.unsubscribe();
}
}
}
finally
{
Lifecycle.endRequest();
}
// Package up the response
marshalResponse(requests, response.getOutputStream());
} | 1 | Java | 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 |
public static void fillArticleInfo(Log data, HttpServletRequest request, String suffix) {
data.put("alias", data.get("alias") + suffix);
data.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + data.get("alias"));
data.put("noSchemeUrl", WebTools.getHomeUrlWithHost(request) + Constants.getArticleUri() + data.get("alias"));
data.put("typeUrl", WebTools.getHomeUrl(request) + Constants.getArticleUri() + "sort/" + data.get("typeAlias") + suffix);
Log lastLog = data.get("lastLog");
Log nextLog = data.get("nextLog");
nextLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + nextLog.get("alias") + suffix);
lastLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + lastLog.get("alias") + suffix);
//没有使用md的toc目录的文章才尝试使用系统提取的目录
if (data.getStr("markdown") != null && !data.getStr("markdown").toLowerCase().contains("[toc]")
&& !data.getStr("markdown").toLowerCase().contains("[tocm]")) {
//最基础的实现方式,若需要更强大的实现方式建议使用JavaScript完成(页面输入toc对象)
OutlineVO outlineVO = OutlineUtil.extractOutline(data.getStr("content"));
data.put("tocHtml", OutlineUtil.buildTocHtml(outlineVO, ""));
data.put("toc", outlineVO);
}
if (!new CommentService().isAllowComment()) {
data.set("canComment", false);
}
} | 0 | Java | 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 |
protected SAXContentHandler createContentHandler(XMLReader reader) {
return new SAXContentHandler(getDocumentFactory(), dispatchHandler);
} | 1 | Java | 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 |
protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException;
@Override
public abstract void send(PlainStreamElement element) throws NotConnectedException;
@Override
public abstract boolean isUsingCompression();
/**
* Establishes a connection to the XMPP server and performs an automatic login
* only if the previous connection state was logged (authenticated). It basically
* creates and maintains a connection to the server.
* <p>
* Listeners will be preserved from a previous connection.
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException
* @throws ConnectionException with detailed information about the failed connection.
* @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
*/
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException {
// Check if not already connected
throwAlreadyConnectedExceptionIfAppropriate();
// Reset the connection state
saslAuthentication.init();
saslFeatureReceived.init();
lastFeaturesReceived.init();
streamId = null;
// Perform the actual connection to the XMPP service
connectInternal();
return this;
} | 1 | Java | 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 |
public void fireUndeployEvent(HotDeployEvent hotDeployEvent) {
for (HotDeployListener hotDeployListener : _hotDeployListeners) {
try {
hotDeployListener.invokeUndeploy(hotDeployEvent);
}
catch (HotDeployException hde) {
_log.error(hde, hde);
}
}
_deployedServletContextNames.remove(
hotDeployEvent.getServletContextName());
PACLPolicyManager.unregister(hotDeployEvent.getContextClassLoader());
} | 0 | Java | 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 |
public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
return checkRestrictorService(CORS_CHECK,pOrigin,pIsStrictCheck);
} | 1 | Java | 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 |
public void addViolation(String propertyName, String key, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atKey(key)
.addConstraintViolation();
} | 0 | Java | 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 |
/*package*/ ApiTokenProperty(String seed) {
apiToken = Secret.fromString(seed);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private void markCookieAsHttpOnly(ServletContext context) {
try {
Method m;
try {
m = context.getClass().getMethod("getSessionCookieConfig");
} catch (NoSuchMethodException x) { // 3.0+
LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x);
return;
}
Object sessionCookieConfig = m.invoke(context);
// not exposing session cookie to JavaScript to mitigate damage caused by XSS
Class scc = Class.forName("javax.servlet.SessionCookieConfig");
Method setHttpOnly = scc.getMethod("setHttpOnly",boolean.class);
setHttpOnly.invoke(sessionCookieConfig,true);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set HTTP-only cookie flag", e);
}
} | 1 | Java | CWE-254 | 7PK - Security Features | Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. | https://cwe.mitre.org/data/definitions/254.html | safe |
public void setFeature(String name, boolean value) throws SAXException {
getXMLReader().setFeature(name, value);
} | 1 | Java | 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 |
public PersistentTask updateTask(Task task, Serializable runnableTask, Identity modifier, Date scheduledDate) {
PersistentTask ptask = dbInstance.getCurrentEntityManager()
.find(PersistentTask.class, task.getKey(), LockModeType.PESSIMISTIC_WRITE);
if(ptask != null) {
ptask.setLastModified(new Date());
ptask.setScheduledDate(scheduledDate);
ptask.setStatus(TaskStatus.newTask);
ptask.setStatusBeforeEditStr(null);
ptask.setTask(xstream.toXML(runnableTask));
ptask = dbInstance.getCurrentEntityManager().merge(ptask);
if(modifier != null) {
//add to the list of modifier
PersistentTaskModifier mod = new PersistentTaskModifier();
mod.setCreationDate(new Date());
mod.setModifier(modifier);
mod.setTask(ptask);
dbInstance.getCurrentEntityManager().persist(mod);
}
dbInstance.commit();
}
return ptask;
} | 0 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | vulnerable |
public String getHeader(String name) {
//logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
//logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
} | 0 | Java | 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 |
public DefaultConfidentialStore(File rootDir) throws IOException, InterruptedException {
this.rootDir = rootDir;
if (rootDir.mkdirs()) {
// protect this directory. but don't change the permission of the existing directory
// in case the administrator changed this.
new FilePath(rootDir).chmod(0700);
}
TextFile masterSecret = new TextFile(new File(rootDir,"master.key"));
if (!masterSecret.exists()) {
// we are only going to use small number of bits (since export control limits AES key length)
// but let's generate a long enough key anyway
masterSecret.write(Util.toHexString(randomBytes(128)));
}
this.masterKey = Util.toAes128Key(masterSecret.readTrim());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static String getOrderClause(Set<String> joinAliases, Set<String> functionAlias, String alias, Order order) {
String property = order.getProperty();
checkSortExpression(order);
if (functionAlias.contains(property)) {
return String.format("%s %s", property, toJpaDirection(order));
}
boolean qualifyReference = !property.contains("("); // ( indicates a function
for (String joinAlias : joinAliases) {
if (property.startsWith(joinAlias.concat("."))) {
qualifyReference = false;
break;
}
}
String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
: property;
String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;
return String.format("%s %s", wrapped, toJpaDirection(order));
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public void existingDocumentFromUITemplateSpecified() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&template=XWiki.MyTemplate
String templateDocumentFullName = "XWiki.MyTemplate";
DocumentReference templateDocumentReference =
new DocumentReference("MyTemplate", Arrays.asList("XWiki"), "xwiki");
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("template")).thenReturn("XWiki.MyTemplate");
// Mock the passed template document as existing.
mockTemplateDocumentExisting(templateDocumentFullName, templateDocumentReference);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating X.Y.WebHome and using the template specified in the request.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
} | 0 | Java | CWE-862 | Missing Authorization | The software does not perform an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/862.html | vulnerable |
public boolean isCorsAccessAllowed(String pOrigin) {
return cors;
} | 0 | Java | 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 |
public void translate(BlockPickRequestPacket packet, GeyserSession session) {
Vector3i vector = packet.getBlockPosition();
int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
// Block is air - chunk caching is probably off
if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
// Check for an item frame since the client thinks that's a block when it's an entity in Java
ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
if (entity != null) {
// Check to see if the item frame has an item in it first
if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
// Grab the item in the frame
InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
} else {
// Grab the frame as the item
InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
}
}
return;
}
InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
}
| 0 | Java | 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 |
final protected Style getStyle() {
return getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());
} | 0 | Java | 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 |
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null || !ICON_SIZE.matcher(qs).matches())
throw new ServletException();
Cookie cookie = new Cookie("iconSize", qs);
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
} | 0 | Java | 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 |
public void addElementQualified() {
Element root = DocumentHelper.createElement("root");
root.addElement("element>name", "http://example.com/namespace");
} | 1 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | safe |
public boolean isMergeAdjacentText() {
return mergeAdjacentText;
} | 1 | Java | 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 |
public void testArraySafeBitLength_OK()
throws JOSEException {
assertEquals( 8, ByteUtils.bitLength(new byte[1]));
assertEquals(16, ByteUtils.bitLength(new byte[2]));
assertEquals(32, ByteUtils.bitLength(new byte[4]));
assertEquals(64, ByteUtils.bitLength(new byte[8]));
} | 1 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
public String get() {
try {
if (secret==null) {
synchronized (this) {
if (secret==null) {
byte[] payload = load();
if (payload==null) {
payload = ConfidentialStore.get().randomBytes(length/2);
store(payload);
}
secret = Util.toHexString(payload).substring(0,length);
}
}
}
return secret;
} catch (IOException e) {
throw new Error("Failed to load the key: "+getId(),e);
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userID = request.getParameter("userID");
String newID = request.getParameter("newID");
if (newID != null && newID.matches(".*[&<>\"`']+.*")) {
throw new ServletException("User ID must not contain any HTML markup.");
}
// now save to the xml file
try {
UserManager userFactory = UserFactory.getInstance();
userFactory.renameUser(userID, newID);
} catch (Throwable e) {
throw new ServletException("Error renaming user " + userID + " to " + newID, e);
}
response.sendRedirect("list.jsp");
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
protected boolean isProbablePrime(BigInteger x)
{
int iterations = getNumberOfIterations(x.bitLength(), param.getCertainty());
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
} | 1 | Java | CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information. | https://cwe.mitre.org/data/definitions/327.html | safe |
/*package*/ Secret(String value, byte[] iv) {
this.value = value;
this.iv = iv;
} | 1 | Java | CWE-326 | Inadequate Encryption Strength | The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. | https://cwe.mitre.org/data/definitions/326.html | safe |
public byte[] engineGetIV()
{
if (engineSpec != null)
{
return engineSpec.getNonce();
}
return null;
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String groupName = request.getParameter("groupName");
String groupComment = request.getParameter("groupComment");
if (groupComment == null) {
groupComment = "";
}
if (groupName != null && groupName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (groupComment != null && groupComment.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group comment must not contain any HTML markup.");
}
boolean hasGroup = false;
try {
hasGroup = m_groupRepository.groupExists(groupName);
} catch (Throwable e) {
throw new ServletException("Can't determine if group " + groupName + " already exists in groups.xml.", e);
}
if (hasGroup) {
return new ModelAndView("admin/userGroupView/groups/newGroup", "action", "redo");
} else {
WebGroup newGroup = new WebGroup();
newGroup.setName(groupName);
newGroup.setComments(groupComment);
return editGroup(request, newGroup);
}
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
public void setFeature(String name, boolean value) throws SAXException {
getXMLReader().setFeature(name, value);
} | 0 | Java | 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 | vulnerable |
public void testIncludesUri() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "git://**" );
add( "**/repo/**" );
}};
Assert.assertFalse( includes( patterns, URI.create( "file:///Users/home" ) ) );
Assert.assertTrue( includes( patterns, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( includes( patterns, URI.create( "git://master@antpathmatcher" ) ) );
} | 1 | Java | 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 |
public void setupClientDefaults(ClientRepresentation clientRep, ClientModel newClient) {
SamlRepresentationAttributes rep = new SamlRepresentationAttributes(clientRep.getAttributes());
SamlClient client = new SamlClient(newClient);
if (clientRep.isStandardFlowEnabled() == null) newClient.setStandardFlowEnabled(true);
if (rep.getCanonicalizationMethod() == null) {
client.setCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE);
}
if (rep.getSignatureAlgorithm() == null) {
client.setSignatureAlgorithm(SignatureAlgorithm.RSA_SHA256);
}
if (rep.getNameIDFormat() == null) {
client.setNameIDFormat("username");
}
if (rep.getIncludeAuthnStatement() == null) {
client.setIncludeAuthnStatement(true);
}
if (rep.getForceNameIDFormat() == null) {
client.setForceNameIDFormat(false);
}
if (rep.getAllowEcpFlow() == null) {
client.setAllowECPFlow(false);
}
if (rep.getSamlServerSignature() == null) {
client.setRequiresRealmSignature(true);
}
if (rep.getForcePostBinding() == null) {
client.setForcePostBinding(true);
}
if (rep.getClientSignature() == null) {
client.setRequiresClientSignature(true);
}
if (client.requiresClientSignature() && client.getClientSigningCertificate() == null) {
CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(newClient.getClientId());
client.setClientSigningCertificate(info.getCertificate());
client.setClientSigningPrivateKey(info.getPrivateKey());
}
if (clientRep.isFrontchannelLogout() == null) {
newClient.setFrontchannelLogout(true);
}
client.setArtifactBindingIdentifierFrom(clientRep.getClientId());
} | 1 | Java | 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 | safe |
public void validateFail(ViolationCollector col) {
col.addViolation("${'value'}");
col.addViolation("$\\A{1+1}");
col.addViolation("{value}", Collections.singletonMap("value", "TEST"));
col.addViolation("${'property'}", "${'value'}");
col.addViolation("${'property'}", 1, "${'value'}");
col.addViolation("${'property'}", "${'key'}", "${'value'}");
} | 1 | Java | 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 |
public void setUp() throws Exception {
super.setUp();
TestUtil.createTempTable(con, "xmltab","x xml");
} | 0 | Java | 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 | vulnerable |
public PersistentTask createTask(String name, Serializable task,
Identity creator, OLATResource resource, String resSubPath, Date scheduledDate) {
PersistentTask ptask = new PersistentTask();
Date currentDate = new Date();
ptask.setCreationDate(currentDate);
ptask.setLastModified(currentDate);
ptask.setScheduledDate(scheduledDate);
ptask.setName(name);
ptask.setCreator(creator);
ptask.setResource(resource);
ptask.setResSubPath(resSubPath);
ptask.setStatus(TaskStatus.newTask);
ptask.setTask(xstream.toXML(task));
dbInstance.getCurrentEntityManager().persist(ptask);
return ptask;
} | 0 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | vulnerable |
public JsonBuilder setEscapeHtml(final boolean escapeHtml)
{
this.escapeHtml = escapeHtml;
return this;
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public PlayerBinary(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
super(code, skinParam, ruler, compact);
this.style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());
this.suggestedHeight = 30;
} | 0 | Java | 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 |
void getAllReturnsEmptyListForUnknownName() {
final HttpHeadersBase headers = newEmptyHeaders();
assertThat(headers.getAll("noname").size()).isEqualTo(0);
} | 1 | Java | 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 |
public RedirectView callback(@RequestParam(defaultValue = "/") String redirect,
@PathVariable String serverId,
@RequestParam String code,
@RequestParam String state,
HttpServletRequest request,
HttpSession session) throws UnsupportedEncodingException {
try {
String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
if (!state.equals(cachedState)) {
throw new BusinessException(ErrorType.STATE_ERROR.name());
}
oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));
} finally {
session.removeAttribute(STATE_SESSION_KEY);
}
} | 1 | Java | 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 |
public void headerMinusSignContentLengthValidationShouldPropagate() {
headerSignContentLengthValidationShouldPropagateWithEndStream(true, false);
} | 1 | Java | 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 |
protected void afterFeaturesReceived() throws NotConnectedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
send(new StartTls());
}
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
} | 1 | Java | 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 |
private ECFieldElement generateMultiplyInputB_OpenSSLBug()
{
int[] x = Nat256.create();
x[0] = RANDOM.nextInt() >>> 1;
x[3] = 1;
x[7] = -1;
return fe(Nat256.toBigInteger(x));
} | 1 | Java | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
public void translate(ServerBossBarPacket packet, GeyserSession session) {
BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
switch (packet.getAction()) {
case ADD:
long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);
session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
break;
case UPDATE_TITLE:
if (bossBar != null) bossBar.updateTitle(packet.getTitle());
break;
case UPDATE_HEALTH:
if (bossBar != null) bossBar.updateHealth(packet.getHealth());
break;
case REMOVE:
session.getEntityCache().removeBossBar(packet.getUuid());
break;
case UPDATE_STYLE:
case UPDATE_FLAGS:
//todo
}
} | 0 | Java | 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 |
private File tempFile() throws IOException {
String newpostfix;
String diskFilename = getDiskFilename();
if (diskFilename != null) {
newpostfix = '_' + diskFilename;
} else {
newpostfix = getPostfix();
}
File tmpFile;
if (getBaseDirectory() == null) {
// create a temporary file
tmpFile = PlatformDependent.createTempFile(getPrefix(), newpostfix, null);
} else {
tmpFile = PlatformDependent.createTempFile(getPrefix(), newpostfix, new File(
getBaseDirectory()));
}
if (deleteOnExit()) {
// See https://github.com/netty/netty/issues/10351
DeleteFileOnExitHook.add(tmpFile.getPath());
}
return tmpFile;
} | 1 | Java | CWE-379 | Creation of Temporary File in Directory with Insecure Permissions | The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. | https://cwe.mitre.org/data/definitions/379.html | safe |
public void translate(ServerEntityPositionPacket packet, GeyserSession session) {
Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
entity = session.getPlayerEntity();
}
if (entity == null) return;
entity.moveRelative(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), entity.getRotation(), packet.isOnGround());
} | 0 | Java | 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 |
public InputStream getResourceAsStream(String path) {
return classLoader.getResourceAsStream(resourceRoot + path);
} | 0 | Java | NVD-CWE-noinfo | null | null | null | vulnerable |
public void testXmlLoad() throws Exception {
File exploitFile = f.newFile();
try {
// be extra sure there's no file already
if (exploitFile.exists() && !exploitFile.delete()) {
throw new IllegalStateException("file exists and cannot be deleted");
}
File tempJobDir = new File(j.jenkins.getRootDir(), "security383");
String exploitXml = IOUtils.toString(
XStream2Security383Test.class.getResourceAsStream(
"/hudson/util/XStream2Security383Test/config.xml"), "UTF-8");
exploitXml = exploitXml.replace("@TOKEN@", exploitFile.getAbsolutePath());
FileUtils.write(new File(tempJobDir, "config.xml"), exploitXml);
try {
Items.load(j.jenkins, tempJobDir);
} catch (Exception e) {
// ignore
}
assertFalse("no file should be created here", exploitFile.exists());
} finally {
exploitFile.delete();
}
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
public void validateFail3(ViolationCollector col) {
col.addViolation("p", 3, FAILED);
} | 1 | Java | 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 |
public void Test20037_ScientificIntegerOverflow() throws ParseException {
NumberFormat nf = NumberFormat.getInstance(ULocale.US);
// Test overflow of exponent
Number result = nf.parse("1E-2147483648");
assertEquals("Should snap to zero",
"0", result.toString());
// Test edge case overflow of exponent
// Note: the behavior is different from C++; this is probably due to the
// intermediate BigDecimal form, which has its own restrictions
result = nf.parse("1E-2147483647E-1");
assertEquals("Should not overflow and should parse only the first exponent",
"0.0", result.toString());
// For Java, we should get *pretty close* to 2^31.
result = nf.parse("1E-547483647");
assertEquals("Should *not* snap to zero",
"1E-547483647", result.toString());
// Test edge case overflow of exponent
result = nf.parse(".0003e-2147483644");
assertEquals("Should not overflow",
"0", result.toString());
} | 1 | Java | 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 |
public void translate(ServerWindowPropertyPacket packet, GeyserSession session) {
Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
if (inventory == null)
return;
InventoryTranslator translator = session.getInventoryTranslator();
if (translator != null) {
translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue());
}
} | 0 | Java | 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 |
private static byte[] generateNonceIVPersonalizationString(SecureRandom random)
{
return Arrays.concatenate(Strings.toByteArray("Nonce"), random.generateSeed(16),
Pack.longToLittleEndian(Thread.currentThread().getId()), Pack.longToLittleEndian(System.currentTimeMillis()));
} | 1 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | safe |
private boolean isAdmin(String accountName) {
if (this.adminFilter != null) {
try {
InitialDirContext context = initContext();
String searchString = adminFilter.replace(":login", encodeForLdap(accountName));
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
if (results.hasMoreElements()) {
results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return false;
}
return true;
}
} catch (NamingException e) {
return false;
}
}
return false;
} | 1 | Java | 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 |
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
JpaUser updateUser = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
if (updateUser == null) {
throw new NotFoundException("User " + user.getUsername() + " not found.");
}
logger.debug("updateUser({})", user.getUsername());
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, updateUser.getRoles()))
throw new UnauthorizedException("The user is not allowed to update an admin user");
String encodedPassword;
//only update Password if a value is set
if (StringUtils.isEmpty(user.getPassword())) {
encodedPassword = updateUser.getPassword();
} else {
// Update an JPA user with an encoded password.
encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
}
// Only save internal roles
Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(
(JpaOrganization) user.getOrganization(), emf);
JpaUser updatedUser = UserDirectoryPersistenceUtil.saveUser(
new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user
.getProvider(), true, roles), emf);
cache.put(user.getUsername() + DELIMITER + organization.getId(), updatedUser);
updateGroupMembership(user);
return updatedUser;
} | 0 | Java | CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information. | https://cwe.mitre.org/data/definitions/327.html | vulnerable |
public void testPrivateKeyParsingSHA256()
throws Exception
{
XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest());
XMSSMT mt = new XMSSMT(params, new SecureRandom());
mt.generateKeys();
byte[] privateKey = mt.exportPrivateKey();
byte[] publicKey = mt.exportPublicKey();
mt.importState(privateKey, publicKey);
assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey()));
} | 1 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | safe |
public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){
selectedTaskId = event.getTaskId();
selectedTaskName = event.getTaskName();
view.getTaskIdAndName().setText(String.valueOf(selectedTaskId) + " - "+selectedTaskName);
view.getContent().clear();
String placeToGo;
if(event.getPlace() != null && !event.getPlace().equals("")){
placeToGo = event.getPlace();
}else{
placeToGo = "Task Details";
}
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
activitiesMap.put(placeToGo, activity);
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
} | 0 | Java | 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 |
private String attributeToString(Object attribute) {
if (attribute == null) {
return null;
}
if (attribute instanceof Number) {
return attribute.toString();
} else if (attribute instanceof String) {
return (String) attribute;
} else if (attribute instanceof Element) {
return ((Element) attribute).getTextContent();
} else {
logger.warn("This library currently doesn't handle attributes of type [" + attribute.getClass() + "]");
}
return null;
} | 0 | Java | 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 | vulnerable |
public QName(String name, Namespace namespace, String qualifiedName) {
this.name = (name == null) ? "" : name;
this.qualifiedName = qualifiedName;
this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
: namespace;
validateNCName(this.name);
validateQName(this.qualifiedName);
} | 1 | Java | CWE-91 | XML Injection (aka Blind XPath Injection) | The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. | https://cwe.mitre.org/data/definitions/91.html | safe |
protected String getComparator() {
return "like";
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public IESwithDESede()
{
super(new IESEngine(new DHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(new DESedeEngine())));
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
public void testMatchOperations() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperations(new LinkedHashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertEquals("key_ops=[sign, verify]", matcher.toString());
} | 0 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
public String toString() {
if (query == null) {
return path;
}
return path + '?' + query;
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
private static String getOrderClause(Set<String> joinAliases, String alias, Order order) {
String property = order.getProperty();
boolean qualifyReference = !property.contains("("); // ( indicates a function
for (String joinAlias : joinAliases) {
if (property.startsWith(joinAlias.concat("."))) {
qualifyReference = false;
break;
}
}
String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
: property;
String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;
return String.format("%s %s", wrapped, toJpaDirection(order));
} | 0 | Java | 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 |
public PBEWithSHA256AESCBC192()
{
super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA256, 192, 16);
} | 0 | Java | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// GAE can't serve dot prefixed folders
String uri = request.getRequestURI().replace("/.", "/");
if (uri.toLowerCase().contains(".json"))
{
response.setContentType("application/json");
}
// Serve whatever was requested from .well-known
try (InputStream in = getServletContext().getResourceAsStream(uri))
{
if (in == null)
{
response.sendError(404);
return;
}
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
response.getOutputStream().write(buffer, 0, count);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
} | 0 | Java | 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 |
public Document read(String systemId) throws DocumentException {
InputSource source = new InputSource(systemId);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
} | 0 | Java | 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 | vulnerable |
public void corsNoTags() {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
} | 0 | Java | 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 |
private void testBSI()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC");
kpGen.initialize(new ECGenParameterSpec(TeleTrusTObjectIdentifiers.brainpoolP512r1.getId()));
KeyPair kp = kpGen.generateKeyPair();
byte[] data = "Hello World!!!".getBytes();
String[] cvcAlgs = { "SHA1WITHCVC-ECDSA", "SHA224WITHCVC-ECDSA",
"SHA256WITHCVC-ECDSA", "SHA384WITHCVC-ECDSA",
"SHA512WITHCVC-ECDSA" };
String[] cvcOids = { EACObjectIdentifiers.id_TA_ECDSA_SHA_1.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_224.getId(),
EACObjectIdentifiers.id_TA_ECDSA_SHA_256.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_384.getId(),
EACObjectIdentifiers.id_TA_ECDSA_SHA_512.getId() };
testBsiAlgorithms(kp, data, cvcAlgs, cvcOids);
String[] plainAlgs = { "SHA1WITHPLAIN-ECDSA", "SHA224WITHPLAIN-ECDSA",
"SHA256WITHPLAIN-ECDSA", "SHA384WITHPLAIN-ECDSA",
"SHA512WITHPLAIN-ECDSA", "RIPEMD160WITHPLAIN-ECDSA" };
String[] plainOids = { BSIObjectIdentifiers.ecdsa_plain_SHA1.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA224.getId(),
BSIObjectIdentifiers.ecdsa_plain_SHA256.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA384.getId(),
BSIObjectIdentifiers.ecdsa_plain_SHA512.getId(), BSIObjectIdentifiers.ecdsa_plain_RIPEMD160.getId() };
testBsiAlgorithms(kp, data, plainAlgs, plainOids);
} | 0 | Java | CWE-347 | Improper Verification of Cryptographic Signature | The software does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
public void setHeadersShouldClearAndOverwrite() {
final HttpHeadersBase headers1 = newEmptyHeaders();
headers1.add("name", "value");
final HttpHeadersBase headers2 = newEmptyHeaders();
headers2.add("name", "newvalue");
headers2.add("name1", "value1");
headers1.set(headers2);
assertThat(headers2).isEqualTo(headers1);
} | 0 | Java | 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 |
public void testPostJobXml() throws Exception {
File exploitFile = f.newFile();
try {
// be extra sure there's no file already
if (exploitFile.exists() && !exploitFile.delete()) {
throw new IllegalStateException("file exists and cannot be deleted");
}
File tempJobDir = new File(j.jenkins.getRootDir(), "security383");
String exploitXml = IOUtils.toString(
XStream2Security383Test.class.getResourceAsStream(
"/hudson/util/XStream2Security383Test/config.xml"), "UTF-8");
exploitXml = exploitXml.replace("@TOKEN@", exploitFile.getAbsolutePath());
when(req.getMethod()).thenReturn("POST");
when(req.getInputStream()).thenReturn(new Stream(IOUtils.toInputStream(exploitXml)));
when(req.getContentType()).thenReturn("application/xml");
when(req.getParameter("name")).thenReturn("foo");
try {
j.jenkins.doCreateItem(req, rsp);
} catch (Exception e) {
// don't care
}
assertFalse("no file should be created here", exploitFile.exists());
} finally {
exploitFile.delete();
}
} | 1 | Java | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
public RainbowParameters(int[] vi)
{
this.vi = vi;
try
{
checkParams();
}
catch (Exception e)
{
e.printStackTrace();
}
} | 0 | Java | 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 |
private static boolean isInvalidPath(String path) {
if (path.contains("WEB-INF") || path.contains("META-INF")) {
return true;
}
if (path.contains(":/")) {
String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
return true;
}
}
if (path.contains("")) {
path = StringUtils.cleanPath(path);
if (path.contains("../")) {
return true;
}
}
return false;
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
newNode.setDisplayOption(CourseNode.DISPLAY_OPTS_TITLE_DESCRIPTION_CONTENT);
VFSContainer rootContainer = course.getCourseFolderContainer();
VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
if (singleFile == null) {
singleFile = rootContainer.createChildLeaf("/" + filename);
}
if(in != null) {
moduleConfig.set(SPEditController.CONFIG_KEY_FILE, "/" + filename);
OutputStream out = singleFile.getOutputStream(false);
FileUtils.copy(in, out);
FileUtils.closeSafely(out);
FileUtils.closeSafely(in);
} else {
if(StringHelper.containsNonWhitespace(path)) {
if(!path.startsWith("/")) {
path = "/" + path;
}
if(!path.endsWith("/")) {
path += "/";
}
} else {
path = "/";
}
moduleConfig.set(SPEditController.CONFIG_KEY_FILE, path + filename);
}
//saved node configuration
} | 0 | Java | 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 |
public void corsEmpty() {
InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
} | 0 | Java | 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 |
public void testOfCharSequence() {
// Should produce a lower-cased AsciiString.
assertThat((Object) HttpHeaderNames.of("Foo")).isEqualTo(AsciiString.of("foo"));
// Should reuse known header name instances.
assertThat((Object) HttpHeaderNames.of("date")).isSameAs(HttpHeaderNames.DATE);
} | 0 | Java | 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 |
private static void handleErrorResponse(HttpURLConnection conn, String url, String moduleFullName) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
MapValue payload = (MapValue) JSONParser.parse(result.toString());
createError("error: " + payload.getStringValue("message"));
} catch (IOException e) {
createError("failed to pull the module '" + moduleFullName + "' from the remote repository '" + url + "'");
}
} | 0 | Java | CWE-306 | Missing Authentication for Critical Function | The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. | https://cwe.mitre.org/data/definitions/306.html | vulnerable |
public static HColor unlinear(HColor color1, HColor color2, int completion) {
if (completion == 0) {
return color1;
}
if (completion == 100) {
return color2;
}
if (color1 instanceof HColorSimple && color2 instanceof HColorSimple) {
return HColorSimple.unlinear((HColorSimple) color1, (HColorSimple) color2, completion);
}
return color1;
} | 0 | Java | 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 |
public void testAADLengthComputation()
throws JOSEException {
Assert.assertArrayEquals(AAD_LENGTH, com.nimbusds.jose.crypto.AAD.computeLength(AAD));
} | 1 | Java | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
public void testWhereWithLikeFunction() {
Entity from = from(Entity.class);
where(lower(from.getCode())).like("%test%");
Query<Entity> select = select(from);
assertEquals("select entity_0 from Entity entity_0 where lower(entity_0.code) like :function_1", select.getQuery());
assertEquals("%test%", select.getParameters().get("function_1"));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private int rewriteRecursive(File dir, String relative, TaskListener listener) throws InvalidKeyException {
String canonical;
try {
canonical = dir.getCanonicalPath();
} catch (IOException e) {
canonical = dir.getAbsolutePath(); //
}
if (!callstack.add(canonical)) {
listener.getLogger().println("Cycle detected: "+dir);
return 0;
}
try {
File[] children = dir.listFiles();
if (children==null) return 0;
int rewritten=0;
for (File child : children) {
String cn = child.getName();
if (cn.endsWith(".xml")) {
if ((count++)%100==0)
listener.getLogger().println("Scanning "+child);
try {
File backup = null;
if (backupDirectory!=null) backup = new File(backupDirectory,relative+'/'+ cn);
if (rewrite(child,backup)) {
if (backup!=null)
listener.getLogger().println("Copied "+child+" to "+backup+" as a backup");
listener.getLogger().println("Rewritten "+child);
rewritten++;
}
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to rewrite "+child));
}
}
if (child.isDirectory()) {
if (!isIgnoredDir(child))
rewritten += rewriteRecursive(child,
relative.length()==0 ? cn : relative+'/'+ cn,
listener);
}
}
return rewritten;
} finally {
callstack.remove(canonical);
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public int addWorkUnit(WorkUnit workUnit, long fileModificationTimeInMillis, long fileSize) {
workUnitList.add(workUnit);
if (fileModificationTimeInMillis < oldestFileModificationTime) {
oldestFileModificationTime = fileModificationTimeInMillis;
}
if (fileModificationTimeInMillis > youngestFileModificationTime) {
youngestFileModificationTime = fileModificationTimeInMillis;
}
totalFileSize += fileSize;
return size();
} | 0 | Java | 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 |
private SearchResult lookupUser(String accountName) throws NamingException {
InitialDirContext context = initContext();
String searchString = searchFilter.replace(":login", encodeForLdap(accountName));
SearchControls searchControls = new SearchControls();
String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute};
searchControls.setReturningAttributes(attributeFilter);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
SearchResult searchResult = null;
if (results.hasMoreElements()) {
searchResult = results.nextElement();
if (results.hasMoreElements()) {
LOGGER.warn("Matched multiple users for the accountName: " + accountName);
return null;
}
}
return searchResult;
} | 1 | Java | 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 |
public byte[] toByteArray()
{
/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
int n = params.getDigestSize();
int indexSize = (params.getHeight() + 7) / 8;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
byte[] out = new byte[totalSize];
int position = 0;
/* copy index */
byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);
XMSSUtil.copyBytesAtOffset(out, indexBytes, position);
position += indexSize;
/* copy secretKeySeed */
XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
position += secretKeySize;
/* copy secretKeyPRF */
XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
position += secretKeyPRFSize;
/* copy publicSeed */
XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
position += publicSeedSize;
/* copy root */
XMSSUtil.copyBytesAtOffset(out, root, position);
/* concatenate bdsState */
byte[] bdsStateOut = null;
try
{
bdsStateOut = XMSSUtil.serialize(bdsState);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("error serializing bds state");
}
return Arrays.concatenate(out, bdsStateOut);
} | 0 | Java | CWE-470 | Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') | The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. | https://cwe.mitre.org/data/definitions/470.html | vulnerable |
private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String groupName = request.getParameter("groupName");
String groupComment = request.getParameter("groupComment");
if (groupComment == null) {
groupComment = "";
}
if (groupName != null && groupName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (groupComment != null && groupComment.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group comment must not contain any HTML markup.");
}
boolean hasGroup = false;
try {
hasGroup = m_groupRepository.groupExists(groupName);
} catch (Throwable e) {
throw new ServletException("Can't determine if group " + groupName + " already exists in groups.xml.", e);
}
if (hasGroup) {
return new ModelAndView("admin/userGroupView/groups/newGroup", "action", "redo");
} else {
WebGroup newGroup = new WebGroup();
newGroup.setName(groupName);
newGroup.setComments(groupComment);
return editGroup(request, newGroup);
}
} | 1 | Java | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
public void addViolation(String propertyName, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addConstraintViolation();
} | 1 | Java | 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 |
public OHttpSession[] getSessions() {
acquireSharedLock();
try {
return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);
} finally {
releaseSharedLock();
}
}
| 0 | Java | 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 |
public SAXReader(DocumentFactory factory) {
this.factory = factory;
} | 0 | Java | 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 | vulnerable |
public ViolationCollector(ConstraintValidatorContext context) {
this.context = context;
} | 0 | Java | 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 |
public void validateFail(ViolationCollector col) {
} | 0 | Java | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.