Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,29 @@ public static Element addChildElement(Element parentElement, String elementName)
return childElement;
}

/**
* Creates a {@link DocumentBuilderFactory} that does not resolve external entities,
* external DTDs or XIncludes, protecting against XML external entity (XXE) attacks.
* DOCTYPE declarations are still allowed, so documents that declare one keep parsing.
* Use this instead of {@link DocumentBuilderFactory#newInstance()} whenever parsing
* XML that may come from outside the program.
* @return a hardened, namespace-unaware factory
* @throws ParserConfigurationException if the underlying parser does not support these settings
* @since 7.4.1
*/
public static DocumentBuilderFactory newSecureDocumentBuilderFactory() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
return factory;
}

/**
* Create a new, empty {@code}org.w3c.dom.Document{@code}
* @return a new {@code}org.w3c.dom.Document{@code}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -22,6 +25,7 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Expand Down Expand Up @@ -55,6 +59,37 @@ void addChildDocument() throws ParserConfigurationException, DOMException {
assertEquals(added, root.getChildNodes().item(0));
}

@Test
@DisplayName("Secure factory does not resolve external entities (XXE)")
void secureFactoryDoesNotResolveExternalEntities(@TempDir Path tmp) throws Exception {
String secret = "XXE-SECRET-CONTENT";
Path secretFile = tmp.resolve("secret.txt");
Files.write(secretFile, secret.getBytes(StandardCharsets.UTF_8));
String xml = "<?xml version=\"1.0\"?>"
+ "<!DOCTYPE root [<!ENTITY xxe SYSTEM \"" + secretFile.toUri() + "\">]>"
+ "<root>&xxe;</root>";

String text;
try {
Document doc = XMLHelper.newSecureDocumentBuilderFactory().newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
text = doc.getDocumentElement().getTextContent();
} catch (SAXException e) {
// refusing to parse is also a safe outcome
text = "";
}
assertFalse(text.contains(secret), "external entity was resolved");
}

@Test
@DisplayName("Secure factory still parses ordinary XML")
void secureFactoryParsesPlainXml() throws Exception {
Document doc = XMLHelper.newSecureDocumentBuilderFactory().newDocumentBuilder()
.parse(new ByteArrayInputStream(TEST_XML.getBytes(StandardCharsets.UTF_8)));
assertEquals("root", doc.getDocumentElement().getTagName());
assertTrue(doc.getElementsByTagName("a").getLength() == 2);
}

@Test
void inputStreamToDocument() throws SAXException, IOException, ParserConfigurationException {
Document doc = readTestDoc();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,25 +96,17 @@ public void toPDB(StringBuffer buf) {

//counters for tracking where we are
int seqNum = 0;
int groupsWritten = 0;
int groupNum = 0;
//new StringBuilder for adding the groups to
StringBuilder stringBuilder = new StringBuilder();

while (groupsWritten < groups.size()) {
while (groupNum < groups.size()) {
StringBuilder groupsString = new StringBuilder();
for (int i = 0; i < 4 && groupsWritten < groups.size(); i++) {
for (int i = 0; i < 4 && groupNum < groups.size(); i++, groupNum++) {
Group group = groups.get(groupNum);
// Make sure the pdbName is formatted as 3 width string.
String groupString = String.format(Locale.UK, "%3s %s",
group.getPDBName(), group.getResidueNumber().toPDB());
groupsWritten++;
groupNum++;
if (i == 3 || groupsWritten == groups.size()) {
// groupString = groupString.trim();
groupString.replaceFirst("\\s+$", ""); // remove only trailing whitespace.
}
groupsString.append(groupString);
groupsString.append(String.format(Locale.UK, "%3s %s",
group.getPDBName(), group.getResidueNumber().toPDB()));
}
stringBuilder.append(String.format(Locale.UK, "SITE %3d %3s %2d %-62s", seqNum + 1, siteID, groups.size(), groupsString.toString()));
//iterate the line counter, add the end of line character
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,63 +229,60 @@ private void runAlignPairs(AtomCache cache, String alignPairs, String outputFile

File f = new File(alignPairs);

BufferedReader is = new BufferedReader (new InputStreamReader(new FileInputStream(f)));
try (BufferedReader is = new BufferedReader (new InputStreamReader(new FileInputStream(f)));
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile, true))) {

BufferedWriter out = new BufferedWriter(new FileWriter(outputFile, true));
StructureAlignment algorithm = getAlgorithm();

StructureAlignment algorithm = getAlgorithm();
String header = "# algorithm:" + algorithm.getAlgorithmName();
out.write(header);
out.write(newline);

String header = "# algorithm:" + algorithm.getAlgorithmName();
out.write(header);
out.write(newline);
out.write("#Legend: " + newline );
String legend = getDbSearchLegend();
out.write(legend + newline );
System.out.println(legend);
String line = null;
while ( (line = is.readLine()) != null){
if ( line.startsWith("#"))
continue;

out.write("#Legend: " + newline );
String legend = getDbSearchLegend();
out.write(legend + newline );
System.out.println(legend);
String line = null;
while ( (line = is.readLine()) != null){
if ( line.startsWith("#"))
continue;
String[] spl = line.split(" ");

String[] spl = line.split(" ");
if ( spl.length != 2) {
System.err.println("wrongly formattted line. Expected format: 4hhb.A 4hhb.B but found " + line);
continue;
}

if ( spl.length != 2) {
System.err.println("wrongly formattted line. Expected format: 4hhb.A 4hhb.B but found " + line);
continue;
}
String pdb1 = spl[0];
String pdb2 = spl[1];

String pdb1 = spl[0];
String pdb2 = spl[1];

Structure structure1 = cache.getStructure(pdb1);
Structure structure2 = cache.getStructure(pdb2);

Structure structure1 = cache.getStructure(pdb1);
Structure structure2 = cache.getStructure(pdb2);
Atom[] ca1;
Atom[] ca2;

Atom[] ca1;
Atom[] ca2;

ca1 = StructureTools.getRepresentativeAtomArray(structure1);
ca2 = StructureTools.getRepresentativeAtomArray(structure2);

ca1 = StructureTools.getRepresentativeAtomArray(structure1);
ca2 = StructureTools.getRepresentativeAtomArray(structure2);
Object jparams = getParameters();

Object jparams = getParameters();

AFPChain afpChain;
AFPChain afpChain;

afpChain = algorithm.align(ca1, ca2, jparams);
afpChain.setName1(pdb1);
afpChain.setName2(pdb2);
afpChain = algorithm.align(ca1, ca2, jparams);
afpChain.setName1(pdb1);
afpChain.setName2(pdb2);

String result = getDbSearchResult(afpChain);
out.write(result);
System.out.print(result);
String result = getDbSearchResult(afpChain);
out.write(result);
System.out.print(result);

checkWriteFile(afpChain,ca1,ca2,true);
checkWriteFile(afpChain,ca1,ca2,true);
}
}

out.close();
is.close();
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,17 @@ public class OptimalCECPMain extends CeMain {
*/
public static final String version = "1.0";

