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 |
---|---|---|---|---|---|---|---|
private void testSmallSecret()
throws Exception
{
BigInteger p = new BigInteger("ff3b512a4cc0961fa625d6cbd9642c377ece46b8dbc3146a98e0567f944034b5e3a1406edb179a77cd2539bdb74dc819f0a74d486606e26e578ff52c5242a5ff", 16);
BigInteger g = new BigInteger("58a66667431136e99d86de8199eb650a21afc9de3dd4ef9da6dfe89c866e928698952d95e68b418becef26f23211572eebfcbf328809bdaf02bba3d24c74f8c0", 16);
DHPrivateKeySpec aPrivSpec = new DHPrivateKeySpec(
new BigInteger("30a6ea4e2240a42867ad98bd3adbfd5b81aba48bd930f20a595983d807566f7cba4e766951efef2c6c0c1be3823f63d66e12c2a091d5ff3bbeb1ea6e335d072d", 16), p, g);
DHPublicKeySpec aPubSpec = new DHPublicKeySpec(
new BigInteger("694dfea1bfc8897e2fcbfd88033ab34f4581892d7d5cc362dc056e3d43955accda12222bd651ca31c85f008a05dea914de68828dfd83a54a340fa84f3bbe6caf", 16), p, g);
DHPrivateKeySpec bPrivSpec = new DHPrivateKeySpec(
new BigInteger("775b1e7e162190700e2212dd8e4aaacf8a2af92c9c108b81d5bf9a14548f494eaa86a6c4844b9512eb3e3f2f22ffec44c795c813edfea13f075b99bbdebb34bd", 16), p, g);
DHPublicKeySpec bPubSpec = new DHPublicKeySpec(
new BigInteger("d8ddd4ff9246635eadbfa0bc2ef06d98a329b6e8cd2d1435d7b4921467570e697c9a9d3c172c684626a9d2b6b2fa0fc725d5b91f9a9625b717a4169bc714b064", 16), p, g);
KeyFactory kFact = KeyFactory.getInstance("DH", "BC");
byte[] secret = testTwoParty("DH", 512, 0, new KeyPair(kFact.generatePublic(aPubSpec), kFact.generatePrivate(aPrivSpec)), new KeyPair(kFact.generatePublic(bPubSpec), kFact.generatePrivate(bPrivSpec)));
if (secret.length != ((p.bitLength() + 7) / 8))
{
fail("short secret wrong length");
}
if (!Arrays.areEqual(Hex.decode("00340d3309ddc86e99e2f0be4fc212837bfb5c59336b09b9e1aeb1884b72c8b485b56723d0bf1c1d37fc89a292fc1cface9125106f1df15f55f22e4f77c5879b"), secret))
{
fail("short secret mismatch");
}
} | 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 |
private void checkParams()
{
if (vi == null)
{
throw new IllegalArgumentException("no layers defined.");
}
if (vi.length > 1)
{
for (int i = 0; i < vi.length - 1; i++)
{
if (vi[i] >= vi[i + 1])
{
throw new IllegalArgumentException(
"v[i] has to be smaller than v[i+1]");
}
}
}
else
{
throw new IllegalArgumentException(
"Rainbow needs at least 1 layer, such that v1 < v2.");
}
} | 1 | 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 | safe |
protected void runTeardown() {
Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
} | 1 | 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 | safe |
public void translate(ServerEntityCollectItemPacket packet, GeyserSession session) {
// Collected entity is the other entity
Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId());
if (collectedEntity == null) return;
// Collector is the entity 'picking up' the item
Entity collectorEntity;
if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) {
collectorEntity = session.getPlayerEntity();
} else {
collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId());
}
if (collectorEntity == null) return;
if (collectedEntity instanceof ExpOrbEntity) {
// Player just picked up an experience orb
LevelEventPacket xpPacket = new LevelEventPacket();
xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP);
xpPacket.setPosition(collectedEntity.getPosition());
xpPacket.setData(0);
session.sendUpstreamPacket(xpPacket);
} else {
// Item is being picked up (visual only)
TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket();
takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId());
takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId());
session.sendUpstreamPacket(takeItemEntityPacket);
}
} | 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 void init() throws TemplateException {
if (_configuration != null) {
return;
}
LiferayTemplateLoader liferayTemplateLoader =
new LiferayTemplateLoader();
liferayTemplateLoader.setTemplateLoaders(
PropsValues.FREEMARKER_ENGINE_TEMPLATE_LOADERS);
_stringTemplateLoader = new StringTemplateLoader();
MultiTemplateLoader multiTemplateLoader =
new MultiTemplateLoader(
new TemplateLoader[] {
new ClassTemplateLoader(getClass(), StringPool.SLASH),
_stringTemplateLoader, liferayTemplateLoader
});
_configuration = new Configuration();
_configuration.setDefaultEncoding(StringPool.UTF8);
_configuration.setLocalizedLookup(
PropsValues.FREEMARKER_ENGINE_LOCALIZED_LOOKUP);
_configuration.setNewBuiltinClassResolver(
new LiferayTemplateClassResolver());
_configuration.setObjectWrapper(new LiferayObjectWrapper());
_configuration.setTemplateLoader(multiTemplateLoader);
_configuration.setTemplateUpdateDelay(
PropsValues.FREEMARKER_ENGINE_MODIFICATION_CHECK_INTERVAL);
try {
_configuration.setSetting(
"auto_import", PropsValues.FREEMARKER_ENGINE_MACRO_LIBRARY);
_configuration.setSetting(
"cache_storage", PropsValues.FREEMARKER_ENGINE_CACHE_STORAGE);
_configuration.setSetting(
"template_exception_handler",
PropsValues.FREEMARKER_ENGINE_TEMPLATE_EXCEPTION_HANDLER);
}
catch (Exception e) {
throw new TemplateException("Unable to init freemarker manager", e);
}
_standardHelperUtilities = _templateContextHelper.getHelperUtilities();
_restrictedHelperUtilities =
_templateContextHelper.getRestrictedHelperUtilities();
} | 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 OHttpSession removeSession(final String iSessionId) {
acquireExclusiveLock();
try {
return sessions.remove(iSessionId);
} finally {
releaseExclusiveLock();
}
}
| 1 | 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 | safe |
private SecretKey getKey() {
try {
if (secret==null) {
synchronized (this) {
if (secret==null) {
byte[] payload = load();
if (payload==null) {
payload = ConfidentialStore.get().randomBytes(256);
store(payload);
}
// Due to the stupid US export restriction JDK only ships 128bit version.
secret = new SecretKeySpec(payload,0,128/8, ALGORITHM);
}
}
}
return secret;
} catch (IOException e) {
throw new Error("Failed to load the key: "+getId(),e);
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private void testHeaderNameStartsWithControlChar(int controlChar) {
ByteBuf requestBuffer = Unpooled.buffer();
requestBuffer.writeCharSequence("GET /some/path HTTP/1.1\r\n" +
"Host: netty.io\r\n", CharsetUtil.US_ASCII);
requestBuffer.writeByte(controlChar);
requestBuffer.writeCharSequence("Transfer-Encoding: chunked\r\n\r\n", CharsetUtil.US_ASCII);
testInvalidHeaders0(requestBuffer);
} | 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 doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
String userName = request.getParameter("aname");
String password = sha.getSHA(request.getParameter("pass"));
// String password = request.getParameter("pass");
String rememberMe = request.getParameter("remember-me");
// validation
if (adminDao.loginValidate(userName, password)) {
if (rememberMe != null) {
Cookie cookie1 = new Cookie("uname", userName);
Cookie cookie2 = new Cookie("pass", password);
cookie1.setMaxAge(24 * 60 * 60);
cookie2.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
response.addCookie(cookie2);
}
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
/*
* RequestDispatcher rd =
* request.getRequestDispatcher("AdminController?actions=admin_list");
* rd.forward(request, response);
*/
response.sendRedirect("AdminController?actions=admin_list");
} else {
RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Username or Password !!");
rd.include(request, response);
}
} | 0 | Java | CWE-759 | Use of a One-Way Hash without a Salt | The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input. | https://cwe.mitre.org/data/definitions/759.html | vulnerable |
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String secret = getSecret();
Key key = new SecretKeySpec(Decoders.BASE64.decode(secret), getSignatureAlgorithm().getJcaName());
Jwt jwt = Jwts.parser().
setSigningKey(key).
parse((String) token.getPrincipal());
Map<String, Serializable> principal = getPrincipal(jwt);
return new SimpleAuthenticationInfo(principal, ((String) token.getCredentials()).toCharArray(), getName());
} | 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 |
void relative() {
assertThat(parse("foo")).isNull();
} | 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 RefUpdated uploadFiles(Collection<FileUpload> uploads, String directory, String commitMessage) {
Map<String, BlobContent> newBlobs = new HashMap<>();
String parentPath = getDirectory();
if (directory != null) {
if (parentPath != null)
parentPath += "/" + directory;
else
parentPath = directory;
}
User user = Preconditions.checkNotNull(SecurityUtils.getUser());
BlobIdent blobIdent = getBlobIdent();
for (FileUpload upload: uploads) {
String blobPath = upload.getClientFileName();
if (parentPath != null)
blobPath = parentPath + "/" + blobPath;
if (getProject().isReviewRequiredForModification(user, blobIdent.revision, blobPath))
throw new BlobEditException("Review required for this change. Please submit pull request instead");
else if (getProject().isBuildRequiredForModification(user, blobIdent.revision, blobPath))
throw new BlobEditException("Build required for this change. Please submit pull request instead");
BlobContent blobContent = new BlobContent.Immutable(upload.getBytes(), FileMode.REGULAR_FILE);
newBlobs.put(blobPath, blobContent);
}
BlobEdits blobEdits = new BlobEdits(Sets.newHashSet(), newBlobs);
String refName = blobIdent.revision!=null?GitUtils.branch2ref(blobIdent.revision):"refs/heads/master";
ObjectId prevCommitId;
if (blobIdent.revision != null)
prevCommitId = getProject().getRevCommit(blobIdent.revision, true).copy();
else
prevCommitId = ObjectId.zeroId();
while (true) {
try {
ObjectId newCommitId = blobEdits.commit(getProject().getRepository(), refName, prevCommitId,
prevCommitId, user.asPerson(), commitMessage);
return new RefUpdated(getProject(), refName, prevCommitId, newCommitId);
} catch (ObjectAlreadyExistsException|NotTreeException e) {
throw new BlobEditException(e.getMessage());
} catch (ObsoleteCommitException e) {
prevCommitId = e.getOldCommitId();
}
}
}
| 0 | Java | CWE-434 | Unrestricted Upload of File with Dangerous Type | The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
public void checkAccess(ThreadGroup g) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(g);
final ThreadGroup cg = c.getThreadGroup();
if (cg == null) {
// What the heck is going on here? JDK 1.3 is sending me a dead thread.
// This crashes the entire jvm if I don't return here.
return;
}
// Bug fix #382 Unable to run robocode.bat -- Access Control Exception
if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) {
return; // The SeedGenerator might create a thread, which needs to be silently ignored
}
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy == null) {
throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName());
}
if (cg.activeCount() > 5) {
String message = "Robots are only allowed to create up to 5 threads!";
robotProxy.punishSecurityViolation(message);
throw new SecurityException(message);
}
} | 1 | 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 | safe |
public ConstraintValidatorContext getContext() {
return 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 static void destroy(ClassLoader classLoader) {
Map<String, TemplateManager> templateManagers = _getTemplateManagers();
for (TemplateManager templateManager : templateManagers.values()) {
templateManager.destroy(classLoader);
}
} | 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 |
private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() {
/** {@inheritDoc} */
public boolean check(Restrictor restrictor, Object... args) {
return restrictor.isCorsAccessAllowed((String) args[0]);
}
}; | 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 FormValidation doCheck(@AncestorInPath Item project, @QueryParameter String value ) {
// Require CONFIGURE permission on this project
if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.getInstance().getItem(projectName,project,Item.class);
if(item==null)
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName,
AbstractProject.findNearest(projectName,project.getParent()).getRelativeNameFrom(project)));
if(!(item instanceof AbstractProject))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
} | 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 void saveCustomConfigAndCompileCSS(Map<String, Map<String, Object>> customConfig, CourseEnvironment courseEnvironment){
VFSContainer themeBase = null;
VFSContainer base = null;
base = (VFSContainer) courseEnvironment.getCourseBaseContainer().resolve(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER);
if (base == null) {
base = courseEnvironment.getCourseBaseContainer().createChildContainer(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER);
}
themeBase = (VFSContainer) base.resolve("/" + CourseLayoutHelper.CONFIG_KEY_CUSTOM);
if (themeBase == null) {
themeBase = base.createChildContainer(CourseLayoutHelper.CONFIG_KEY_CUSTOM);
}
VFSLeaf configTarget = (VFSLeaf) themeBase.resolve(CUSTOM_CONFIG_XML);
if (configTarget == null) {
configTarget = themeBase.createChildLeaf(CUSTOM_CONFIG_XML);
}
XStream xStream = XStreamHelper.createXStreamInstance();
xStream.toXML(customConfig, configTarget.getOutputStream(false));
// compile the css-files
StringBuilder sbMain = new StringBuilder();
StringBuilder sbIFrame = new StringBuilder();
for (Entry<String, Map<String, Object>> iterator : customConfig.entrySet()) {
String type = iterator.getKey();
Map<String, Object> elementConfig = iterator.getValue();
AbstractLayoutElement configuredLayEl = createLayoutElementByType(type, elementConfig);
sbIFrame.append(configuredLayEl.getCSSForIFrame());
sbMain.append(configuredLayEl.getCSSForMain());
}
// attach line for logo, if there is any to cssForMain:
appendLogoPart(sbMain, themeBase);
VFSLeaf mainFile = (VFSLeaf) themeBase.resolve(MAIN_CSS);
if (mainFile == null) mainFile = themeBase.createChildLeaf(MAIN_CSS);
VFSLeaf iFrameFile = (VFSLeaf) themeBase.resolve(IFRAME_CSS);
if (iFrameFile == null) iFrameFile = themeBase.createChildLeaf(IFRAME_CSS);
FileUtils.save(mainFile.getOutputStream(false), sbMain.toString(), "utf-8");
FileUtils.save(iFrameFile.getOutputStream(false), sbIFrame.toString(), "utf-8");
} | 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 void dataContentLengthInvalid() throws Exception {
dataContentLengthInvalid(true);
} | 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 static byte[] decryptWithConcatKDF(final JWEHeader header,
final SecretKey secretKey,
final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authTag,
final Provider ceProvider,
final Provider macProvider)
throws JOSEException {
byte[] epu = null;
if (header.getCustomParam("epu") instanceof String) {
epu = new Base64URL((String)header.getCustomParam("epu")).decode();
}
byte[] epv = null;
if (header.getCustomParam("epv") instanceof String) {
epv = new Base64URL((String)header.getCustomParam("epv")).decode();
}
SecretKey cekAlt = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv);
final byte[] plainText = AESCBC.decrypt(cekAlt, iv.decode(), cipherText.decode(), ceProvider);
SecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv);
String macInput = header.toBase64URL().toString() + "." +
encryptedKey.toString() + "." +
iv.toString() + "." +
cipherText.toString();
byte[] mac = HMAC.compute(cik, macInput.getBytes(), macProvider);
if (! ConstantTimeUtils.areEqual(authTag.decode(), mac)) {
throw new JOSEException("HMAC integrity check failed");
}
return plainText;
} | 0 | Java | CWE-354 | Improper Validation of Integrity Check Value | The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. | https://cwe.mitre.org/data/definitions/354.html | 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 checkPermission(Permission perm) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkPermission(perm);
if (perm instanceof SocketPermission) {
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
String message = "Using socket is not allowed";
robotProxy.punishSecurityViolation(message);
throw new SecurityException(message);
}
} | 1 | 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 | safe |
public void testIncludesMid() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "default://**" );
add( "**/repo/**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertTrue( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertFalse( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher/repo/sss" ) );
Assert.assertTrue( includes( patterns, path ) );
}
} | 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 Operation.OperationResult executeFixedCostOperation(
final MessageFrame frame, final EVM evm) {
Bytes shiftAmount = frame.popStackItem();
if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
frame.popStackItem();
frame.pushStackItem(UInt256.ZERO);
} else {
final int shiftAmountInt = shiftAmount.toInt();
final Bytes value = leftPad(frame.popStackItem());
if (shiftAmountInt >= 256) {
frame.pushStackItem(UInt256.ZERO);
} else {
frame.pushStackItem(value.shiftLeft(shiftAmountInt));
}
}
return successResponse;
} | 0 | Java | CWE-681 | Incorrect Conversion between Numeric Types | When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur. | https://cwe.mitre.org/data/definitions/681.html | vulnerable |
public void addViolation(String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.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 OldECIES()
{
super(new OldIESEngine(new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest())));
} | 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 |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (newName != null && newName.matches(".*[&<>\"`']+.*")) {
throw new ServletException("Group ID must not contain any HTML markup.");
}
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | 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 OldIESwithAES()
{
super(new AESEngine());
} | 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 |
final void add(CharSequence name, String value) {
final AsciiString normalizedName = HttpHeaderNames.of(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
add0(h, i, normalizedName, 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 int getExpirationTime() {
return expirationTime;
}
| 1 | 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 | safe |
default Optional<Integer> findInt(CharSequence name) {
return get(name, Integer.class);
} | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
VFSContainer currentContainer = folderComponent.getCurrentContainer();
status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
if(selection.getFiles().isEmpty()) {
status = FolderCommandStatus.STATUS_FAILED;
wControl.setWarning(trans.translate("warning.file.selection.empty"));
return null;
}
MediaResource mr = new ZipMediaResource(currentContainer, selection);
ureq.getDispatchResult().setResultingMediaResource(mr);
return null;
} | 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 |
/*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {
String secret = Secret.SECRET;
if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();
return Util.toAes128Key(secret);
} | 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 void iteratorShouldReturnAllNameValuePairs() {
final HttpHeadersBase headers1 = newEmptyHeaders();
headers1.add("name1", "value1", "value2");
headers1.add("name2", "value3");
headers1.add("name3", "value4", "value5", "value6");
headers1.add("name1", "value7", "value8");
assertThat(headers1.size()).isEqualTo(8);
final HttpHeadersBase headers2 = newEmptyHeaders();
for (Map.Entry<AsciiString, String> entry : headers1) {
headers2.add(entry.getKey(), entry.getValue());
}
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 PersistedMapper persistMapper(String sessionId, String mapperId, Serializable mapper, int expirationTime) {
PersistedMapper m = new PersistedMapper();
m.setMapperId(mapperId);
Date currentDate = new Date();
m.setLastModified(currentDate);
if(expirationTime > 0) {
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.SECOND, expirationTime);
m.setExpirationDate(cal.getTime());
}
m.setOriginalSessionId(sessionId);
String configuration = XStreamHelper.createXStreamInstance().toXML(mapper);
m.setXmlConfiguration(configuration);
dbInstance.getCurrentEntityManager().persist(m);
return m;
} | 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 |
protected void store(ConfidentialKey key, byte[] payload) throws IOException {
CipherOutputStream cos=null;
FileOutputStream fos=null;
try {
Cipher sym = Secret.getCipher("AES");
sym.init(Cipher.ENCRYPT_MODE, masterKey);
cos = new CipherOutputStream(fos=new FileOutputStream(getFileFor(key)), sym);
cos.write(payload);
cos.write(MAGIC);
} catch (GeneralSecurityException e) {
throw new IOException2("Failed to persist the key: "+key.getId(),e);
} finally {
IOUtils.closeQuietly(cos);
IOUtils.closeQuietly(fos);
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public MultiMap set(CharSequence name, CharSequence value) {
HttpUtils.validateHeader(name, value);
headers.set(toLowerCase(name), value);
return this;
} | 1 | Java | 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 |
protected XMLReader installXMLFilter(XMLReader reader) {
XMLFilter filter = getXMLFilter();
if (filter != null) {
// find the root XMLFilter
XMLFilter root = filter;
while (true) {
XMLReader parent = root.getParent();
if (parent instanceof XMLFilter) {
root = (XMLFilter) parent;
} else {
break;
}
}
root.setParent(reader);
return filter;
}
return reader;
} | 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 static void testListBinary() throws Exception {
TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryListEncoding);
TProtocol iprot = new TBinaryProtocol(buf);
testTruncated(new MyListStruct(), iprot);
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
private void verifyShellState()
{
if ( shell.getWorkingDirectory() == null )
{
shell.setWorkingDirectory( workingDir );
}
if ( shell.getExecutable() == null )
{
shell.setExecutable( 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 |
public void testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
} | 1 | Java | CWE-378 | Creation of Temporary File With Insecure Permissions | Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack. | https://cwe.mitre.org/data/definitions/378.html | safe |
public BigInteger[] decode(
byte[] encoding)
throws IOException
{
ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding);
if (s.size() != 2)
{
throw new IOException("malformed signature");
}
if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER)))
{
throw new IOException("malformed signature");
}
BigInteger[] sig = new BigInteger[2];
sig[0] = ASN1Integer.getInstance(s.getObjectAt(0)).getValue();
sig[1] = ASN1Integer.getInstance(s.getObjectAt(1)).getValue();
return sig;
} | 1 | 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 | safe |
protected void ensureMapHasEnough(int size, byte keyType, byte valueType) {
int minimumExpected = size * (typeMinimumSize(keyType) + typeMinimumSize(valueType));
ensureHasEnoughBytes(minimumExpected);
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
public TList readListBegin() throws TException {
byte type = readByte();
int size = readI32();
ensureContainerHasEnough(size, type);
return new TList(type, size);
} | 1 | Java | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
if (javaVersion() >= 7) {
if (directory == null) {
return Files.createTempFile(prefix, suffix).toFile();
}
return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();
}
final File file;
if (directory == null) {
file = File.createTempFile(prefix, suffix);
} else {
file = File.createTempFile(prefix, suffix, directory);
}
// Try to adjust the perms, if this fails there is not much else we can do...
if (!file.setReadable(false, false)) {
throw new IOException("Failed to set permissions on temporary file " + file);
}
if (!file.setReadable(true, true)) {
throw new IOException("Failed to set permissions on temporary file " + file);
}
return file;
} | 1 | Java | CWE-378 | Creation of Temporary File With Insecure Permissions | Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack. | https://cwe.mitre.org/data/definitions/378.html | safe |
protected Details authenticate(String username, String password) throws AuthenticationException {
Details u = loadUserByUsername(username);
if (!u.isPasswordCorrect(password)) {
String message;
try {
message = ResourceBundle.getBundle("org.acegisecurity.messages").getString("AbstractUserDetailsAuthenticationProvider.badCredentials");
} catch (MissingResourceException x) {
message = "Bad credentials";
}
throw new BadCredentialsException(message);
}
return u;
} | 1 | 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 | safe |
public static SocketFactory getSocketFactory(Properties info) throws PSQLException {
// Socket factory
String socketFactoryClassName = PGProperty.SOCKET_FACTORY.get(info);
if (socketFactoryClassName == null) {
return SocketFactory.getDefault();
}
try {
return (SocketFactory) ObjectFactory.instantiate(socketFactoryClassName, info, true,
PGProperty.SOCKET_FACTORY_ARG.get(info));
} catch (Exception e) {
throw new PSQLException(
GT.tr("The SocketFactory class provided {0} could not be instantiated.",
socketFactoryClassName),
PSQLState.CONNECTION_FAILURE, e);
}
} | 0 | Java | CWE-665 | Improper Initialization | The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used. | https://cwe.mitre.org/data/definitions/665.html | vulnerable |
private boolean handleJid(Invite invite) {
List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
if (invite.isAction(XmppUri.ACTION_JOIN)) {
Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
if (muc != null) {
switchToConversationDoNotAppend(muc, invite.getBody());
return true;
} else {
showJoinConferenceDialog(invite.getJid().asBareJid().toString());
return false;
}
} else if (contacts.size() == 0) {
showCreateContactDialog(invite.getJid().toString(), invite);
return false;
} else if (contacts.size() == 1) {
Contact contact = contacts.get(0);
if (!invite.isSafeSource() && invite.hasFingerprints()) {
displayVerificationWarningDialog(contact, invite);
} else {
if (invite.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
}
}
if (invite.account != null) {
xmppConnectionService.getShortcutService().report(contact);
}
switchToConversationDoNotAppend(contact, invite.getBody());
}
return true;
} else {
if (mMenuSearchView != null) {
mMenuSearchView.expandActionView();
mSearchEditText.setText("");
mSearchEditText.append(invite.getJid().toString());
filter(invite.getJid().toString());
} else {
mInitialSearchValue.push(invite.getJid().toString());
}
return true;
}
} | 1 | 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 | safe |
public void testContainsNameAndValue() {
final HttpHeadersBase headers = newHttp2Headers();
assertThat(headers.contains("name1", "value2")).isTrue();
assertThat(headers.contains("name1", "Value2")).isFalse();
assertThat(headers.contains("name2", "value3")).isTrue();
assertThat(headers.contains("name2", "Value3")).isFalse();
} | 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 ECIESwithAESCBC()
{
super(new CBCBlockCipher(new AESFastEngine()), 16);
} | 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 |
public void translate(ServerSpawnLivingEntityPacket packet, GeyserSession session) {
Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());
Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getHeadYaw());
EntityType type = EntityUtils.toBedrockEntity(packet.getType());
if (type == null) {
session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType()));
return;
}
Class<? extends Entity> entityClass = type.getEntityClass();
try {
Constructor<? extends Entity> entityConstructor = entityClass.getConstructor(long.class, long.class, EntityType.class,
Vector3f.class, Vector3f.class, Vector3f.class);
Entity entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
type, position, motion, rotation
);
session.getEntityCache().spawnEntity(entity);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
}
} | 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 ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | 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 testMatchUse() {
JWKMatcher matcher = new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.ENCRYPTION).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256,EC_P256_X, EC_P256_Y).keyID("2").build()));
assertEquals("use=enc", matcher.toString());
} | 1 | 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 | safe |
public boolean checkUrlParameter(String url)
{
if (url != null)
{
try
{
URL parsedUrl = new URL(url);
String protocol = parsedUrl.getProtocol();
String host = parsedUrl.getHost().toLowerCase();
return (protocol.equals("http") || protocol.equals("https"))
&& !host.endsWith(".internal")
&& !host.endsWith(".local")
&& !host.contains("localhost")
&& !host.startsWith("0.") // 0.0.0.0/8
&& !host.startsWith("10.") // 10.0.0.0/8
&& !host.startsWith("127.") // 127.0.0.0/8
&& !host.startsWith("169.254.") // 169.254.0.0/16
&& !host.startsWith("172.16.") // 172.16.0.0/12
&& !host.startsWith("172.17.") // 172.16.0.0/12
&& !host.startsWith("172.18.") // 172.16.0.0/12
&& !host.startsWith("172.19.") // 172.16.0.0/12
&& !host.startsWith("172.20.") // 172.16.0.0/12
&& !host.startsWith("172.21.") // 172.16.0.0/12
&& !host.startsWith("172.22.") // 172.16.0.0/12
&& !host.startsWith("172.23.") // 172.16.0.0/12
&& !host.startsWith("172.24.") // 172.16.0.0/12
&& !host.startsWith("172.25.") // 172.16.0.0/12
&& !host.startsWith("172.26.") // 172.16.0.0/12
&& !host.startsWith("172.27.") // 172.16.0.0/12
&& !host.startsWith("172.28.") // 172.16.0.0/12
&& !host.startsWith("172.29.") // 172.16.0.0/12
&& !host.startsWith("172.30.") // 172.16.0.0/12
&& !host.startsWith("172.31.") // 172.16.0.0/12
&& !host.startsWith("192.0.0.") // 192.0.0.0/24
&& !host.startsWith("192.168.") // 192.168.0.0/16
&& !host.startsWith("198.18.") // 198.18.0.0/15
&& !host.startsWith("198.19.") // 198.18.0.0/15
&& !host.endsWith(".arpa"); // reverse domain (needed?)
}
catch (MalformedURLException e)
{
return false;
}
}
else
{
return false;
}
} | 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 testUpdateUser() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));
JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
String newPassword = "newPassword";
JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);
User loadUpdatedUser = provider.updateUser(updateUser);
// User loadUpdatedUser = provider.loadUser(user.getUsername());
assertNotNull(loadUpdatedUser);
assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());
assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());
updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);
try {
provider.updateUser(updateUser);
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
} | 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 testHttpClientRequestHeadersDontContainCROrLF() throws Exception {
server.requestHandler(req -> {
req.headers().forEach(header -> {
String name = header.getKey();
switch (name.toLowerCase()) {
case "host":
case ":method":
case ":path":
case ":scheme":
case ":authority":
break;
default:
fail("Unexpected header " + name);
}
});
testComplete();
});
startServer();
HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {});
List<BiConsumer<String, String>> list = Arrays.asList(
req::putHeader,
req.headers()::set,
req.headers()::add
);
list.forEach(cs -> {
try {
req.putHeader("header-name: header-value\r\nanother-header", "another-value");
fail();
} catch (IllegalArgumentException e) {
}
});
assertEquals(0, req.headers().size());
req.end();
await();
} | 1 | Java | 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 |
function findLateSubscriptionSortedByPriority() {
if (late_subscriptions.length === 0) {
return null;
}
late_subscriptions.sort(compare_subscriptions);
// istanbul ignore next
if (doDebug) {
debugLog(
late_subscriptions
.map(
(s: Subscription) =>
"[ id = " +
s.id +
" prio=" +
s.priority +
" t=" +
s.timeToExpiration +
" ka=" +
s.timeToKeepAlive +
" m?=" +
s.hasUncollectedMonitoredItemNotifications +
" " +
SubscriptionState[s.state] +
" " + s.messageSent +
"]"
)
.join(" \n")
);
}
return late_subscriptions[late_subscriptions.length - 1];
} | 0 | Java | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
void testGetAndRemove() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2", "value3");
headers.add("name3", "value4", "value5", "value6");
assertThat(headers.getAndRemove("name1", "defaultvalue")).isEqualTo("value1");
assertThat(headers.getAndRemove("name2")).isEqualTo("value2");
assertThat(headers.getAndRemove("name2")).isNull();
assertThat(headers.getAllAndRemove("name3")).containsExactly("value4", "value5", "value6");
assertThat(headers.size()).isZero();
assertThat(headers.getAndRemove("noname")).isNull();
assertThat(headers.getAndRemove("noname", "defaultvalue")).isEqualTo("defaultvalue");
} | 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 int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
poly.update(ciphertext, ciphertextOffset, length);
finish(ad, length);
System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
return length + 16;
} | 0 | Java | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
public boolean isCorsAccessAllowed(String pOrigin) {
return restrictor.isCorsAccessAllowed(pOrigin);
} | 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 testInvalidGroupIds() {
testInvalidGroupId("John<b>Doe</b>",true);
testInvalidGroupId("Jane'Doe'",true);
testInvalidGroupId("John&Doe",true);
testInvalidGroupId("Jane\"\"Doe",true);
} | 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 |
private void verifyShellState()
{
if ( shell.getWorkingDirectory() == null )
{
shell.setWorkingDirectory( workingDir );
}
if ( shell.getOriginalExecutable() == null )
{
shell.setExecutable( executable );
}
} | 1 | 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 | safe |
public String render(String templateContent, Map<String, Object> context) {
VelocityContext velocityContext = new VelocityContext(context);
try (StringWriter sw = new StringWriter()) {
Velocity.evaluate(velocityContext, sw, "velocityTemplateEngine", templateContent);
return sw.toString();
}
catch (Exception ex) {
throw new TemplateRenderException(ex);
}
} | 0 | Java | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
public BigInteger[] generateSignature(
byte[] message)
{
DSAParameters params = key.getParameters();
BigInteger q = params.getQ();
BigInteger m = calculateE(q, message);
BigInteger x = ((DSAPrivateKeyParameters)key).getX();
if (kCalculator.isDeterministic())
{
kCalculator.init(q, x, message);
}
else
{
kCalculator.init(q, random);
}
BigInteger k = kCalculator.nextK();
// the randomizer is to conceal timing information related to k and x.
BigInteger r = params.getG().modPow(k.add(getRandomizer(q, random)), params.getP()).mod(q);
k = k.modInverse(q).multiply(m.add(x.multiply(r)));
BigInteger s = k.mod(q);
return new BigInteger[]{ r, s };
} | 1 | Java | CWE-361 | 7PK - Time and State | This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. According to the authors of the Seven Pernicious Kingdoms, "Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time. Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information." | https://cwe.mitre.org/data/definitions/361.html | safe |
public void setAllowECPFlow(boolean val) {
client.setAttribute(SamlConfigAttributes.SAML_ALLOW_ECP_FLOW, Boolean.toString(val));
} | 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 testInvalidUserId(final String userId, final boolean mustFail) {
adminPage();
findElementByLink("Configure Users, Groups and On-Call Roles").click();
findElementByLink("Configure Users").click();
findElementByLink("Add new user").click();
enterText(By.id("userID"), userId);
enterText(By.id("pass1"), "SmokeTestPassword");
enterText(By.id("pass2"), "SmokeTestPassword");
findElementByXpath("//button[@type='submit' and text()='OK']").click();
if (mustFail) {
try {
final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent());
alert.dismiss();
} catch (final Exception e) {
LOG.debug("Got an exception waiting for a 'invalid user ID' alert.", e);
throw e;
}
} else {
wait.until(ExpectedConditions.elementToBeClickable(By.name("finish")));
}
} | 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 todo_oldTasks() {
String taskName = UUID.randomUUID().toString();
PersistentTask ctask = persistentTaskDao.createTask(taskName, new DummyTask());
//simulate a task from a previous boot
PersistentTask ptask = new PersistentTask();
ptask.setCreationDate(new Date());
ptask.setLastModified(new Date());
ptask.setName(UUID.randomUUID().toString());
ptask.setStatus(TaskStatus.inWork);
ptask.setExecutorBootId(UUID.randomUUID().toString());
ptask.setExecutorNode(Integer.toString(WebappHelper.getNodeId()));
ptask.setTask(XStreamHelper.createXStreamInstance().toXML(new DummyTask()));
dbInstance.getCurrentEntityManager().persist(ptask);
//simulate a task from an other node
PersistentTask alienTask = new PersistentTask();
alienTask.setCreationDate(new Date());
alienTask.setLastModified(new Date());
alienTask.setName(UUID.randomUUID().toString());
alienTask.setStatus(TaskStatus.inWork);
alienTask.setExecutorBootId(UUID.randomUUID().toString());
alienTask.setExecutorNode(Integer.toString(WebappHelper.getNodeId() + 1));
alienTask.setTask(XStreamHelper.createXStreamInstance().toXML(new DummyTask()));
dbInstance.getCurrentEntityManager().persist(alienTask);
dbInstance.commitAndCloseSession();
List<Long> todos = persistentTaskDao.tasksToDo();
Assert.assertNotNull(todos);
Assert.assertFalse(todos.isEmpty());
Assert.assertTrue(todos.contains(ptask.getKey()));
Assert.assertTrue(todos.contains(ctask.getKey()));
Assert.assertFalse(todos.contains(alienTask.getKey()));
} | 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 void tearDown() throws Exception {
if (embeddedServer != null) {
embeddedServer.extinguish();
}
} | 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 testFormat() throws Exception {
assertEquals("<a> <b>c</b></a>", format("<a><b>c</b></a>", 1).replaceAll("[\r\n]", ""));
assertEquals("<a> <b>c</b></a>", format("<a><b>c</b></a>", 3).replaceAll("[\r\n]", ""));
assertEquals("<a><b>c</b></a>", format("<a><b>c</b></a>", -21));
assertThrows(IllegalArgumentException.class, () -> format("<a><b>c</b></a>", 0));
// check if the XXE protection is enabled
String xxeAttack = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + " <!DOCTYPE test [\n"
+ " <!ENTITY xxe SYSTEM \"file:///etc/passwd\">\n" + " ]>" + "<a><b>&xxe;</b></a>";
assertEquals(xxeAttack, format(xxeAttack, 1));
// wrongly formatted XML
assertEquals("<a><b>c</b><a>", format("<a><b>c</b><a>", 1));
} | 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 |
private void checkMimeTypes(String given, final String expected) throws ServletException, IOException {
prepareStandardInitialisation();
initRequestResponseMocks(
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
// The default content type
response.setContentType(expected);
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(given);
replay(request, response);
servlet.doGet(request, response);
verifyMocks();
servlet.destroy();
} | 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 Optional<URL> getResource(String path) {
boolean isDirectory = isDirectory(path);
if (!isDirectory) {
URL url = classLoader.getResource(prefixPath(path));
return Optional.ofNullable(url);
}
return Optional.empty();
} | 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 ECIESwithCipher(BlockCipher cipher)
{
super(new IESEngine(new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
new PaddedBufferedBlockCipher(cipher)));
} | 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 String list(Model model, // TODO model should no longer be injected
@RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
@RequestParam(required = false, defaultValue = "false") boolean desc,
@RequestParam(required = false) String base) throws IOException, TemplateException {
securityCheck(base);
Path currentFolder = loggingPath(base);
List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);
model.addAttribute("sortBy", sortBy);
model.addAttribute("desc", desc);
model.addAttribute("files", sortedFiles);
model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
model.addAttribute("parent", getParent(currentFolder));
model.addAttribute("stylesheets", stylesheets);
return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
} | 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 testAll() throws Exception {
testStringFilterInjection();
} | 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 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 |
public Response workspaceClientEnqueue(@FormParam(WorkSpaceAdapter.CLIENT_NAME) String clientName,
@FormParam(WorkSpaceAdapter.WORK_BUNDLE_OBJ) String workBundleString) {
logger.debug("TPWorker incoming execute! check prio={}", Thread.currentThread().getPriority());
// TODO Doesn't look like anything is actually calling this, should we remove this?
final boolean success;
try {
// Look up the place reference
final String nsName = KeyManipulator.getServiceLocation(clientName);
final IPickUpSpace place = (IPickUpSpace) Namespace.lookup(nsName);
if (place == null) {
throw new IllegalArgumentException("No client place found using name " + clientName);
}
final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(workBundleString.getBytes("8859_1")));
WorkBundle paths = (WorkBundle) ois.readObject();
success = place.enque(paths);
} catch (Exception e) {
logger.warn("WorkSpaceClientEnqueWorker exception", e);
return Response.serverError().entity("WorkSpaceClientEnqueWorker exception:\n" + e.getMessage()).build();
}
if (success) {
// old success from WorkSpaceClientEnqueWorker
// return WORKER_SUCCESS;
return Response.ok().entity("Successful add to the PickUpPlaceClient queue").build();
} else {
// old failure from WorkSpaceClientEnqueWorker
// return new WorkerStatus(WorkerStatus.FAILURE, "WorkSpaceClientEnqueWorker failed, queue full");
return Response.serverError().entity("WorkSpaceClientEnqueWorker failed, queue full").build();
}
} | 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 CommandExecutionResult createBinary(String code, String full, boolean compact) {
final Player player = new PlayerBinary(full, getSkinParam(), ruler, compactByDefault);
players.put(code, player);
return CommandExecutionResult.ok();
} | 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 VFSLeaf createChildLeaf(String name) {
File fNewFile = new File(getBasefile(), name);
try {
if(!fNewFile.getParentFile().exists()) {
fNewFile.getParentFile().mkdirs();
}
if (!fNewFile.createNewFile()) {
log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists");
return null;
}
} catch (Exception e) {
log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e);
return null;
}
return new LocalFileImpl(fNewFile, this);
} | 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 |
void testUri() {
final HttpHeadersBase headers = newHttp2Headers();
assertThat(headers.uri()).isEqualTo(URI.create("https://netty.io/index.html"));
} | 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 |
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
} | 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 setValidation(boolean validation) {
this.validating = validation;
} | 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 |
private ZonedDateTime toZonedDateTime(XMLGregorianCalendar instant) {
if (instant == null) {
return null;
}
return instant.toGregorianCalendar().toZonedDateTime();
} | 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 translate(ServerWindowItemsPacket packet, GeyserSession session) {
Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
if (inventory == null)
return;
inventory.setStateId(packet.getStateId());
for (int i = 0; i < packet.getItems().length; i++) {
GeyserItemStack newItem = GeyserItemStack.from(packet.getItems()[i]);
inventory.setItem(i, newItem, session);
}
InventoryTranslator translator = session.getInventoryTranslator();
if (translator != null) {
translator.updateInventory(session, inventory);
}
session.getPlayerInventory().setCursor(GeyserItemStack.from(packet.getCarriedItem()), session);
InventoryUtils.updateCursor(session);
} | 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 boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultResetPasswordRequestResponse that = (DefaultResetPasswordRequestResponse) o;
return new EqualsBuilder()
.append(userReference, that.userReference)
.append(userEmail, that.userEmail)
.append(verificationCode, that.verificationCode)
.isEquals();
} | 0 | Java | CWE-640 | Weak Password Recovery Mechanism for Forgotten Password | The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak. | https://cwe.mitre.org/data/definitions/640.html | vulnerable |
void setHeadersShouldOnlyOverwriteHeaders() {
final HttpHeadersBase headers1 = newEmptyHeaders();
headers1.add("name", "value");
headers1.add("name1", "value1");
final HttpHeadersBase headers2 = newEmptyHeaders();
headers2.add("name", "newvalue");
headers2.add("name2", "value2");
final HttpHeadersBase expected = newEmptyHeaders();
expected.add("name", "newvalue");
expected.add("name1", "value1");
expected.add("name2", "value2");
headers1.set(headers2);
assertThat(expected).isEqualTo(headers1);
} | 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 SAXReader(boolean validating) {
this.validating = validating;
} | 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 |
private void renderState(FacesContext context) throws IOException {
// Get the view state and write it to the response..
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
String viewStateId = Util.getViewStateId(context);
writer.startUpdate(viewStateId);
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
writer.endUpdate();
ClientWindow window = context.getExternalContext().getClientWindow();
if (null != window) {
String clientWindowId = Util.getClientWindowId(context);
writer.startUpdate(clientWindowId);
writer.writeText(window.getId(), null);
writer.endUpdate();
}
} | 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 boolean isIgnoreComments() {
return ignoreComments;
} | 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 setStripWhitespaceText(boolean stripWhitespaceText) {
this.stripWhitespaceText = stripWhitespaceText;
} | 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 |
private File createTemporaryFolderIn(File parentFolder) throws IOException {
File createdFolder = null;
for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
// Use createTempFile to get a suitable folder name.
String suffix = ".tmp";
File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
String tmpName = tmpFile.toString();
// Discard .tmp suffix of tmpName.
String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
createdFolder = new File(folderName);
if (createdFolder.mkdir()) {
tmpFile.delete();
return createdFolder;
}
tmpFile.delete();
}
throw new IOException("Unable to create temporary directory in: "
+ parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
+ "Last attempted to create: " + createdFolder.toString());
} | 0 | 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 | vulnerable |
protected void after() {
if (!Secret.SECRET.equals(value))
throw new IllegalStateException("Someone tinkered with Secret.SECRET");
Secret.SECRET = null;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void emptyHeaderNameNotAllowed() {
assertThatThrownBy(() -> newEmptyHeaders().add("", "foo"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("malformed header name: <EMPTY>");
} | 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 OldECIESwithAESCBC()
{
super(new CBCBlockCipher(new AESEngine()), 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 |
public void translate(ItemStackRequestPacket packet, GeyserSession session) {
Inventory inventory = session.getOpenInventory();
if (inventory == null)
return;
InventoryTranslator translator = session.getInventoryTranslator();
translator.translateRequests(session, inventory, packet.getRequests());
} | 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 void testLoadMapper_serializade() {
//create a mapper
String mapperId = UUID.randomUUID().toString();
String sessionId = UUID.randomUUID().toString().substring(0, 32);
PersistentMapper sMapper = new PersistentMapper("mapper-to-persist");
PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);
Assert.assertNotNull(pMapper);
dbInstance.commitAndCloseSession();
//load the mapper
PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper);
Assert.assertEquals(pMapper, loadedMapper);
Assert.assertEquals(mapperId, loadedMapper.getMapperId());
Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());
Assert.assertTrue(objReloaded instanceof PersistentMapper);
PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;
Assert.assertEquals("mapper-to-persist", sMapperReloaded.getKey());
} | 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 |
private <T> T unmarshallFromDocument(Document document, Class<T> type) throws SAMLException {
try {
JAXBContext context = JAXBContext.newInstance(type);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<T> element = unmarshaller.unmarshal(document, type);
return element.getValue();
} catch (JAXBException e) {
throw new SAMLException("Unable to unmarshall SAML response", e);
}
} | 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 static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
String terminalWidth) {
initializeSsl();
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.GET);
handleResponse(conn, getStatusCode(conn), terminalWidth);
Authenticator.setDefault(null);
} | 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 |
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
final String compact = arg.get("COMPACT", 0);
final String code = arg.get("CODE", 0);
String full = arg.get("FULL", 0);
if (full == null) {
full = code;
}
final TimingStyle type = TimingStyle.valueOf(arg.get("TYPE", 0).toUpperCase());
return diagram.createRobustConcise(code, full, type, compact != null);
} | 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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
UserFactory.init();
} catch (Throwable e) {
throw new ServletException("AddNewUserServlet: Error initialising user factory." + e);
}
UserManager userFactory = UserFactory.getInstance();
String userID = request.getParameter("userID");
if (userID != null && userID.matches(".*[&<>\"`']+.*")) {
throw new ServletException("User ID must not contain any HTML markup.");
}
String password = request.getParameter("pass1");
boolean hasUser = false;
try {
hasUser = userFactory.hasUser(userID);
} catch (Throwable e) {
throw new ServletException("can't determine if user " + userID + " already exists in users.xml.", e);
}
if (hasUser) {
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/newUser.jsp?action=redo");
dispatcher.forward(request, response);
} else {
final Password pass = new Password();
pass.setEncryptedPassword(UserFactory.getInstance().encryptedPassword(password, true));
pass.setSalt(true);
final User newUser = new User();
newUser.setUserId(userID);
newUser.setPassword(pass);
final HttpSession userSession = request.getSession(false);
userSession.setAttribute("user.modifyUser.jsp", newUser);
// forward the request for proper display
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/userGroupView/users/modifyUser.jsp");
dispatcher.forward(request, response);
}
} | 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 |
void testGetOperations() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertThat(headers.get("Foo")).isEqualTo("1");
final List<String> values = headers.getAll("Foo");
assertThat(values).containsExactly("1", "2");
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.