code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
static void setAttribute(TransformerFactory transformerFactory, String attributeName) {
try {
transformerFactory.setAttribute(attributeName, "");
} catch (IllegalArgumentException iae) {
if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) {
LOGGER.warning("Enabling XXE protection failed. The attribute " + attributeName
+ " is not supported by the TransformerFactory. The " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
+ " system property is used so the XML processing continues in the UNSECURE mode"
+ " with XXE protection disabled!!!");
} else {
LOGGER.severe("Enabling XXE protection failed. The attribute " + attributeName
+ " is not supported by the TransformerFactory. This usually mean an outdated XML processor"
+ " is present on the classpath (e.g. Xerces, Xalan). If you are not able to resolve the issue by"
+ " fixing the classpath, the " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
+ " system property can be used to disable XML External Entity protections."
+ " We don't recommend disabling the XXE as such the XML processor configuration is unsecure!!!", iae);
throw iae;
}
}
} | CWE-611 | 13 |
public void testPullCount() throws IOException {
initializeSsl();
String url = RepoUtils.getRemoteRepoURL() + "/modules/info/" + orgName + "/" + moduleName + "/*/";
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), "", 0, "", "");
conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.GET);
int statusCode = conn.getResponseCode();
if (statusCode == 200) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
Charset.defaultCharset()))) {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Object payload = JSONParser.parse(result.toString());
if (payload instanceof MapValue) {
long pullCount = ((MapValue) payload).getIntValue("totalPullCount");
Assert.assertEquals(pullCount, totalPullCount);
} else {
Assert.fail("error: invalid response received");
}
}
} else {
Assert.fail("error: could not connect to remote repository to find the latest version of module");
}
} | CWE-306 | 79 |
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);
} | CWE-470 | 84 |
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();
}
} | CWE-502 | 15 |
public static boolean copyResource(File file, String filename, File targetDirectory, PathMatcher filter) {
try {
Path path = getResource(file, filename);
if(path == null) {
return false;
}
Path destDir = targetDirectory.toPath();
Files.walkFileTree(path, new CopyVisitor(path, destDir, filter));
PathUtils.closeSubsequentFS(path);
return true;
} catch (IOException e) {
log.error("", e);
return false;
}
} | CWE-22 | 2 |
public RainbowParameters(int[] vi)
{
this.vi = vi;
try
{
checkParams();
}
catch (Exception e)
{
e.printStackTrace();
}
} | CWE-502 | 15 |
public Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = shell.getWorkingDirectory();
try
{
if ( workingDir == null )
{
process = Runtime.getRuntime().exec( getShellCommandline(), environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
} | CWE-78 | 6 |
private HColor getColor(ColorParam colorParam, Stereotype stereo) {
final ISkinParam skinParam = diagram.getSkinParam();
return rose.getHtmlColor(skinParam, stereo, colorParam);
} | CWE-918 | 16 |
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());
} | CWE-347 | 25 |
private boolean isStale(URL source, File target) {
if( source.getProtocol().equals("jar") ) {
// unwrap the jar protocol...
try {
String parts[] = source.getFile().split(Pattern.quote("!"));
source = new URL(parts[0]);
} catch (MalformedURLException e) {
return false;
}
}
File sourceFile=null;
if( source.getProtocol().equals("file") ) {
sourceFile = new File(source.getFile());
}
if( sourceFile!=null && sourceFile.exists() ) {
if( sourceFile.lastModified() > target.lastModified() ) {
return true;
}
}
return false;
} | CWE-94 | 14 |
public ResetPasswordRequestResponse requestResetPassword(UserReference userReference) throws ResetPasswordException
{
this.checkUserReference(userReference);
UserProperties userProperties = this.userPropertiesResolver.resolve(userReference);
InternetAddress email = userProperties.getEmail();
if (email == null) {
String exceptionMessage =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noEmail");
throw new ResetPasswordException(exceptionMessage);
}
DocumentUserReference documentUserReference = (DocumentUserReference) userReference;
DocumentReference reference = documentUserReference.getReference();
XWikiContext context = this.contextProvider.get();
try {
XWikiDocument userDocument = context.getWiki().getDocument(reference, context);
if (userDocument.getXObject(LDAP_CLASS_REFERENCE) != null) {
String exceptionMessage =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.ldapUser",
userReference.toString());
throw new ResetPasswordException(exceptionMessage);
}
BaseObject xObject = userDocument.getXObject(RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, context);
String verificationCode = context.getWiki().generateRandomString(30);
xObject.set(VERIFICATION_PROPERTY, verificationCode, context);
String saveComment =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment");
context.getWiki().saveDocument(userDocument, saveComment, true, context);
return new DefaultResetPasswordRequestResponse(userReference, email, verificationCode);
} catch (XWikiException e) {
throw new ResetPasswordException("Error when reading user document to perform reset password request.", e);
}
} | CWE-640 | 20 |
public static IRubyObject from_document(ThreadContext context, IRubyObject klazz, IRubyObject document) {
XmlDocument doc = ((XmlDocument) ((XmlNode) document).document(context));
RubyArray errors = (RubyArray) doc.getInstanceVariable("@errors");
if (!errors.isEmpty()) {
throw ((XmlSyntaxError) errors.first()).toThrowable();
}
DOMSource source = new DOMSource(doc.getDocument());
IRubyObject uri = doc.url(context);
if (!uri.isNil()) {
source.setSystemId(uri.convertToString().asJavaString());
}
return getSchema(context, (RubyClass)klazz, source);
} | CWE-611 | 13 |
void doubleQuote() {
final PathAndQuery res = PathAndQuery.parse("/\"?\"");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/%22");
assertThat(res.query()).isEqualTo("%22");
} | CWE-22 | 2 |
public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) {
CacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils
.deserialize(cacheAllocationRequestBytes);
return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(
getJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances()));
} | CWE-502 | 15 |
public boolean isValidating() {
return validating;
} | CWE-611 | 13 |
public void drawU(UGraphic ug) {
ug = ug.apply(backColor.bg()).apply(borderColor);
final URectangle rect = new URectangle(dim.getWidth(), dim.getHeight()).rounded(rounded);
rect.setDeltaShadow(shadowing);
ug.apply(stroke).draw(rect);
final double yLine = titleHeight + attributeHeight;
ug = ug.apply(imgBackcolor.bg());
final double thickness = stroke.getThickness();
final URectangle inner = new URectangle(dim.getWidth() - 4 * thickness,
dim.getHeight() - titleHeight - 4 * thickness - attributeHeight).rounded(rounded);
ug.apply(imgBackcolor).apply(new UTranslate(2 * thickness, yLine + 2 * thickness)).draw(inner);
if (titleHeight > 0) {
ug.apply(stroke).apply(UTranslate.dy(yLine)).draw(ULine.hline(dim.getWidth()));
}
if (attributeHeight > 0) {
ug.apply(stroke).apply(UTranslate.dy(yLine - attributeHeight)).draw(ULine.hline(dim.getWidth()));
}
} | CWE-918 | 16 |
public String getShortDescription() {
if(note != null) {
return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
} else {
return Messages.Cause_RemoteCause_ShortDescription(addr);
}
} | CWE-79 | 1 |
public static String applySorting(String query, Sort sort, String alias) {
Assert.hasText(query);
if (null == sort || !sort.iterator().hasNext()) {
return query;
}
StringBuilder builder = new StringBuilder(query);
if (!ORDER_BY.matcher(query).matches()) {
builder.append(" order by ");
} else {
builder.append(", ");
}
Set<String> aliases = getOuterJoinAliases(query);
for (Order order : sort) {
builder.append(getOrderClause(aliases, alias, order)).append(", ");
}
builder.delete(builder.length() - 2, builder.length());
return builder.toString();
} | CWE-89 | 0 |
public static boolean isAbsolute(String url)
{
if (url.startsWith("//")) // //www.domain.com/start
{
return true;
}
if (url.startsWith("/")) // /somePage.html
{
return false;
}
boolean result = false;
try
{
URI uri = new URI(url);
result = uri.isAbsolute();
}
catch (URISyntaxException e) {} //Ignore
return result;
} | CWE-601 | 11 |
public void encodeByteArray() {
Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT);
packet.data = "abc".getBytes(Charset.forName("UTF-8"));
packet.id = 23;
packet.nsp = "/cool";
Helpers.testBin(packet);
} | CWE-476 | 46 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (keySpec == null) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
try {
setup(ad);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(iv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
try {
int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
cipher.doFinal(plaintext, plaintextOffset + result);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
return dataLen;
} | CWE-125 | 47 |
public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZipAPKTool("", srcFolder, zip);
zip.flush();
}
} | CWE-22 | 2 |
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new ECDSA5Test());
} | CWE-347 | 25 |
public void testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
} | CWE-379 | 83 |
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);
} | CWE-306 | 79 |
public void setDocumentFactory(DocumentFactory documentFactory) {
this.factory = documentFactory;
} | CWE-611 | 13 |
parse_io(ThreadContext context,
IRubyObject klazz,
IRubyObject data,
IRubyObject enc)
{
//int encoding = (int)enc.convertToInteger().getLongValue();
final Ruby runtime = context.runtime;
XmlSaxParserContext ctx = newInstance(runtime, (RubyClass) klazz);
ctx.initialize(runtime);
ctx.setIOInputSource(context, data, runtime.getNil());
return ctx;
} | CWE-241 | 68 |
public void setIgnoreComments(boolean ignoreComments) {
this.ignoreComments = ignoreComments;
} | CWE-611 | 13 |
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;
} | CWE-787 | 24 |
public RoundedContainer(Dimension2D dim, double titleHeight, double attributeHeight, HColor borderColor,
HColor backColor, HColor imgBackcolor, UStroke stroke, double rounded, double shadowing) {
if (dim.getWidth() == 0) {
throw new IllegalArgumentException();
}
this.rounded = rounded;
this.dim = dim;
this.imgBackcolor = imgBackcolor;
this.titleHeight = titleHeight;
this.borderColor = borderColor;
this.backColor = backColor;
this.attributeHeight = attributeHeight;
this.stroke = stroke;
this.shadowing = shadowing;
} | CWE-918 | 16 |
public DefaultFileSystemResourceLoader(Path path) {
this.baseDirPath = Optional.of(path);
} | CWE-22 | 2 |
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;
} | CWE-125 | 47 |
public boolean isStripWhitespaceText() {
return stripWhitespaceText;
} | CWE-611 | 13 |
public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
.Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssMtPrivateKey.getIndex())
.withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssMtPrivateKey.getPublicSeed())
.withRoot(xmssMtPrivateKey.getRoot());
if (xmssMtPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState()));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
} | CWE-502 | 15 |
public static List<String> checkLockedFileBeforeUnzipNonStrict(VFSLeaf zipLeaf, VFSContainer targetDir, Identity identity) {
List<String> lockedFiles = new ArrayList<>();
VFSLockManager vfsLockManager = CoreSpringFactory.getImpl(VFSLockManager.class);
try(InputStream in = zipLeaf.getInputStream();
net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in);) {
// unzip files
net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry();
while (oEntr != null) {
if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
if (oEntr.isDirectory()) {
// skip MacOSX specific metadata directory
// directories aren't locked
oZip.closeEntry();
oEntr = oZip.getNextEntry();
continue;
} else {
// search file
VFSContainer createIn = targetDir;
String name = oEntr.getName();
// check if entry has directories which did not show up as
// directories above
int dirSepIndex = name.lastIndexOf('/');
if (dirSepIndex == -1) {
// try it windows style, backslash is also valid format
dirSepIndex = name.lastIndexOf('\\');
}
if (dirSepIndex > 0) {
// get subdirs
createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, false);
if (createIn == null) {
//sub directories don't exist, and aren't locked
oZip.closeEntry();
oEntr = oZip.getNextEntry();
continue;
}
name = name.substring(dirSepIndex + 1);
}
VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
if(vfsLockManager.isLockedForMe(newEntry, identity, VFSLockApplicationType.vfs, null)) {
lockedFiles.add(name);
}
}
}
oZip.closeEntry();
oEntr = oZip.getNextEntry();
}
} catch (IOException e) {
return null;
}
return lockedFiles;
} | CWE-22 | 2 |
private static Stream<Arguments> provideFilesAndExpectedExceptionType() {
return Stream.of(
Arguments.of("abnormal/corrupt-header.rar", CorruptHeaderException.class),
Arguments.of("abnormal/mainHeaderNull.rar", BadRarArchiveException.class)
);
} | CWE-835 | 42 |
protected SymbolContext getContextLegacy() {
if (UseStyle.useBetaStyle() == false)
return new SymbolContext(HColorUtils.COL_D7E0F2, HColorUtils.COL_038048).withStroke(new UStroke(2));
final HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(),
skinParam.getIHtmlColorSet());
final HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(),
skinParam.getIHtmlColorSet());
return new SymbolContext(backgroundColor, lineColor).withStroke(getStroke());
} | CWE-918 | 16 |
private void decodeTest()
{
EllipticCurve curve = new EllipticCurve(
new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"));
if (!p.getAffineX().equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16)))
{
fail("x uncompressed incorrectly");
}
if (!p.getAffineY().equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16)))
{
fail("y uncompressed incorrectly");
}
} | CWE-347 | 25 |
public void testGetShellCommandLineNonWindows()
throws Exception
{
Commandline cmd = new Commandline( new BourneShell() );
cmd.setExecutable( "/usr/bin" );
cmd.addArguments( new String[] {
"a",
"b"
} );
String[] shellCommandline = cmd.getShellCommandline();
assertEquals( "Command line size", 3, shellCommandline.length );
assertEquals( "/bin/sh", shellCommandline[0] );
assertEquals( "-c", shellCommandline[1] );
if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
{
assertEquals( "\\usr\\bin a b", shellCommandline[2] );
}
else
{
assertEquals( "/usr/bin a b", shellCommandline[2] );
}
} | CWE-78 | 6 |
public Document read(URL url) throws DocumentException {
String systemID = url.toExternalForm();
InputSource source = new InputSource(systemID);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
} | CWE-611 | 13 |
protected Response attachToPost(Long messageKey, String filename, InputStream file, HttpServletRequest request) {
//load message
Message mess = fom.loadMessage(messageKey);
if(mess == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
if(!forum.equalsByPersistableKey(mess.getForum())) {
return Response.serverError().status(Status.CONFLICT).build();
}
return attachToPost(mess, filename, file, request);
} | CWE-22 | 2 |
public static int sharedKeyLength(final JWEAlgorithm alg, final EncryptionMethod enc)
throws JOSEException {
if (alg.equals(JWEAlgorithm.ECDH_ES)) {
int length = enc.cekBitLength();
if (length == 0) {
throw new JOSEException("Unsupported JWE encryption method " + enc);
}
return length;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW)) {
return 128;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A192KW)) {
return 192;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) {
return 256;
} else {
throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(
alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS));
}
} | CWE-347 | 25 |
public void testGetChunk() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf1 = test.getChunk(1024);
assertEquals(buf1.readerIndex(), 0);
assertEquals(buf1.writerIndex(), 1024);
ByteBuf buf2 = test.getChunk(1024);
assertEquals(buf2.readerIndex(), 0);
assertEquals(buf2.writerIndex(), 1024);
assertFalse("Arrays should not be equal",
Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
} finally {
test.delete();
}
} | CWE-379 | 83 |
public void sendError(int sc, String msg) throws IOException {
if (isIncluding()) {
Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error",
new String[] { "" + sc, msg });
return;
}
Logger.log(Logger.DEBUG, Launcher.RESOURCES,
"WinstoneResponse.SendingError", new String[] { "" + sc, msg });
if ((this.webAppConfig != null) && (this.req != null)) {
RequestDispatcher rd = this.webAppConfig
.getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);
if (rd != null) {
try {
rd.forward(this.req, this);
return;
} catch (IllegalStateException err) {
throw err;
} catch (IOException err) {
throw err;
} catch (Throwable err) {
Logger.log(Logger.WARNING, Launcher.RESOURCES,
"WinstoneResponse.ErrorInErrorPage", new String[] {
rd.getName(), sc + "" }, err);
return;
}
}
}
// If we are here there was no webapp and/or no request object, so
// show the default error page
if (this.errorStatusCode == null) {
this.statusCode = sc;
}
String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
new String[] { sc + "", (msg == null ? "" : msg), "",
Launcher.RESOURCES.getString("ServerVersion"),
"" + new Date() });
setContentLength(output.getBytes(getCharacterEncoding()).length);
Writer out = getWriter();
out.write(output);
out.flush();
} | CWE-79 | 1 |
public void view(@RequestParam String filename,
@RequestParam(required = false) String base,
@RequestParam(required = false) Integer tailLines,
HttpServletResponse response) throws IOException {
securityCheck(filename);
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
Path path = loggingPath(base);
FileProvider fileProvider = getFileProvider(path);
if (tailLines != null) {
fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines);
}
else {
fileProvider.streamContent(path, filename, response.getOutputStream());
}
} | CWE-22 | 2 |
void empty() {
final PathAndQuery res = PathAndQuery.parse(null);
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/");
assertThat(res.query()).isNull();
final PathAndQuery res2 = PathAndQuery.parse("");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/");
assertThat(res2.query()).isNull();
final PathAndQuery res3 = PathAndQuery.parse("?");
assertThat(res3).isNotNull();
assertThat(res3.path()).isEqualTo("/");
assertThat(res3.query()).isEqualTo("");
} | CWE-22 | 2 |
protected XMLReader createXMLReader() throws SAXException {
return SAXHelper.createXMLReader(isValidating());
} | CWE-611 | 13 |
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
} | CWE-22 | 2 |
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;
}
} | CWE-918 | 16 |
public void write(byte[] b, int offset, int length) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (offset < 0 || offset + length > b.length) {
throw new ArrayIndexOutOfBoundsException();
}
write(fd, b, offset, length);
} | CWE-190 | 19 |
private static String encodeToPercents(Bytes value, boolean isPath) {
final BitSet allowedChars = isPath ? ALLOWED_PATH_CHARS : ALLOWED_QUERY_CHARS;
final int length = value.length;
boolean needsEncoding = false;
for (int i = 0; i < length; i++) {
if (!allowedChars.get(value.data[i] & 0xFF)) {
needsEncoding = true;
break;
}
}
if (!needsEncoding) {
// Deprecated, but it fits perfect for our use case.
// noinspection deprecation
return new String(value.data, 0, 0, length);
}
final StringBuilder buf = new StringBuilder(length);
for (int i = 0; i < length; i++) {
final int b = value.data[i] & 0xFF;
if (b == PERCENT_ENCODING_MARKER && (i + 1) < length) {
final int marker = value.data[i + 1] & 0xFF;
final String percentEncodedChar = MARKER_TO_PERCENT_ENCODED_CHAR[marker];
if (percentEncodedChar != null) {
buf.append(percentEncodedChar);
i++;
continue;
}
}
if (allowedChars.get(b)) {
buf.append((char) b);
} else if (b == ' ') {
if (isPath) {
buf.append("%20");
} else {
buf.append('+');
}
} else {
buf.append('%');
appendHexNibble(buf, b >>> 4);
appendHexNibble(buf, b & 0xF);
}
}
return buf.toString();
} | CWE-22 | 2 |
public synchronized <T extends Result> T setResult(Class<T> resultClass) throws SQLException {
checkFreed();
initialize();
if (resultClass == null || DOMResult.class.equals(resultClass)) {
domResult = new DOMResult();
active = true;
return (T) domResult;
} else if (SAXResult.class.equals(resultClass)) {
try {
SAXTransformerFactory transformerFactory =
(SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();
stringWriter = new StringWriter();
transformerHandler.setResult(new StreamResult(stringWriter));
active = true;
return (T) new SAXResult(transformerHandler);
} catch (TransformerException te) {
throw new PSQLException(GT.tr("Unable to create SAXResult for SQLXML."),
PSQLState.UNEXPECTED_ERROR, te);
}
} else if (StreamResult.class.equals(resultClass)) {
stringWriter = new StringWriter();
active = true;
return (T) new StreamResult(stringWriter);
} else if (StAXResult.class.equals(resultClass)) {
stringWriter = new StringWriter();
try {
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter);
active = true;
return (T) new StAXResult(xsw);
} catch (XMLStreamException xse) {
throw new PSQLException(GT.tr("Unable to create StAXResult for SQLXML"),
PSQLState.UNEXPECTED_ERROR, xse);
}
}
throw new PSQLException(GT.tr("Unknown XML Result class: {0}", resultClass),
PSQLState.INVALID_PARAMETER_TYPE);
} | CWE-611 | 13 |
public Directory read(final ImageInputStream input) throws IOException {
Validate.notNull(input, "input");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
// TODO: Consider parsing using SAX?
// TODO: Determine encoding and parse using a Reader...
// TODO: Refactor scanner to return inputstream?
// TODO: Be smarter about ASCII-NULL termination/padding (the SAXParser aka Xerces DOMParser doesn't like it)...
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler());
Document document = builder.parse(new InputSource(IIOUtil.createStreamAdapter(input)));
// XMLSerializer serializer = new XMLSerializer(System.err, System.getProperty("file.encoding"));
// serializer.serialize(document);
String toolkit = getToolkit(document);
Node rdfRoot = document.getElementsByTagNameNS(XMP.NS_RDF, "RDF").item(0);
NodeList descriptions = document.getElementsByTagNameNS(XMP.NS_RDF, "Description");
return parseDirectories(rdfRoot, descriptions, toolkit);
}
catch (SAXException e) {
throw new IIOException(e.getMessage(), e);
}
catch (ParserConfigurationException e) {
throw new RuntimeException(e); // TODO: Or IOException?
}
} | CWE-611 | 13 |
public static HColor noGradient(HColor color) {
if (color instanceof HColorGradient) {
return ((HColorGradient) color).getColor1();
}
return color;
} | CWE-918 | 16 |
public void testMatchUseNotSpecifiedOrSignature() {
JWKMatcher matcher = new JWKMatcher.Builder().keyUses(KeyUse.SIGNATURE, null).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.SIGNATURE).build()));
assertTrue(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3").keyUse(KeyUse.ENCRYPTION).build()));
assertEquals("use=[sig, null]", matcher.toString());
} | CWE-347 | 25 |
protected EntityResolver createDefaultEntityResolver(String systemId) {
String prefix = null;
if ((systemId != null) && (systemId.length() > 0)) {
int idx = systemId.lastIndexOf('/');
if (idx > 0) {
prefix = systemId.substring(0, idx + 1);
}
}
return new SAXEntityResolver(prefix);
} | CWE-611 | 13 |
public boolean isIncludeInternalDTDDeclarations() {
return includeInternalDTDDeclarations;
} | CWE-611 | 13 |
static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) {
Ruby runtime = context.getRuntime();
XmlRelaxng xmlRelaxng = (XmlRelaxng) NokogiriService.XML_RELAXNG_ALLOCATOR.allocate(runtime, klazz);
xmlRelaxng.setInstanceVariable("@errors", runtime.newEmptyArray());
try {
Schema schema = xmlRelaxng.getSchema(source, context);
xmlRelaxng.setVerifier(schema.newVerifier());
return xmlRelaxng;
} catch (VerifierConfigurationException ex) {
throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage());
}
} | CWE-611 | 13 |
public boolean isResetPasswordSent()
{
// If there is no form and we see an info box, then the request was sent.
return !getDriver().hasElementWithoutWaiting(By.cssSelector("#resetPasswordForm"))
&& messageBox.getText().contains("An e-mail was sent to");
} | CWE-640 | 20 |
public SAXReader(String xmlReaderClassName, boolean validating)
throws SAXException {
if (xmlReaderClassName != null) {
this.xmlReader = XMLReaderFactory
.createXMLReader(xmlReaderClassName);
}
this.validating = validating;
} | CWE-611 | 13 |
private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException {
Headers headers = pExchange.getResponseHeaders();
if (pJson != null) {
headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
pExchange.sendResponseHeaders(200, 0);
Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8");
IoUtil.streamResponseAndClose(writer, pJson, callback);
} else {
headers.set("Content-Type", "text/plain");
pExchange.sendResponseHeaders(200,-1);
}
} | CWE-79 | 1 |
public VideoMetadata readVideoMetadataFile(OLATResource videoResource){
VFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);
VFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);
try {
return (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);
} catch (Exception e) {
log.error("Error while parsing XStream file for videoResource::{}", videoResource, e);
// return an empty, so at least it displays something and not an error
VideoMetadata meta = new VideoMetadataImpl();
meta.setWidth(800);
meta.setHeight(600);
return meta;
}
} | CWE-91 | 78 |
private static IRubyObject getSchema(ThreadContext context, RubyClass klazz, Source source) {
String moduleName = klazz.getName();
if ("Nokogiri::XML::Schema".equals(moduleName)) {
return XmlSchema.createSchemaInstance(context, klazz, source);
} else if ("Nokogiri::XML::RelaxNG".equals(moduleName)) {
return XmlRelaxng.createSchemaInstance(context, klazz, source);
}
return context.getRuntime().getNil();
} | CWE-611 | 13 |
public static IRubyObject read_memory(ThreadContext context, IRubyObject klazz, IRubyObject content) {
String data = content.convertToString().asJavaString();
return getSchema(context, (RubyClass) klazz, new StreamSource(new StringReader(data)));
} | CWE-611 | 13 |
public DocumentFactory getDocumentFactory() {
if (factory == null) {
factory = DocumentFactory.getInstance();
}
return factory;
} | CWE-611 | 13 |
public boolean isMergeAdjacentText() {
return mergeAdjacentText;
} | CWE-611 | 13 |
public void encodeDeepBinaryJSONWithNullValue() throws JSONException {
JSONObject data = new JSONObject("{a: \"b\", c: 4, e: {g: null}, h: null}");
data.put("h", new byte[9]);
Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
packet.data = data;
packet.nsp = "/";
packet.id = 600;
Helpers.testBin(packet);
} | CWE-476 | 46 |
private void checkParams()
throws Exception
{
if (vi == null)
{
throw new Exception("no layers defined.");
}
if (vi.length > 1)
{
for (int i = 0; i < vi.length - 1; i++)
{
if (vi[i] >= vi[i + 1])
{
throw new Exception(
"v[i] has to be smaller than v[i+1]");
}
}
}
else
{
throw new Exception(
"Rainbow needs at least 1 layer, such that v1 < v2.");
}
} | CWE-470 | 84 |
public void testEscapeSingleQuotesOnArgument()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { "arg'withquote" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertEquals("cd /usr/bin && chmod 'arg'\\''withquote'", shellCommandLine.get(shellCommandLine.size() - 1));
} | CWE-78 | 6 |
public XMLFilter getXMLFilter() {
return xmlFilter;
} | CWE-611 | 13 |
public URIDryConverter(URI base, Map<PackageID, Manifest> dependencyManifests, boolean isBuild) {
super(base, dependencyManifests, isBuild);
this.base = URI.create(base.toString() + "/modules/info/");
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
proxy = getProxy();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
// ignore errors
}
} | CWE-306 | 79 |
private AuthnRequestParseResult parseRequest(byte[] xmlBytes) throws SAMLException {
String xml = new String(xmlBytes, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("SAMLRequest XML is\n{}", xml);
}
AuthnRequestParseResult result = new AuthnRequestParseResult();
result.document = parseFromBytes(xmlBytes);
result.authnRequest = unmarshallFromDocument(result.document, AuthnRequestType.class);
result.request = new AuthenticationRequest();
result.request.xml = xml;
result.request.id = result.authnRequest.getID();
result.request.issuer = result.authnRequest.getIssuer().getValue();
result.request.issueInstant = result.authnRequest.getIssueInstant().toGregorianCalendar().toZonedDateTime();
NameIDPolicyType nameIdPolicyType = result.authnRequest.getNameIDPolicy();
if (nameIdPolicyType == null) {
result.request.nameIdFormat = NameIDFormat.EmailAddress;
} else {
result.request.nameIdFormat = NameIDFormat.fromSAMLFormat(nameIdPolicyType.getFormat());
}
result.request.version = result.authnRequest.getVersion();
return result;
} | CWE-611 | 13 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (keySpec == null) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
try {
setup(ad);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(iv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
try {
int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
cipher.doFinal(plaintext, plaintextOffset + result);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
return dataLen;
} | CWE-787 | 24 |
public void testCreateHttpUrlConnection() {
HttpURLConnection conn;
// Test without proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Assert.assertNotNull(conn);
// Test with the proxy
conn = createHttpUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
Assert.assertNotNull(conn);
} | CWE-306 | 79 |
public static Object deserialize(byte[] data)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
} | CWE-502 | 15 |
public DefaultFileSystemResourceLoader(File baseDirPath) {
this.baseDirPath = Optional.of(baseDirPath.toPath());
} | CWE-22 | 2 |
private static void createBaloInHomeRepo(HttpURLConnection conn, String modulePathInBaloCache,
String moduleNameWithOrg, boolean isNightlyBuild, String newUrl, String contentDisposition) {
long responseContentLength = conn.getContentLengthLong();
if (responseContentLength <= 0) {
createError("invalid response from the server, please try again");
}
String resolvedURI = conn.getHeaderField(RESOLVED_REQUESTED_URI);
if (resolvedURI == null || resolvedURI.equals("")) {
resolvedURI = newUrl;
}
String[] uriParts = resolvedURI.split("/");
String moduleVersion = uriParts[uriParts.length - 3];
validateModuleVersion(moduleVersion);
String baloFile = getBaloFileName(contentDisposition, uriParts[uriParts.length - 1]);
Path baloCacheWithModulePath = Paths.get(modulePathInBaloCache, moduleVersion);
//<user.home>.ballerina/balo_cache/<org-name>/<module-name>/<module-version>
Path baloPath = Paths.get(baloCacheWithModulePath.toString(), baloFile);
if (baloPath.toFile().exists()) {
createError("module already exists in the home repository: " + baloPath.toString());
}
createBaloFileDirectory(baloCacheWithModulePath);
writeBaloFile(conn, baloPath, moduleNameWithOrg + ":" + moduleVersion, responseContentLength);
handleNightlyBuild(isNightlyBuild, baloCacheWithModulePath);
} | CWE-306 | 79 |
public void testCurveCheckOk()
throws Exception {
ECPublicKey ephemeralPublicKey = generateECPublicKey(ECKey.Curve.P_256);
ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);
ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey);
} | CWE-347 | 25 |
public void setStripWhitespaceText(boolean stripWhitespaceText) {
this.stripWhitespaceText = stripWhitespaceText;
} | CWE-611 | 13 |
private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
final Point2D corner = getPosition(elkNode);
final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());
PackageStyle packageStyle = group.getPackageStyle();
final ISkinParam skinParam = diagram.getSkinParam();
if (packageStyle == null)
packageStyle = skinParam.packageStyle();
final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();
final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
.getMergedStyle(skinParam.getCurrentStyleBuilder());
final double shadowing = style.value(PName.Shadowing).asDouble();
final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);
HColor backColor = getBackColor(umlDiagramType);
backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),
group.getUSymbol());
final double roundCorner = group.getUSymbol() == null ? 0
: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());
final TextBlock ztitle = getTitleBlock(group);
final TextBlock zstereo = TextBlockUtils.empty(0, 0);
final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);
final HColor borderColor = HColorUtils.BLACK;
decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
skinParam.getStereotypeAlignment(), 0);
// // Print a simple rectangle right now
// ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
} | CWE-918 | 16 |
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
} | CWE-601 | 11 |
public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()
{
Shell sh = newShell();
sh.setWorkingDirectory( "\\usr\\local\\'something else'" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd \"\\usr\\local\\\'something else\'\" && chmod", executable );
} | CWE-78 | 6 |
public void performTest()
throws Exception
{
testKeyConversion();
testAdaptiveKeyConversion();
decodeTest();
testECDSA239bitPrime();
testECDSA239bitBinary();
testGeneration();
testKeyPairGenerationWithOIDs();
testNamedCurveParameterPreservation();
testNamedCurveSigning();
testBSI();
testMQVwithHMACOnePass();
testAlgorithmParameters();
} | CWE-347 | 25 |
private JsonNode yamlPathToJson(Path path) throws IOException {
Yaml reader = new Yaml();
ObjectMapper mapper = new ObjectMapper();
Path p;
try (InputStream in = Files.newInputStream(path)) {
return mapper.valueToTree(reader.load(in));
}
} | CWE-502 | 15 |
protected HtmlRenderable htmlBody() {
return HtmlElement.li().content(
HtmlElement.span(HtmlAttribute.cssClass("artifact")).content(
HtmlElement.a(HtmlAttribute.href(getUrl()))
.content(getFileName())
)
);
} | CWE-79 | 1 |
public PlayerClock(String title, ISkinParam skinParam, TimingRuler ruler, int period, int pulse, int offset,
boolean compact) {
super(title, skinParam, ruler, compact);
this.displayTitle = title.length() > 0;
this.period = period;
this.pulse = pulse;
this.offset = offset;
this.suggestedHeight = 30;
} | CWE-918 | 16 |
public void testByteSerialization() throws Exception {
final IBaseDataObject d = DataObjectFactory.getInstance("abc".getBytes(), "testfile", Form.UNKNOWN);
final byte[] bytes = PayloadUtil.serializeToBytes(d);
final String s1 = new String(bytes);
assertTrue("Serializedion must include data from payload", s1.indexOf("abc") > -1);
} | CWE-502 | 15 |
public static int beta() {
final int beta = 1;
return beta;
} | CWE-918 | 16 |
protected List<String> getRawCommandLine( String executable, String[] arguments )
{
List<String> commandLine = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
if ( executable != null )
{
String preamble = getExecutionPreamble();
if ( preamble != null )
{
sb.append( preamble );
}
if ( isQuotedExecutableEnabled() )
{
char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );
sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false ) );
}
else
{
sb.append( getExecutable() );
}
}
for ( int i = 0; i < arguments.length; i++ )
{
if ( sb.length() > 0 )
{
sb.append( " " );
}
if ( isQuotedArgumentsEnabled() )
{
char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() );
sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) );
}
else
{
sb.append( arguments[i] );
}
}
commandLine.add( sb.toString() );
return commandLine;
} | CWE-78 | 6 |
public static int version() {
return 1202204;
} | CWE-918 | 16 |
public static AlgorithmMode resolveAlgorithmMode(final JWEAlgorithm alg)
throws JOSEException {
if (alg.equals(JWEAlgorithm.ECDH_ES)) {
return AlgorithmMode.DIRECT;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW) ||
alg.equals(JWEAlgorithm.ECDH_ES_A192KW) ||
alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) {
return AlgorithmMode.KW;
} else {
throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(
alg,
ECDHCryptoProvider.SUPPORTED_ALGORITHMS));
}
} | CWE-347 | 25 |
public static Path visit(File file, String filename, FileVisitor<Path> visitor)
throws IOException, IllegalArgumentException {
if(!StringHelper.containsNonWhitespace(filename)) {
filename = file.getName();
}
Path fPath = null;
if(file.isDirectory()) {
fPath = file.toPath();
} else if(filename != null && filename.toLowerCase().endsWith(".zip")) {
try {
fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/");
} catch (ProviderNotFoundException | ServiceConfigurationError e) {
throw new IOException("Unreadable file with .zip extension: " + file, e);
}
} else {
fPath = file.toPath();
}
if(fPath != null) {
Files.walkFileTree(fPath, visitor);
}
return fPath;
} | CWE-22 | 2 |
public static void beforeClass() throws IOException {
final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) r.nextInt(255);
}
tmp = File.createTempFile("netty-traffic", ".tmp");
tmp.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tmp);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
} | CWE-378 | 80 |
private RDFDescription parseAsResource(Node node) {
// See: http://www.w3.org/TR/REC-rdf-syntax/#section-Syntax-parsetype-resource
List<Entry> entries = new ArrayList<Entry>();
for (Node child : asIterable(node.getChildNodes())) {
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
entries.add(new XMPEntry(child.getNamespaceURI() + child.getLocalName(), child.getLocalName(), getChildTextValue(child)));
}
return new RDFDescription(entries);
} | CWE-611 | 13 |
public static long compileTime() {
return 1649510957985L;
} | CWE-918 | 16 |
protected SymbolContext getContextLegacy() {
throw new UnsupportedOperationException();
} | CWE-918 | 16 |
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);
encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
ghash.update(ciphertext, ciphertextOffset, length);
ghash.pad(ad != null ? ad.length : 0, length);
ghash.finish(ciphertext, ciphertextOffset + length, 16);
for (int index = 0; index < 16; ++index)
ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
return length + 16;
} | CWE-787 | 24 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
poly.update(ciphertext, ciphertextOffset, dataLen);
finish(ad, dataLen);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | CWE-125 | 47 |
public AsciiString generateSessionId() {
ThreadLocalRandom random = ThreadLocalRandom.current();
UUID uuid = new UUID(random.nextLong(), random.nextLong());
return AsciiString.of(uuid.toString());
} | CWE-338 | 21 |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String filename = file.getFileName().toString();
Path normalizedPath = file.normalize();
if(!normalizedPath.startsWith(destDir)) {
throw new IOException("Invalid ZIP");
}
if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
resetAndCopyProperties(file, destFile);
} else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
final Path destFile = Paths.get(mediaDir.toString(), file.toString());
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
}
return FileVisitResult.CONTINUE;
} | CWE-22 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.