protected OptimalCECPParameters params;
// Kept apart from CeMain.params, which CeMain.align(Atom[],Atom[],Object) overwrites with
// whatever parameters it is given. setParameters keeps both pointing to the same object.
protected OptimalCECPParameters cpParams;

/**
*
*/
public OptimalCECPMain() {
super();
params = new OptimalCECPParameters();
cpParams = new OptimalCECPParameters();
super.setParameters(cpParams);
}

@Override
Expand All @@ -89,7 +92,7 @@ public String getVersion() {
*/
@Override
public ConfigStrucAligParams getParameters() {
return params;
return cpParams;
}

/**
Expand All @@ -100,7 +103,8 @@ public void setParameters(ConfigStrucAligParams params){
if (! (params instanceof OptimalCECPParameters )){
throw new IllegalArgumentException("provided parameter object is not of type CeParameter");
}
this.params = (OptimalCECPParameters) params;
this.cpParams = (OptimalCECPParameters) params;
super.setParameters(params);
}

/**
Expand Down Expand Up @@ -445,10 +449,10 @@ private static void assignOptAln(AFPChain afpChain, List<List<List<Integer>>> bl
public AFPChain align(Atom[] ca1, Atom[] ca2, Object param)
throws StructureException
{
if(params.isTryAllCPs()) {
if(cpParams.isTryAllCPs()) {
return alignOptimal(ca1,ca2,param,null);
} else {
int cpPoint = params.getCPPoint();
int cpPoint = cpParams.getCPPoint();
return alignPermuted(ca1, ca2, param, cpPoint);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,8 @@ private boolean initFromURL(String suffix) {
String path = url.getPath();
mySource = Source.URL;
try {
pdbId = new PdbId(URLIdentifier.guessPDBID( path.substring(path.lastIndexOf('/')+1) ));
String guessedId = URLIdentifier.guessPDBID( path.substring(path.lastIndexOf('/')+1) );
pdbId = guessedId == null ? null : new PdbId(guessedId);
} catch (IllegalArgumentException e) {
pdbId = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class FCAlignHelper
private int N; //length of protein 2
private double g; //gap-create
private double h; //gap-extend
private double m; //g + h
private double gapOpen; //g + h: cost of the first residue of a gap
private double[][] sij;
private char[][] trace; //trace-record
private char[][] etrace; //trace-record
Expand Down Expand Up @@ -85,7 +85,7 @@ private void init(int M0, int N0, double g0, double h0)
N = N0;
g = g0; //gap-create
h = h0; //gap-extend
m = g + h; //gap-create + gap-extend
gapOpen = g + h; //gap-create + gap-extend
trace = new char[M+1][N+1];
etrace = new char[M+1][N+1];
dtrace = new char[M+1][N+1];
Expand Down Expand Up @@ -127,11 +127,11 @@ private void doAlign(){
e = -g;
for(j = 1; j <= N; j ++) {
trace_e = 'e';
if ((c = c - m) > (e = e - h)) {
if ((c = c - gapOpen) > (e = e - h)) {
e = c; trace_e = 'E';
}//insertion
trace_d = 'd';
if ((c = CC[j] - m) > (d = DD[j] - h)) {
if ((c = CC[j] - gapOpen) > (d = DD[j] - h)) {
d = c; trace_d = 'D';
}//deletion
//ie CC[j]==CC[i-1][j] DD[j]==DD[i-1][j]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,8 @@ else if (block.getAlignRes().get(str).get(rightPrevRes1) + 1 < block
freePool.get(str).add(resL1);

break;
default:
throw new IllegalStateException("Unexpected direction " + rl);
}
checkGaps();
return true;
Expand Down Expand Up @@ -762,6 +764,8 @@ else if (nextPos[str] == -1) {
}
}
break;
default:
throw new IllegalStateException("Unexpected direction " + rl);
}
if (size - gaps >= Rmin)
return true;
Expand Down Expand Up @@ -838,16 +842,15 @@ private double probabilityFunction(double AS, int m, int maxIter) {
*/
private void saveHistory(String filePath) throws IOException {

FileWriter writer = new FileWriter(filePath);
writer.append("Step,Length,RMSD,Score\n");
try (FileWriter writer = new FileWriter(filePath)) {
writer.append("Step,Length,RMSD,Score\n");

for (int i = 0; i < lengthHistory.size(); i++) {
writer.append(String.valueOf(i * 100));
writer.append("," + lengthHistory.get(i));
writer.append("," + rmsdHistory.get(i));
writer.append("," + scoreHistory.get(i) + "\n");
for (int i = 0; i < lengthHistory.size(); i++) {
writer.append(String.valueOf(i * 100));
writer.append("," + lengthHistory.get(i));
writer.append("," + rmsdHistory.get(i));
writer.append("," + scoreHistory.get(i) + "\n");
}
}
writer.flush();
writer.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams;

Expand Down Expand Up @@ -148,7 +148,7 @@ public String toString() {
@Override
public void reset() {

randomSeed = new Random().nextInt(10000);
randomSeed = ThreadLocalRandom.current().nextInt(10000);
minBlockLen = 10;
minAlignedStructures = 0;
gapOpen = 20.0;
Expand Down
Loading
Loading