code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
public static void serializeToStream(final OutputStream os, final Object payload) throws IOException { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(os); oos.writeObject(payload); } finally { if (oos != null) { try { oos.close(); } catch (IOException ignore) { // empty catch block } } } }
CWE-502
15
public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable { File file = File.createTempFile("netty-", ".tmp"); file.deleteOnExit(); final FileOutputStream out = new FileOutputStream(file); out.write(data); out.close(); sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { // Just drop the message. } }); cb.handler(new ChannelInboundHandlerAdapter()); Channel sc = sb.bind().sync().channel(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); // Request file region which is bigger then the underlying file. FileRegion region = new DefaultFileRegion( new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024); assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class)); cc.close().sync(); sc.close().sync(); }
CWE-378
80
public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; }
CWE-611
13
public ModelAndView recover(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String usernameOrEmail = StringUtils.trimToNull(request.getParameter("usernameOrEmail")); if (usernameOrEmail != null) { map.put("usernameOrEmail", usernameOrEmail); User user = getUserByUsernameOrEmail(usernameOrEmail); boolean captchaOk; if (settingsService.isCaptchaEnabled()) { String recaptchaResponse = request.getParameter("g-recaptcha-response"); ReCaptcha captcha = new ReCaptcha(settingsService.getRecaptchaSecretKey()); captchaOk = recaptchaResponse != null && captcha.isValid(recaptchaResponse); } else { captchaOk = true; } if (!captchaOk) { map.put("error", "recover.error.invalidcaptcha"); } else if (user == null) { map.put("error", "recover.error.usernotfound"); } else if (user.getEmail() == null) { map.put("error", "recover.error.noemail"); } else { String password = RandomStringUtils.randomAlphanumeric(8); if (emailPassword(password, user.getUsername(), user.getEmail())) { map.put("sentTo", user.getEmail()); user.setLdapAuthenticated(false); user.setPassword(password); securityService.updateUser(user); } else { map.put("error", "recover.error.sendfailed"); } } } if (settingsService.isCaptchaEnabled()) { map.put("recaptchaSiteKey", settingsService.getRecaptchaSiteKey()); } return new ModelAndView("recover", "model", map); }
CWE-335
81
public static XStream createXStreamInstance() { return new EnhancedXStream(false); }
CWE-91
78
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.write(window.getId()); writer.endUpdate(); } }
CWE-79
1
public void tearDown() throws Exception { if(embeddedServer != null) embeddedServer.extinguish(); }
CWE-22
2
void resetPasswordUnexistingUser() throws Exception { when(this.userReference.toString()).thenReturn("user:Foobar"); when(this.userManager.exists(this.userReference)).thenReturn(false); String exceptionMessage = "User [user:Foobar] doesn't exist"; when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser", "user:Foobar")).thenReturn(exceptionMessage); ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class, () -> this.resetPasswordManager.resetPassword(this.userReference, "some password")); assertEquals(exceptionMessage, resetPasswordException.getMessage()); }
CWE-640
20
setImmediate(() => { if (!this.pendingPublishRequestCount) { return; } const starving_subscription = this._find_starving_subscription(); if (starving_subscription) { doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id); starving_subscription.process_subscription(); } });
CWE-770
37
private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException { OutputStream out = null; try { Headers headers = pExchange.getResponseHeaders(); if (pJson != null) { headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8"); String json = pJson.toJSONString(); String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()); String content = callback == null ? json : callback + "(" + json + ");"; byte[] response = content.getBytes("UTF8"); pExchange.sendResponseHeaders(200,response.length); out = pExchange.getResponseBody(); out.write(response); } else { headers.set("Content-Type", "text/plain"); pExchange.sendResponseHeaders(200,-1); } } finally { if (out != null) { // Always close in order to finish the request. // Otherwise the thread blocks. out.close(); } } }
CWE-79
1
public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); }
CWE-22
2
private <T> Document marshallToDocument(JAXBElement<T> object, Class<T> type) throws SAMLException { try { JAXBContext context = JAXBContext.newInstance(type); Marshaller marshaller = context.createMarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); marshaller.marshal(object, document); return document; } catch (JAXBException | ParserConfigurationException e) { throw new SAMLException("Unable to marshallRequest JAXB SAML object to DOM.", e); } }
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-125
47
public SAXReader(XMLReader xmlReader, boolean validating) { this.xmlReader = xmlReader; this.validating = validating; }
CWE-611
13
public CreateCommentResponse save(CreateCommentRequest createCommentRequest) { CreateCommentResponse createCommentResponse = new CreateCommentResponse(); if (createCommentRequest.getLogId() != null && createCommentRequest.getComment() != null) { if (isAllowComment(Integer.valueOf(createCommentRequest.getLogId()))) { String comment = Jsoup.clean(createCommentRequest.getComment(), Whitelist.basic()); if (comment.length() > 0 && !ParseUtil.isGarbageComment(comment)) { new Comment().set("userHome", createCommentRequest.getUserHome()) .set("userMail", createCommentRequest.getComment()) .set("userIp", createCommentRequest.getIp()) .set("userName", createCommentRequest.getUserName()) .set("logId", createCommentRequest.getLogId()) .set("userComment", comment) .set("user_agent", createCommentRequest.getUserAgent()) .set("reply_id", createCommentRequest.getReplyId()) .set("commTime", new Date()).set("hide", 1).save(); } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } Log log = new Log().findByIdOrAlias(createCommentRequest.getLogId()); if (log != null) { createCommentResponse.setAlias(log.getStr("alias")); } return createCommentResponse; }
CWE-79
1
public UPathHand(UPath source, Random rnd) { final UPath result = new UPath(); Point2D last = new Point2D.Double(); for (USegment segment : source) { final USegmentType type = segment.getSegmentType(); if (type == USegmentType.SEG_MOVETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; result.moveTo(x, y); last = new Point2D.Double(x, y); } else if (type == USegmentType.SEG_CUBICTO) { final double x2 = segment.getCoord()[4]; final double y2 = segment.getCoord()[5]; final HandJiggle jiggle = HandJiggle.create(last, 2.0, rnd); final CubicCurve2D tmp = new CubicCurve2D.Double(last.getX(), last.getY(), segment.getCoord()[0], segment.getCoord()[1], segment.getCoord()[2], segment.getCoord()[3], x2, y2); jiggle.curveTo(tmp); jiggle.appendTo(result); last = new Point2D.Double(x2, y2); } else if (type == USegmentType.SEG_LINETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; final HandJiggle jiggle = new HandJiggle(last.getX(), last.getY(), defaultVariation, rnd); jiggle.lineTo(x, y); for (USegment seg2 : jiggle.toUPath()) { if (seg2.getSegmentType() == USegmentType.SEG_LINETO) { result.lineTo(seg2.getCoord()[0], seg2.getCoord()[1]); } } last = new Point2D.Double(x, y); } else { this.path = source; return; } } this.path = result; this.path.setDeltaShadow(source.getDeltaShadow()); }
CWE-918
16
public Operation.OperationResult executeFixedCostOperation( final MessageFrame frame, final EVM evm) { Bytes shiftAmount = frame.popStackItem(); final Bytes value = leftPad(frame.popStackItem()); final boolean negativeNumber = value.get(0) < 0; if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); } else { final int shiftAmountInt = shiftAmount.toInt(); if (shiftAmountInt >= 256) { frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); } else { // first perform standard shift right. Bytes result = value.shiftRight(shiftAmountInt); // if a negative number, carry through the sign. if (negativeNumber) { final Bytes32 significantBits = ALL_BITS.shiftLeft(256 - shiftAmountInt); result = result.or(significantBits); } frame.pushStackItem(result); } } return successResponse; }
CWE-681
59
public final HColor getBackColor(ISkinParam skinParam, Style style) { if (colors == null || colors.getColor(ColorType.BACK) == null) { if (UseStyle.useBetaStyle() == false) return HColorUtils.COL_D7E0F2; return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); } return colors.getColor(ColorType.BACK); }
CWE-918
16
public void warning(SAXParseException e) { }
CWE-611
13
void ampersand() { final PathAndQuery res = PathAndQuery.parse("/&?a=1&a=2&b=3"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/&"); assertThat(res.query()).isEqualTo("a=1&a=2&b=3"); // '%26' in a query string should never be decoded into '&'. final PathAndQuery res2 = PathAndQuery.parse("/%26?a=1%26a=2&b=3"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/&"); assertThat(res2.query()).isEqualTo("a=1%26a=2&b=3"); }
CWE-22
2
void checkVerificationCode() throws Exception { when(this.userManager.exists(this.userReference)).thenReturn(true); InternetAddress email = new InternetAddress("[email protected]"); when(this.userProperties.getEmail()).thenReturn(email); String verificationCode = "abcd1245"; BaseObject xObject = mock(BaseObject.class); when(this.userDocument .getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE)) .thenReturn(xObject); String encodedVerificationCode = "encodedVerificationCode"; when(xObject.getStringValue(DefaultResetPasswordManager.VERIFICATION_PROPERTY)) .thenReturn(encodedVerificationCode); BaseClass baseClass = mock(BaseClass.class); when(xObject.getXClass(context)).thenReturn(baseClass); PasswordClass passwordClass = mock(PasswordClass.class); when(baseClass.get(DefaultResetPasswordManager.VERIFICATION_PROPERTY)).thenReturn(passwordClass); when(passwordClass.getEquivalentPassword(encodedVerificationCode, verificationCode)) .thenReturn(encodedVerificationCode); String newVerificationCode = "foobartest"; when(xWiki.generateRandomString(30)).thenReturn(newVerificationCode); String saveComment = "Save new verification code"; when(this.localizationManager .getTranslationPlain("xe.admin.passwordReset.step2.versionComment.changeValidationKey")) .thenReturn(saveComment); DefaultResetPasswordRequestResponse expected = new DefaultResetPasswordRequestResponse(this.userReference, email, newVerificationCode); assertEquals(expected, this.resetPasswordManager.checkVerificationCode(this.userReference, verificationCode)); verify(this.xWiki).saveDocument(this.userDocument, saveComment, true, context); }
CWE-640
20
static public UStroke getStrokeInternal(IGroup group, ISkinParam skinParam, Style style) { final Colors colors = group.getColors(); if (colors.getSpecificLineStroke() != null) return colors.getSpecificLineStroke(); if (style != null) return style.getStroke(); if (group.getUSymbol() != null && group.getUSymbol() != USymbols.PACKAGE) return group.getUSymbol().getSkinParameter().getStroke(skinParam, group.getStereotype()); return GeneralImageBuilder.getForcedStroke(group.getStereotype(), skinParam); }
CWE-918
16
public static void main(String[] args) throws LifecycleException { String webappDirLocation; if (Constants.IN_JAR) { webappDirLocation = "webapp"; } else { webappDirLocation = "src/main/webapp/"; } Tomcat tomcat = new Tomcat(); String webPort = System.getenv("PORT"); if (webPort == null || webPort.isEmpty()) { webPort = "8080"; } tomcat.setPort(Integer.valueOf(webPort)); tomcat.getConnector(); // Declare an alternative location for your "WEB-INF/classes" dir // Servlet 3.0 annotation will work File additionWebInfClasses; if (Constants.IN_JAR) { additionWebInfClasses = new File(""); } else { additionWebInfClasses = new File("target/classes"); } tomcat.setBaseDir(additionWebInfClasses.toString()); //idea的路径eclipse启动的路径有区别 if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) { webappDirLocation = "web/" + webappDirLocation; } tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); }
CWE-79
1
public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file) { SysUser currentUser = getSysUser(); try { if (!file.isEmpty()) { String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file); currentUser.setAvatar(avatar); if (userService.updateUserInfo(currentUser) > 0) { setSysUser(userService.selectUserById(currentUser.getUserId())); return success(); } } return error(); } catch (Exception e) { log.error("修改头像失败!", e); return error(e.getMessage()); } }
CWE-79
1
public DefaultFileSystemResourceLoader(String path) { this.baseDirPath = Optional.of(Paths.get(normalize(path))); }
CWE-22
2
public FileSelection(UserRequest ureq, String currentContainerRelPath) { if (currentContainerRelPath.equals("/")) currentContainerRelPath = ""; this.currentContainerRelPath = currentContainerRelPath; parse(ureq); }
CWE-22
2
private String getTitleQTI12(QuestionItemImpl item) { try { VFSLeaf leaf = qpoolService.getRootLeaf(item); Item xmlItem = QTIEditHelper.readItemXml(leaf); return xmlItem.getTitle(); } catch (NullPointerException e) { log.warn("Cannot read files from dir: " + item.getDirectory()); } return null; }
CWE-91
78
public RoutingResultBuilder rawParam(String name, String value) { pathParams().put(requireNonNull(name, "name"), ArmeriaHttpUtil.decodePath(requireNonNull(value, "value"))); return this; }
CWE-22
2
void hexadecimal() { assertThat(PathAndQuery.parse("/%")).isNull(); assertThat(PathAndQuery.parse("/%0")).isNull(); assertThat(PathAndQuery.parse("/%0X")).isNull(); assertThat(PathAndQuery.parse("/%X0")).isNull(); }
CWE-22
2
private int _readAndWriteBytes(OutputStream out, int total) throws IOException { int left = total; while (left > 0) { int avail = _inputEnd - _inputPtr; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); avail = _inputEnd - _inputPtr; } int count = Math.min(avail, left); out.write(_inputBuffer, _inputPtr, count); _inputPtr += count; left -= count; } _tokenIncomplete = false; return total; }
CWE-770
37
private void ensureInitialized() throws SQLException { if (!initialized) { throw new PSQLException( GT.tr( "This SQLXML object has not been initialized, so you cannot retrieve data from it."), PSQLState.OBJECT_NOT_IN_STATE); } // Is anyone loading data into us at the moment? if (!active) { return; } if (byteArrayOutputStream != null) { try { data = conn.getEncoding().decode(byteArrayOutputStream.toByteArray()); } catch (IOException ioe) { throw new PSQLException(GT.tr("Failed to convert binary xml data to encoding: {0}.", conn.getEncoding().name()), PSQLState.DATA_ERROR, ioe); } finally { byteArrayOutputStream = null; active = false; } } else if (stringWriter != null) { // This is also handling the work for Stream, SAX, and StAX Results // as they will use the same underlying stringwriter variable. // data = stringWriter.toString(); stringWriter = null; active = false; } else if (domResult != null) { // Copy the content from the result to a source // and use the identify transform to get it into a // friendlier result format. try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource domSource = new DOMSource(domResult.getNode()); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(domSource, streamResult); data = stringWriter.toString(); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."), PSQLState.DATA_ERROR, te); } finally { domResult = null; active = false; } } }
CWE-611
13
public void archive(OLATResourceable ores, File exportDirectory) { ObjectOutputStream out = null; try { File file = new File(exportDirectory, "chat.xml"); Writer writer = new FileWriter(file); out = logXStream.createObjectOutputStream(writer); int counter = 0; List<InstantMessage> messages; do { messages = imDao.getMessages(ores, null, counter, BATCH_SIZE); for(InstantMessage message:messages) { out.writeObject(message); } counter += messages.size(); } while(messages.size() == BATCH_SIZE); } catch (IOException e) { log.error("", e); } finally { IOUtils.closeQuietly(out); } }
CWE-91
78
protected final void _decodeNonStringName(int ch) throws IOException { final int type = ((ch >> 5) & 0x7); String name; if (type == CBORConstants.MAJOR_TYPE_INT_POS) { name = _numberToName(ch, false); } else if (type == CBORConstants.MAJOR_TYPE_INT_NEG) { name = _numberToName(ch, true); } else if (type == CBORConstants.MAJOR_TYPE_BYTES) { /* 08-Sep-2014, tatu: As per [Issue#5], there are codecs * (f.ex. Perl module "CBOR::XS") that use Binary data... */ final int blen = _decodeExplicitLength(ch & 0x1F); byte[] b = _finishBytes(blen); // TODO: Optimize, if this becomes commonly used & bottleneck; we have // more optimized UTF-8 codecs available. name = new String(b, UTF8); } else { if ((ch & 0xFF) == CBORConstants.INT_BREAK) { _reportUnexpectedBreak(); } throw _constructError("Unsupported major type ("+type+") for CBOR Objects, not (yet?) supported, only Strings"); } _parsingContext.setCurrentName(name); }
CWE-770
37
public void svgImage(UImageSvg image, double x, double y) { // https://developer.mozilla.org/fr/docs/Web/SVG/Element/image if (hidden == false) { final Element elt = (Element) document.createElement("image"); elt.setAttribute("width", format(image.getWidth())); elt.setAttribute("height", format(image.getHeight())); elt.setAttribute("x", format(x)); elt.setAttribute("y", format(y)); String svg = manageScale(image); final String svgHeader = "<svg height=\"" + (int) (image.getHeight() * scale) + "\" width=\"" + (int) (image.getWidth() * scale) + "\" xmlns=\"http://www.w3.org/2000/svg\" >"; svg = svgHeader + svg.substring(5); final String s = toBase64(svg); elt.setAttribute("xlink:href", "data:image/svg+xml;base64," + s); getG().appendChild(elt); } ensureVisible(x, y); ensureVisible(x + image.getData("width"), y + image.getData("height")); }
CWE-918
16
private NameID parseNameId(NameIDType element) { NameID nameId = new NameID(); nameId.format = NameIDFormat.fromSAMLFormat(element.getFormat()); nameId.id = element.getValue(); return nameId; }
CWE-611
13
public static String serializeToString(final Object payload) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializeToStream(bos, payload); String agentData = null; try { agentData = bos.toString("8859_1"); } catch (UnsupportedEncodingException e) { logger.warn("Should always support 8859_1", e); agentData = bos.toString(); } return agentData; }
CWE-502
15
private static void addMagic(SName sname) { final String cleanName = sname.name().replace("_", ""); addConvert(cleanName + "BackgroundColor", PName.BackGroundColor, sname); addConvert(cleanName + "BorderColor", PName.LineColor, sname); addConvert(cleanName + "BorderThickness", PName.LineThickness, sname); addConvert(cleanName + "RoundCorner", PName.RoundCorner, sname); addConvert(cleanName + "DiagonalCorner", PName.DiagonalCorner, sname); addConvert(cleanName + "BorderStyle", PName.LineStyle, sname); addConvert(cleanName + "StereotypeFontColor", PName.FontColor, SName.stereotype, sname); addConFont(cleanName, sname); }
CWE-918
16
public Document read(InputStream in) throws DocumentException { InputSource source = new InputSource(in); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
CWE-611
13
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-378
80
private static void handleResponse(HttpURLConnection conn, int statusCode, String terminalWidth) { try { // 200 - modules found // Other - Error occurred, json returned with the error message MapValue payload; if (statusCode == HttpURLConnection.HTTP_OK) { 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); } payload = (MapValue) JSONParser.parse(result.toString()); } catch (IOException e) { throw ErrorUtil.createCommandException(e.getMessage()); } if (payload.getIntValue("count") > 0) { ArrayValue modules = payload.getArrayValue("modules"); printModules(modules, terminalWidth); } else { outStream.println("no modules found"); } } else { StringBuilder result = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) { String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (IOException e) { throw ErrorUtil.createCommandException(e.getMessage()); } payload = (MapValue) JSONParser.parse(result.toString()); throw ErrorUtil.createCommandException(payload.getStringValue("message")); } } finally { conn.disconnect(); } }
CWE-306
79
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
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); }
CWE-79
1
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 void reportJobCaches(byte[] cacheInstanceBytes) { @SuppressWarnings("unchecked") Collection<CacheInstance> cacheInstances = (Collection<CacheInstance>) SerializationUtils .deserialize(cacheInstanceBytes); jobManager.reportJobCaches(getJobToken(), cacheInstances); }
CWE-502
15
public ErrorHandler getErrorHandler() { return errorHandler; }
CWE-611
13
public void setCharacterStream() throws Exception { String exmplar = "<x>value</x>"; SQLXML pgSQLXML = con.createSQLXML(); Writer writer = pgSQLXML.setCharacterStream(); writer.write(exmplar); PreparedStatement preparedStatement = con.prepareStatement("insert into xmltab values (?)"); preparedStatement.setSQLXML(1,pgSQLXML); preparedStatement.execute(); Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("select * from xmltab"); assertTrue(rs.next()); SQLXML result = rs.getSQLXML(1); assertNotNull(result); assertEquals(exmplar, result.getString()); }
CWE-611
13
public PersistentTask createTask(String name, Serializable task, Identity creator, OLATResource resource, String resSubPath, Date scheduledDate) { PersistentTask ptask = new PersistentTask(); Date currentDate = new Date(); ptask.setCreationDate(currentDate); ptask.setLastModified(currentDate); ptask.setScheduledDate(scheduledDate); ptask.setName(name); ptask.setCreator(creator); ptask.setResource(resource); ptask.setResSubPath(resSubPath); ptask.setStatus(TaskStatus.newTask); ptask.setTask(xstream.toXML(task)); dbInstance.getCurrentEntityManager().persist(ptask); return ptask; }
CWE-91
78
public void setDefaultHandler(ElementHandler handler) { getDispatchHandler().setDefaultHandler(handler); }
CWE-611
13
public static byte[] decryptAuthenticated(final SecretKey secretKey, final byte[] iv, final byte[] cipherText, final byte[] aad, final byte[] authTag, final Provider ceProvider, final Provider macProvider) throws JOSEException { // Extract MAC + AES/CBC keys from input secret key CompositeKey compositeKey = new CompositeKey(secretKey); // AAD length to 8 byte array byte[] al = AAD.computeLength(aad); // Check MAC int hmacInputLength = aad.length + iv.length + cipherText.length + al.length; byte[] hmacInput = ByteBuffer.allocate(hmacInputLength). put(aad). put(iv). put(cipherText). put(al). array(); byte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider); byte[] expectedAuthTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength()); boolean macCheckPassed = true; if (! ConstantTimeUtils.areEqual(expectedAuthTag, authTag)) { // Thwart timing attacks by delaying exception until after decryption macCheckPassed = false; } byte[] plainText = decrypt(compositeKey.getAESKey(), iv, cipherText, ceProvider); if (! macCheckPassed) { throw new JOSEException("MAC check failed"); } return plainText; }
CWE-354
82
public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference())); String encodedAttachmentSupport; if (getAttachmentSupport() != null) { encodedAttachmentSupport = Base64.encodeBase64String(SerializationUtils.serialize(getAttachmentSupport())); encodedAttachmentSupport = StringUtils.deleteWhitespace(encodedAttachmentSupport); encodedAttachmentSupport = StringEscapeUtils.escapeEcmaScript(encodedAttachmentSupport); encodedAttachmentSupport = "'" + encodedAttachmentSupport + "'"; } else { encodedAttachmentSupport = "undefined"; } String callback = ajaxBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"), explicit("param3")).toString(); String autosaveKey = getAutosaveKey(); if (autosaveKey != null) autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'"; else autosaveKey = "undefined"; String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);", container.getMarkupId(), callback, ATWHO_LIMIT, encodedAttachmentSupport, getAttachmentSupport()!=null?getAttachmentSupport().getAttachmentMaxSize():0, getUserMentionSupport() != null, getReferenceSupport() != null, JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()), autosaveKey); response.render(OnDomReadyHeaderItem.forScript(script)); script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId()); response.render(OnLoadHeaderItem.forScript(script)); }
CWE-502
15
public PlayerBinary(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) { super(code, skinParam, ruler, compact); this.style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); this.suggestedHeight = 30; }
CWE-918
16
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) { this.translator = trans; this.folderComponent = fc; this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath()); VFSContainer currentContainer = folderComponent.getCurrentContainer(); List<String> lockedFiles = hasLockedFiles(currentContainer, fileSelection); if (lockedFiles.isEmpty()) { String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>"; // create dialog controller dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr); } else { String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles); List<String> buttonLabels = Collections.singletonList(trans.translate("ok")); lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr); } return this; }
CWE-22
2
protected void setDispatchHandler(DispatchHandler dispatchHandler) { this.dispatchHandler = dispatchHandler; }
CWE-611
13
private Certificate toCertificate(KeyDescriptorType keyDescriptorType) { try { List<Object> keyData = keyDescriptorType.getKeyInfo().getContent(); for (Object keyDatum : keyData) { if (keyDatum instanceof JAXBElement<?>) { JAXBElement<?> element = (JAXBElement<?>) keyDatum; if (element.getDeclaredType() == X509DataType.class) { X509DataType cert = (X509DataType) element.getValue(); List<Object> certData = cert.getX509IssuerSerialOrX509SKIOrX509SubjectName(); for (Object certDatum : certData) { element = (JAXBElement<?>) certDatum; if (element.getName().getLocalPart().equals("X509Certificate")) { byte[] certBytes = (byte[]) element.getValue(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); return cf.generateCertificate(new ByteArrayInputStream(certBytes)); } } } } } return null; } catch (CertificateException e) { throw new IllegalArgumentException(e); } }
CWE-611
13
public static DomainSocketAddress newSocketAddress() { try { File file; do { file = File.createTempFile("NETTY", "UDS"); if (!file.delete()) { throw new IOException("failed to delete: " + file); } } while (file.getAbsolutePath().length() > 128); return new DomainSocketAddress(file); } catch (IOException e) { throw new IllegalStateException(e); } }
CWE-379
83
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); }
CWE-79
1
public ResponseEntity<Resource> fetch(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).body(file); }
CWE-22
2
void getGadgets() throws Exception { assertEquals(new ArrayList<>(), this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext)); BaseObject gadgetObject1 = mock(BaseObject.class); when(xWikiDocument.getXObjects(gadgetClassReference)).thenReturn(Collections.singletonList(gadgetObject1)); when(gadgetObject1.getOwnerDocument()).thenReturn(ownerDocument); when(gadgetObject1.getStringValue("title")).thenReturn("Gadget 1"); when(gadgetObject1.getLargeStringValue("content")).thenReturn("Some content"); when(gadgetObject1.getStringValue("position")).thenReturn("0"); when(gadgetObject1.getNumber()).thenReturn(42); List<Gadget> gadgets = this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext); assertEquals(1, gadgets.size()); Gadget gadget = gadgets.get(0); assertEquals("Gadget 1", gadget.getTitle().get(0).toString()); assertEquals("Some content", gadget.getContent().get(0).toString()); assertEquals("42", gadget.getId()); }
CWE-94
14
private void testBSI() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC"); kpGen.initialize(new ECGenParameterSpec(TeleTrusTObjectIdentifiers.brainpoolP512r1.getId())); KeyPair kp = kpGen.generateKeyPair(); byte[] data = "Hello World!!!".getBytes(); String[] cvcAlgs = { "SHA1WITHCVC-ECDSA", "SHA224WITHCVC-ECDSA", "SHA256WITHCVC-ECDSA", "SHA384WITHCVC-ECDSA", "SHA512WITHCVC-ECDSA" }; String[] cvcOids = { EACObjectIdentifiers.id_TA_ECDSA_SHA_1.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_224.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_256.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_384.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_512.getId() }; testBsiAlgorithms(kp, data, cvcAlgs, cvcOids); String[] plainAlgs = { "SHA1WITHPLAIN-ECDSA", "SHA224WITHPLAIN-ECDSA", "SHA256WITHPLAIN-ECDSA", "SHA384WITHPLAIN-ECDSA", "SHA512WITHPLAIN-ECDSA", "RIPEMD160WITHPLAIN-ECDSA" }; String[] plainOids = { BSIObjectIdentifiers.ecdsa_plain_SHA1.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA224.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA256.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA384.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA512.getId(), BSIObjectIdentifiers.ecdsa_plain_RIPEMD160.getId() }; testBsiAlgorithms(kp, data, plainAlgs, plainOids); }
CWE-347
25
private static void handleErrorResponse(HttpURLConnection conn, String url, String moduleFullName) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) { StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } MapValue payload = (MapValue) JSONParser.parse(result.toString()); createError("error: " + payload.getStringValue("message")); } catch (IOException e) { createError("failed to pull the module '" + moduleFullName + "' from the remote repository '" + url + "'"); } }
CWE-306
79
public <T extends Result> T setResult(Class<T> resultClass) throws SQLException { try { if (isDebugEnabled()) { debugCode( "getSource(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')'); } checkEditable(); if (resultClass == null || resultClass == DOMResult.class) { domResult = new DOMResult(); state = State.SET_CALLED; return (T) domResult; } else if (resultClass == SAXResult.class) { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); Writer writer = setCharacterStreamImpl(); transformerHandler.setResult(new StreamResult(writer)); SAXResult saxResult = new SAXResult(transformerHandler); closable = writer; state = State.SET_CALLED; return (T) saxResult; } else if (resultClass == StAXResult.class) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); Writer writer = setCharacterStreamImpl(); StAXResult staxResult = new StAXResult(xof.createXMLStreamWriter(writer)); closable = writer; state = State.SET_CALLED; return (T) staxResult; } else if (StreamResult.class.equals(resultClass)) { Writer writer = setCharacterStreamImpl(); StreamResult streamResult = new StreamResult(writer); closable = writer; state = State.SET_CALLED; return (T) streamResult; } throw unsupported(resultClass.getName()); } catch (Exception e) { throw logAndConvert(e); } }
CWE-611
13
protected final void loadMoreGuaranteed() throws IOException { if (!loadMore()) { _reportInvalidEOF(); } }
CWE-770
37
public String toString() { return toNiceString(this.getClass(), "clientId", clientId, "secret", "[protected]", "discoveryURI", discoveryURI, "scope", scope, "customParams", customParams, "clientAuthenticationMethod", clientAuthenticationMethod, "useNonce", useNonce, "preferredJwsAlgorithm", preferredJwsAlgorithm, "maxAge", maxAge, "maxClockSkew", maxClockSkew, "connectTimeout", connectTimeout, "readTimeout", readTimeout, "resourceRetriever", resourceRetriever, "responseType", responseType, "responseMode", responseMode, "logoutUrl", logoutUrl, "withState", withState, "stateGenerator", stateGenerator, "logoutHandler", logoutHandler, "tokenValidator", tokenValidator, "mappedClaims", mappedClaims); }
CWE-347
25
public Stream<URL> getResources(String path) { Enumeration<URL> all; try { all = classLoader.getResources(prefixPath(path)); } catch (IOException e) { return Stream.empty(); } Stream.Builder<URL> builder = Stream.builder(); while (all.hasMoreElements()) { URL url = all.nextElement(); builder.accept(url); } return builder.build(); }
CWE-22
2
public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { /* HttpServletRequest request = (HttpServletRequest) srequest; //final String realIp = request.getHeader(X_FORWARDED_FOR); //if (realIp != null) { filterChain.doFilter(new XssHttpServletRequestWrapper(request) { *//** public String getRemoteAddr() { return realIp; } public String getRemoteHost() { return realIp; } **//* }, response); return; //} */ }
CWE-79
1
public void spliceToFile() throws Throwable { EventLoopGroup group = new EpollEventLoopGroup(1); File file = File.createTempFile("netty-splice", null); file.deleteOnExit(); SpliceHandler sh = new SpliceHandler(file); ServerBootstrap bs = new ServerBootstrap(); bs.channel(EpollServerSocketChannel.class); bs.group(group).childHandler(sh); bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel(); Bootstrap cb = new Bootstrap(); cb.group(group); cb.channel(EpollSocketChannel.class); cb.handler(new ChannelInboundHandlerAdapter()); Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel(); for (int i = 0; i < data.length;) { int length = Math.min(random.nextInt(1024 * 64), data.length - i); ByteBuf buf = Unpooled.wrappedBuffer(data, i, length); cc.writeAndFlush(buf); i += length; } while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) { if (sh.exception.get() != null) { break; } try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore. } } sc.close().sync(); cc.close().sync(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } byte[] written = new byte[data.length]; FileInputStream in = new FileInputStream(file); try { Assert.assertEquals(written.length, in.read(written)); Assert.assertArrayEquals(data, written); } finally { in.close(); group.shutdownGracefully(); } }
CWE-379
83
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null || !ICON_SIZE.matcher(qs).matches()) throw new ServletException(); Cookie cookie = new Cookie("iconSize", qs); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); }
CWE-79
1
public static SecretKey deriveSharedKey(final JWEHeader header, final SecretKey Z, final ConcatKDF concatKDF) throws JOSEException { final int sharedKeyLength = sharedKeyLength(header.getAlgorithm(), header.getEncryptionMethod()); // Set the alg ID for the concat KDF AlgorithmMode algMode = resolveAlgorithmMode(header.getAlgorithm()); final String algID; if (algMode == AlgorithmMode.DIRECT) { // algID = enc algID = header.getEncryptionMethod().getName(); } else if (algMode == AlgorithmMode.KW) { // algID = alg algID = header.getAlgorithm().getName(); } else { throw new JOSEException("Unsupported JWE ECDH algorithm mode: " + algMode); } return concatKDF.deriveKey( Z, sharedKeyLength, ConcatKDF.encodeDataWithLength(algID.getBytes(Charset.forName("ASCII"))), ConcatKDF.encodeDataWithLength(header.getAgreementPartyUInfo()), ConcatKDF.encodeDataWithLength(header.getAgreementPartyVInfo()), ConcatKDF.encodeIntData(sharedKeyLength), ConcatKDF.encodeNoData()); }
CWE-347
25
public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/bin/echo" ); cmd.addArguments( new String[] { "hello world" } ); File root = File.listRoots()[0]; File workingDirectory = new File( root, "path with spaces" ); cmd.setWorkingDirectory( workingDirectory ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); String expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && /bin/echo \'hello world\'"; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && \\bin\\echo \'hello world\'"; } assertEquals( expectedShellCmd, shellCommandline[2] ); }
CWE-78
6
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); } }
CWE-611
13
private String deflateAndEncode(byte[] result) { Deflater deflater = new Deflater(Deflater.DEFLATED, true); deflater.setInput(result); deflater.finish(); byte[] deflatedResult = new byte[result.length]; int length = deflater.deflate(deflatedResult); deflater.end(); byte[] src = Arrays.copyOf(deflatedResult, length); return Base64.getEncoder().encodeToString(src); }
CWE-611
13
public static UChange changeBack(UGraphic ug) { final HColor color = ug.getParam().getColor(); if (color == null) { return new HColorNone().bg(); } return color.bg(); }
CWE-918
16
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; }
CWE-22
2
private String buildRedirectAuthnRequest(AuthnRequestType authnRequest, String relayState, boolean sign, PrivateKey key, Algorithm algorithm) throws SAMLException { try { byte[] xml = marshallToBytes(PROTOCOL_OBJECT_FACTORY.createAuthnRequest(authnRequest), AuthnRequestType.class); String encodedResult = deflateAndEncode(xml); String parameters = "SAMLRequest=" + URLEncoder.encode(encodedResult, "UTF-8"); if (relayState != null) { parameters += "&RelayState=" + URLEncoder.encode(relayState, "UTF-8"); } if (sign && key != null && algorithm != null) { Signature signature; parameters += "&SigAlg=" + URLEncoder.encode(algorithm.uri, "UTF-8"); signature = Signature.getInstance(algorithm.name); signature.initSign(key); signature.update(parameters.getBytes(StandardCharsets.UTF_8)); String signatureParameter = Base64.getEncoder().encodeToString(signature.sign()); parameters += "&Signature=" + URLEncoder.encode(signatureParameter, "UTF-8"); } return parameters; } catch (Exception e) { // Not possible but freak out throw new SAMLException(e); } }
CWE-611
13
private void visitorPermission(Invocation ai) { ai.invoke(); String templateName = ai.getReturnValue(); if (templateName == null) { return; } GlobalResourceHandler.printUserTime("Template before"); String templatePath = TemplateHelper.fullTemplateInfo(ai.getController(), true); GlobalResourceHandler.printUserTime("Template after"); TemplateVO templateVO = new TemplateService().getTemplateVO(JFinal.me().getContextPath(), new File(PathKit.getWebRootPath() + templatePath)); String ext = ZrLogUtil.getViewExt(templateVO.getViewType()); if (ai.getController().getAttr("log") != null) { ai.getController().setAttr("pageLevel", 1); } else if (ai.getController().getAttr("data") != null) { if ("/".equals(ai.getActionKey()) && new File(PathKit.getWebRootPath() + templatePath + "/" + templateName + ext).exists()) { ai.getController().setAttr("pageLevel", 2); } else { templateName = "page"; ai.getController().setAttr("pageLevel", 1); } } else { ai.getController().setAttr("pageLevel", 2); } fullDevData(ai.getController()); ai.getController().render(templatePath + "/" + templateName + ext); }
CWE-79
1
new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } }
CWE-306
79
public <T extends Source> T getSource(Class<T> sourceClass) throws SQLException { try { if (isDebugEnabled()) { debugCode( "getSource(" + (sourceClass != null ? sourceClass.getSimpleName() + ".class" : "null") + ')'); } checkReadable(); if (sourceClass == null || sourceClass == DOMSource.class) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); return (T) new DOMSource(dbf.newDocumentBuilder().parse(new InputSource(value.getInputStream()))); } else if (sourceClass == SAXSource.class) { return (T) new SAXSource(new InputSource(value.getInputStream())); } else if (sourceClass == StAXSource.class) { XMLInputFactory xif = XMLInputFactory.newInstance(); return (T) new StAXSource(xif.createXMLStreamReader(value.getInputStream())); } else if (sourceClass == StreamSource.class) { return (T) new StreamSource(value.getInputStream()); } throw unsupported(sourceClass.getName()); } catch (Exception e) { throw logAndConvert(e); } }
CWE-611
13
protected void initUpgradesHistories() { File upgradesDir = new File(WebappHelper.getUserDataRoot(), SYSTEM_DIR); File upgradesHistoriesFile = new File(upgradesDir, INSTALLED_UPGRADES_XML); if (upgradesHistoriesFile.exists()) { upgradesHistories = (Map<String, UpgradeHistoryData>)upgradesXStream.fromXML(upgradesHistoriesFile); } else { if (upgradesHistories == null) { upgradesHistories = new HashMap<>(); } needsUpgrade = false; //looks like a new install, no upgrade necessary log.info("This looks like a new install or dropped data, will not do any upgrades."); createUpgradeData(); } }
CWE-91
78
public InternetAddress getUserEmail() { return userEmail; }
CWE-640
20
private String getMimeType(HttpServletRequest pReq) { String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (requestMimeType != null) { return requestMimeType; } return configMimeType; }
CWE-79
1
public HomePageConfig loadConfigFor(Identity identity) { String userName = identity.getName(); HomePageConfig retVal = null; File configFile = getConfigFile(userName); if (!configFile.exists()) { // config file does not exist! create one, init the defaults, save it. retVal = loadAndSaveDefaults(identity); } else { // file exists, load it with XStream, resolve version try { Object tmp = homeConfigXStream.fromXML(configFile); if (tmp instanceof HomePageConfig) { retVal = (HomePageConfig)tmp; if(retVal.resolveVersionIssues()) { saveConfigTo(identity, retVal); } } } catch (Exception e) { log.error("Error while loading homepage config from path::" + configFile.getAbsolutePath() + ", fallback to default configuration", e); FileUtils.deleteFile(configFile); retVal = loadAndSaveDefaults(identity); // show message to user } } return retVal; }
CWE-91
78
private static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } } };
CWE-306
79
public static int getStatusCode(HttpURLConnection conn) { try { return conn.getResponseCode(); } catch (IOException e) { throw ErrorUtil .createCommandException("connection to the remote repository host failed: " + e.getMessage()); } }
CWE-306
79
public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); }
CWE-22
2
void routingResult() throws URISyntaxException { final RoutingResultBuilder builder = RoutingResult.builder(); final RoutingResult routingResult = builder.path("/foo") .query("bar=baz") .rawParam("qux", "quux") .negotiatedResponseMediaType(MediaType.JSON_UTF_8) .build(); assertThat(routingResult.isPresent()).isTrue(); assertThat(routingResult.path()).isEqualTo("/foo"); assertThat(routingResult.query()).isEqualTo("bar=baz"); assertThat(routingResult.pathParams()).containsOnly(new SimpleEntry<>("qux", "quux")); assertThat(routingResult.negotiatedResponseMediaType()).isSameAs(MediaType.JSON_UTF_8); }
CWE-22
2
public CommandExecutionResult createRobustConcise(String code, String full, TimingStyle type, boolean compact) { final Player player = new PlayerRobustConcise(type, full, getSkinParam(), ruler, compactByDefault || compact); players.put(code, player); lastPlayer = player; return CommandExecutionResult.ok(); }
CWE-918
16
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-470
84
public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) { Key key = getJWTKey(); Jwt jwt; try { jwt = Jwts.parser().setSigningKey(key).parse(token.getPrincipal()); } catch (JwtException e) { throw new AuthenticationException(e); } String credentials = legacyHashing ? token.getCredentials() : encryptPassword(token.getCredentials()); Object principal = extractPrincipalFromWebToken(jwt); return new SimpleAuthenticationInfo(principal, credentials, getName()); }
CWE-347
25
public static final void toStream(Binder binder, ZipOutputStream zout) throws IOException { try(OutputStream out=new ShieldOutputStream(zout)) { myStream.toXML(binder, out); } catch (Exception e) { log.error("Cannot export this map: " + binder, e); } }
CWE-91
78
public String getStringParameterSQL(String param) { return "'" + param + "'"; }
CWE-89
0
public Object getResourceDataForKey(String key) { Object data = null; String dataString = null; Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key); if (matcher.find()) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key, dataString)); } int dataStart = matcher.end(); dataString = key.substring(dataStart); byte[] objectArray = null; byte[] dataArray; try { dataArray = dataString.getBytes("ISO-8859-1"); objectArray = decrypt(dataArray); } catch (UnsupportedEncodingException e1) { // default encoding always presented. } if ("B".equals(matcher.group(1))) { data = objectArray; } else { try { ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(objectArray)); data = in.readObject(); } catch (StreamCorruptedException e) { log.error(Messages .getMessage(Messages.STREAM_CORRUPTED_ERROR), e); } catch (IOException e) { log.error(Messages .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e); } catch (ClassNotFoundException e) { log .error( Messages .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e); } } } return data; }
CWE-502
15
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-918
16
public ChangeState(TimeTick when, String comment, Colors colors, String... states) { if (states.length == 0) { throw new IllegalArgumentException(); } this.when = when; this.states = states; this.comment = comment; this.colors = colors; }
CWE-918
16
public SymbolContext getContext(ISkinParam skinParam, Style style) { return new SymbolContext(getBackColor(skinParam, style), getLineColor(skinParam, style)) .withStroke(new UStroke(1.5)); }
CWE-918
16
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) { setTranslator(trans); currentContainer = folderComponent.getCurrentContainer(); if (currentContainer.canWrite() != VFSConstants.YES) { throw new AssertException("Cannot write to current folder."); } status = FolderCommandHelper.sanityCheck(wControl, folderComponent); if(status == FolderCommandStatus.STATUS_FAILED) { return null; } 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; } initForm(ureq); return this; }
CWE-22
2
public PlayerRobustConcise(TimingStyle type, String full, ISkinParam skinParam, TimingRuler ruler, boolean compact) { super(full, skinParam, ruler, compact); this.type = type; this.suggestedHeight = 0; }
CWE-918
16
private <T> byte[] marshallToBytes(JAXBElement<T> object, Class<T> type) throws SAMLException { try { JAXBContext context = JAXBContext.newInstance(type); Marshaller marshaller = context.createMarshaller(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(object, baos); return baos.toByteArray(); } catch (JAXBException e) { throw new SAMLException("Unable to marshallRequest JAXB SAML object to bytes.", e); } }
CWE-611
13
public static String getRealIp(HttpServletRequest request) { //bae env if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) { return request.getHeader("clientip"); } String ip = request.getHeader("X-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
CWE-79
1
public String[] getCommandline() { final String[] args = getArguments(); String executable = getExecutable(); if ( executable == null ) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; System.arraycopy( args, 0, result, 1, args.length ); return result; }
CWE-78
6
public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable { File file = File.createTempFile("netty-", ".tmp"); file.deleteOnExit(); final FileOutputStream out = new FileOutputStream(file); out.write(data); out.close(); sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { // Just drop the message. } }); cb.handler(new ChannelInboundHandlerAdapter()); Channel sc = sb.bind().sync().channel(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); // Request file region which is bigger then the underlying file. FileRegion region = new DefaultFileRegion( new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024); assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class)); cc.close().sync(); sc.close().sync(); }
CWE-379
83